Error creating a file with fopen

2

When trying to create a JSON file with fopen me, a permission error is returned with the following message:

  Warning: fopen (/json/9.json): failed to open stream: No such file or directory in C: \ xampp \ htdocs \ apil \ Controllers \ Classex.php on line 120

As I use the Windows operating system, I have already given permission on the folder that I left pre-created, however, the problem still persists.

Permission I gave everyone on the JSON file by right-clicking on the file-> Properties-> Share:

ThecodeI'musingtoperformthefilecreationandlatersavethedatatoitfollows:

protectedfunctionfilejson($product_id,$account_id){$file=array($account_id);$json=fopen("/json/" . $product_id . ".json", "w");
    fwrite($json, json_encode($file));
    fclose($json);
}

And I call the method in another method that is in the same class as follows:

 Classex::filejson($product_id, $this->getAccount_id());

It should be noted that both $product_id and $account_id faces have the correct content or are not null.

I'm using XAMPP in Windows 10.

    
asked by anonymous 20.09.2018 / 15:36

1 answer

3

First, and important:

Sharing is not a folder permission. Sharing is allowed to access the folder of another PC (and modify its source inclusive).

Folder Permission is by clicking Properties > Security

Second:

There is a bar at the beginning of the path, fopen is relative to the file system, not the root of the site:

$json = fopen("/json/" . $product_id . ".json", "w");
//             ^

If you want path relative to the file you run, you can use this:

$json = fopen("json/" . $product_id . ".json", "w");

Or so:

$json = fopen("./json/" . $product_id . ".json", "w");

Even though, you need to make sure that you are running the script in the correct folder, and that nothing in this code has changed the working directory.

An alternative would be to use some environment variable to produce the complete path:

$root = $_SERVER['DOCUMENT_ROOT']; // Equivale ao "/" do site, dependendo 
                                   // do jeito que foi configurado o servidor
                                   // No seu caso vai retornar algo como: C:/xampp/htdocs

$json = fopen("$root/json/" . $product_id . ".json", "w");
    
20.09.2018 / 15:44