PHP How to write array values to a folder with file_put_contents

I am trying to write all values from array into a folder that I created. Here is my code:

     $dir = "images-folder/";

$new_array[] = array($row[0],$row[1],implode($url_array,','));

$files=$url_array;

foreach($files as $file){

    if (!file_exists($dir.$file)) {   
        file_put_contents($dir.$file, var_export($url_array, true));
    }
    else{
        continue;
    }

I got this error:

file_put_contents. failed to open stream.

The array is read fine and I used var_export to convert the array to a string, but still I am wondering why the file is not saved in the folder. Is there a way to use different logic here or convert the array in other way

Do you have write permission on “images-folder/” for the user running the script (probably apache if this is on a web page)? To make sure you are trying to create a “legal” file, add:

echo "File: " . $dir.$file . "<br>"

above the “file_put_contents” . This will echo out the actual file you are creating.

I have permission to write to the directory

If this is running as a web server page, then it’s not “your” permissions to write to the directory but the process running the script that needs permission.

You could try setting

$dir = “/tmp/”

And see if that works. If the files are created there, then look at the file owner.

I am running the script from the terminal so I think it is ok with that.

So whats an actual example value for $dir.$file?

Sponsor our Newsletter | Privacy Policy | Terms of Service