Home > Blockchain >  file_get_contents(/target/file/here/file.json): Failed to open stream: Permission denied in homepage
file_get_contents(/target/file/here/file.json): Failed to open stream: Permission denied in homepage

Time:12-30

I'm trying to read a json file from my php code by using file_get_contents but I get "Failed to open stream: Permission denied", but it worked when I tried to make selinux in Permissive mode. My is how I can allow file_get_contents to read files without turning on selinux in Permessive mode ?

Note : I'm using httpd server in redhat 7

Trying :

           $json = file_get_contents('/target/file/here/file.json');
           //modify json file
           file_put_contents('new_file.json', $Json_to_put);

Expecting :

1- file_get_content read my file.json 2- file_put_contents create my new_file.json

CodePudding user response:

You can try

  1. Change the owner of the webroot

    chown -R apache:apache /target/file/here

  2. Change the basic permissions

    chmod -R g w /target/file/here

    chmod g s /target/file/here

CodePudding user response:

  1. Permissions would need to be accessable
//Partial Headers from a 3rd party JSON based API I have access too
"headers":
  {"Access-Control-Allow-Headers":"Content-Type,
   Access-Control-Allow-Headers, 
   Access-Control-Allow-Origin, 
   Access-Control-Allow-Methods",
   "Access-Control-Allow-Origin":"*",
   "Access-Control-Allow-Methods":"GET",
   "Content-Type":"application/json"}

You can see the access allows origin of "*", control-method of "GET"

Also - you may want to decode the json..

$json = json_decode(file_get_content($url), false);
// False returns an Object and True returns an Array.

You're doing this from a file on the server, so this likely won't apply, but just for future reference - I've also run into problems when a 3rd party API (in JSON) is encoded, so watch for GZ Encoding, or other types of Encoding. The link I used to grab the above info is GZ encoded.

You should then be able to edit the data and file_put_content the data back to the file.

When you create the file, be sure to add the proper permissions. PHP File Create/Write

  • Related