I modify a file using GD in PHP and am currently saving it with the code below. However, the code below does not overwrite an existing file. What do I need to do to overwrite an existing file or one exists or create a new file otherwise. I tried file_put_contents($target_path1,$temp)
as suggested in this question but that does not seem to work for GD images. Thanks in advance for any suggestions.
imagecopyresampled($temp, $image, 0, 0, 0, 0, $neww, $newh, $oldw, $oldh);
$target_path1 = "../tempfiles/";
$target_path1 = $target_path1 . $usertoken. "-tempimg.png";
imagepng($temp, $target_path1);//saves file temp to the targetpath
Use the function imagepng()
as you are doing.
If it doesn't exist an image it creates a new one.
By default it will overwrite the file if it already exists.
The problem you are talking about in my opinion is related to the file permissions or the way the file path is handled.
@Jakkapong Rattananen
"I think your user that use for run php doesn't has permission to write to your file path."
I think the same.
Your user must have permissions or the path must be writeable.
To be sure set it up to 666 or better to 777.
Take a look at the complete code to do what you want to do
// Resizing or modifying the image
imagecopyresampled($temp, $image, 0, 0, 0, 0, $neww, $newh, $oldw, $oldh);
$path = "../tempfiles/"; //it's yout path $target_path1
$path .= $usertoken . "-tempimg.png"; //adding your filename dynamically generated
// CHECK PERMISSIONS - Ensure the directory exists and is writable !!!!!!!!!
if (!is_dir(dirname($path))) {
mkdir(dirname($path), 0755, true); // Create the directory (if it doesn't exist)
}
// CHECK PERMISSIONS - Make sure the file can be overwritten !!!!!!!!!
if (file_exists($path) && !is_writable($path)) {
chmod($path, 0666); // Also make sure you have permission to do this
}
// THEN FINALIZE
// Save the image, overwriting if it exists
imagepng($temp, $path);
// Cleanup for memory saving
imagedestroy($temp);
imagedestroy($image);
It's basically your code, but improved. So in this way you check if you have permissions (hopefully so).
If you want to be sure or know what's going on, add some else
with echo
or returns
where you see // CHECK PERMISSIONS
.
Also check that the characters contained in $usertoken
are allowed by your machine system.
Good Work