Ubuntu LAMP环境下PHP parse_ini_file与文件引入失效求助
Hey there! Let's break down why your parse_ini_file and require calls are failing—since your hardcoded credentials work perfectly, the issue is almost certainly tied to file permissions, PHP configuration restrictions, or a small oversight in how you're using the parse_ini_file function. Here's how to fix it step by step:
1. Fix File Permissions & Ownership First
Apache runs as the www-data user on Ubuntu, so your db.ini file needs to be readable by this user, and locked down securely to prevent unauthorized access:
- Set the file's owner to
www-data:sudo chown www-data:www-data /var/www/html/my_site/db.ini - Restrict permissions so only the owner can read/write it (this is critical for security):
sudo chmod 600 /var/www/html/my_site/db.ini
2. Add the Section Flag to parse_ini_file
Your db.ini uses a [database] section, but the default parse_ini_file call ignores sections unless you pass true as the second parameter. That's probably why you're getting an empty result! Update your code to:
$config = parse_ini_file('/var/www/html/my_site/db.ini', true); // Access values like this: $db_host = $config['database']['host']; $db_user = $config['database']['username']; $db_pass = $config['database']['password']; $db_name = $config['database']['dbname'];
3. Check PHP's open_basedir Restriction
PHP's open_basedir setting limits which directories scripts can access. If your site's directory isn't in this list, parse_ini_file will fail silently:
- Create a temporary
phpinfo.phpfile in your site directory:<?php phpinfo(); ?> - Access it via your browser (e.g.,
http://your-domain/phpinfo.php) and search for theopen_basedirentry. - If
/var/www/html/my_siteisn't included, edit your Apache PHP config (usually at/etc/php/7.2/apache2/php.ini—adjust the version number if needed):open_basedir = /var/www/html/:/tmp/ - Restart Apache to apply changes:
sudo systemctl restart apache2
4. Test for SELinux Restrictions (If Enabled)
Ubuntu 18.04 disables SELinux by default, but if you've enabled it, it might block Apache from reading your config file:
- Temporarily disable SELinux to test:
sudo setenforce 0 - If your script works now, apply a permanent SELinux rule to allow Apache access to your site directory:
sudo chcon -Rv --type=httpd_sys_content_t /var/www/html/my_site/ - Restart Apache afterward.
5. Debug with Error Messages
To get clear feedback on what's failing, add error checking to your code:
$config = parse_ini_file('/var/www/html/my_site/db.ini', true); if ($config === false) { $error = error_get_last(); echo "Failed to parse ini file: " . $error['message']; exit; }
This will show you exactly why the function is failing (e.g., permission denied, invalid file format).
内容的提问来源于stack exchange,提问作者llLeoll

