如果没有错误处理机制会怎样?
文件没有打开,但仍然向下执行,输出了ok
<?php
$file = fopen('./aaa.php','r');
echo 'ok';
/*
输出结果;
Warning: fopen(./aaa.txt): failed to open stream: No such file or directory in F:\wamp\www\test.php on line 2
ok
*/
添加错误处理机制
使用file_exists()函数检查文件或文件夹是否存在,返回值为bool
//添加了错误处理机制
if (!file_exists('./aaa.txt')){
echo '文件不存在,打开失败';
exit();
}else{
$file = fopen('./aaa.txt','r');
echo '文件打开成功';
fclose($file);
}
方式一:使用php默认处理方式
php会根据默认的逻辑来判断错误等级,决定程序是否继续执行,并输出错误信息
//die() 函数输出一条消息,并退出当前脚本
if (!file_exists('./aaa.txt')){
die('文件不存在,打开失败'