类中使用绝对路径调用yaml_parse_file失败,全局调用正常
解决类内读取YAML配置文件失败的问题
问题现象
全局作用域调用yaml_parse_file能正常读取/var/www/omeglall/yaml/connection.yaml,但在MySQL类内部调用该函数时,在register-ajax.php中实例化类会抛出「No such file or directory」错误。
相关代码
<?php // 全局调用正常 // var_dump(yaml_parse_file("/var/www/omeglall/yaml/connection.yaml")); class MySQL { private $HOST; private $PASSWORD; private $USER; private $DATABASE; private $con; // 路径确认正确 const CONNECTION_PATH="/var/www/omeglall/yaml/connection.yaml"; static private $connection_YAML; public function __construct() { try { $this->load_config(); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $this->con=new mysqli($this->HOST,$this->USER,$this->PASSWORD,$this->DATABASE); if($this->con->connect_error) { throw new Exception("Connection failed:". $this->con->connect_error); } $this->con->set_charset("utf8mb4"); }catch(Exception $e) { $error=$e->getMessage(); echo $error; } } public function getCon() { return $this->con; } private function load_config() { if(empty(self::$connection_YAML)){ // 此处调用失败 self::$connection_YAML=yaml_parse_file(self::CONNECTION_PATH); } $file=self::$connection_YAML; $this->HOST=$file["host"]; $this->USER=$file["user"]; $this->PASSWORD=$file["password"]; $this->DATABASE=$file["database"]; } } ?>
目录结构
项目根目录/var/www/omeglall/下:
yaml/目录(存放connection.yaml配置文件)- 包含上述
MySQL类的PHP文件 register-ajax.php(用于实例化MySQL类)
解决方案
1. 检查文件权限
运行PHP的用户(通常是www-data)需要有YAML文件及父目录的读取权限:
# 设置文件所属用户组 chown www-data:www-data /var/www/omeglall/yaml/connection.yaml # 设置文件可读权限 chmod 644 /var/www/omeglall/yaml/connection.yaml # 确保yaml目录也有读取权限 chmod 755 /var/www/omeglall/yaml
2. 排查SELinux限制(若服务器开启SELinux)
如果服务器启用了SELinux,可能会限制Web进程读取文件:
# 查看文件的SELinux上下文 ls -Z /var/www/omeglall/yaml/connection.yaml # 若上下文不是httpd_sys_content_t,执行以下命令修复 semanage fcontext -a -t httpd_sys_content_t "/var/www/omeglall/yaml(/.*)?" restorecon -Rv /var/www/omeglall/yaml
3. 修复静态变量判断逻辑
原代码中empty(self::$connection_YAML)会在第一次读取失败(返回false)后,后续不再尝试重新读取。修改判断逻辑并增加错误捕获:
private function load_config() { // 仅当变量为null时才尝试读取 if(self::$connection_YAML === null){ self::$connection_YAML = yaml_parse_file(self::CONNECTION_PATH); // 捕获读取失败的情况,抛出明确错误 if(self::$connection_YAML === false){ throw new Exception("无法加载配置文件: " . self::CONNECTION_PATH); } } $file=self::$connection_YAML; $this->HOST=$file["host"]; $this->USER=$file["user"]; $this->PASSWORD=$file["password"]; $this->DATABASE=$file["database"]; }
4. 验证路径正确性
在load_config方法中先输出路径,确认没有隐藏字符或拼写错误:
private function load_config() { var_dump(self::CONNECTION_PATH); exit; // ... 原有代码 }
内容的提问来源于stack exchange,提问作者iago guimaraes
相关产品推荐
相关产品推荐

