修复file_get_contents权限拒绝问题及PHP获取指定URL JSON数据失败求助
1. Fixing file_get_contents() Permission Denied Error
Let’s break down the most common causes and actionable fixes for this error:
Check File/Directory Permissions:
Make sure the file or directory you’re trying to access has the right permissions for your web server user (usuallywww-datafor Apache,nginxfor Nginx). Usechmodto set read permissions (e.g.,chmod 644 your-file.txtfor files,chmod 755 your-directory/for folders). You might also need to adjust ownership withchown www-data:www-data your-file.txt.Check
open_basedirRestriction:
Your PHP config might haveopen_basedirenabled, which limits which directories PHP can access. Look for this directive inphp.ini(or.htaccess/user.inifor per-site settings) and update it to include the path you need, or disable it if it’s safe to do so.SELinux Interference:
If you’re on a system with SELinux (like CentOS/RHEL), it could be blocking PHP from accessing files. Test this temporarily by runningsetenforce 0—if the error goes away, adjust SELinux policies (e.g.,chcon -R -t httpd_sys_content_t /path/to/your/filesto mark the directory as web-accessible).Alternative: Use
curlInstead:
Iffile_get_contentsis restricted (e.g.,allow_url_fopenis disabled), switching tocurloften bypasses these limits, especially for remote URLs.
2. Retrieving JSON from the Specified URL
The problem here is almost certainly that the target server expects a valid User-Agent header. Many servers block requests without a proper user agent (like the empty default from file_get_contents or unconfigured curl), returning an HTML error page instead of JSON.
Fix with file_get_contents():
Add a custom context with a User-Agent header:
$url = "http://air.moepp.gov.mk/graphs/site/pages/MakeGraph.php?station=SkopjeRegion¶meter=PM10D&beginDate=2018-02-10&beginTime=19:00&endDate=2018-02-17&endTime=19:00&i=1518893212453&lang=en"; // Create context with a valid User-Agent $context = stream_context_create([ 'http' => [ 'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' ] ]); $jsonData = file_get_contents($url, false, $context); if ($jsonData === false) { // Debug the error $error = error_get_last(); echo "Error fetching data: " . $error['message']; } else { $data = json_decode($jsonData, true); // Process your JSON here print_r($data); }
Fix with curl:
This is often more reliable for remote requests, as it gives you better control over headers and options:
$url = "http://air.moepp.gov.mk/graphs/site/pages/MakeGraph.php?station=SkopjeRegion¶meter=PM10D&beginDate=2018-02-10&beginTime=19:00&endDate=2018-02-17&endTime=19:00&i=1518893212453&lang=en"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects if needed $jsonData = curl_exec($ch); if (curl_errno($ch)) { echo "Curl error: " . curl_error($ch); } else { $data = json_decode($jsonData, true); print_r($data); } curl_close($ch);
Extra Checks:
- Ensure
allow_url_fopenis enabled inphp.iniif you’re usingfile_get_contentsfor remote URLs. - If the server still doesn’t return JSON, try adding an
Accept: application/jsonheader to your request. - Verify your server isn’t blocked by the target site’s firewall (test from a different IP if you keep getting failures).
内容的提问来源于stack exchange,提问作者Vladimir Danoski

