Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing error with file_get_contents permission denied

Tags:

json

php

curl

I have a question connected with JSON and PHP. So, if you visit this site: http://air.moepp.gov.mk/graphs/site/pages/MakeGraph.php?station=SkopjeRegion&parameter=PM10D&beginDate=2018-02-10&beginTime=19:00&endDate=2018-02-17&endTime=19:00&i=1518893212453&lang=en

As a return you get HTML, but if you go to the response, the response is pure JSON, so I'm trying to get the JSON data, but I fail. Probably I'm doing something wrong, but I don't know what. I tried with file_get_contents() and curl but I don't get anything from it... So here is what I'm trying to do:

<?php
$content = file_get_contents('http://air.moepp.gov.mk/graphs/site/pages/MakeGraph.php?station=SkopjeRegion&parameter=PM10D&beginDate=2018-02-10&beginTime=12:00&endDate=2018-02-17&endTime=12:00&i=1518865590001&lang=en');  
$contents = json_decode($content, true);  
var_dump($contents);

And as return I get NULL.

Edit:

I figured out that my PHP function file_get_contents() is not properly working because of the problem with the permission. The problem was:

file_get_contents('url'): failed to open stream: Permission denied in /var/www/html/xxx.php on line X

After googling, and suggestion from @geoidesic, I found out that SELinux (Security Enhanced Linux) is blocking Apache (by default network connection from httpd (Apache) is disabled. So i followed step-by-step tutorial on http://drib.tech/programming/php-file_get_contents-not-working and finally got it to work. Anyways, here is the solution in short if someone needs it:

  1. Be sure you have allow_url_fopen=On in your php.ini file. (If someone doesn't know where your php.ini file is, quick check with phpinfo() could get you everything.

  2. Check status of SELinux:

    sudo sestatus

    If the status is enabled , then you can check whether the boolean flags httpd_can_network_connect and httpd_unified are enabled, set to 1:

    sudo sestatus -b | grep httpd_can_network_connect and sudo sestatus -b | grep httpd_unified

    If they're off, run this command to set them on:

    sudo setsebool -P httpd_can_network_connect 1 sudo setsebool -P httpd_unified 1

    And then reboot, or restart httpd. So that's all, again, thanks a lot to the guy/s at drib.tech.

like image 201
Vladimir Danoski Avatar asked Feb 17 '18 19:02

Vladimir Danoski


1 Answers

I had the same issue just now and it was caused by selinux.

Resolved by running:

sudo setsebool -P httpd_can_network_connect 1
sudo setsebool -P httpd_unified 1
like image 106
HomeIsWhereThePcIs Avatar answered Nov 01 '22 18:11

HomeIsWhereThePcIs