After an image is uploaded with PHP, I want to make the image file writable in order to add a watermark to it . Here are the codes I used:
if(isset($_FILES['file_poster']['tmp_name']) && $_FILES['file_poster']['tmp_name'] != '') {
$random_filename = substr(md5(time()), 0, 9);
$ext = '.jpg';
if(strpos(strtolower($_FILES['file_poster']['name']), '.png') > -1) {
$ext = '.png';
}
move_uploaded_file($_FILES['file_poster']['tmp_name'], 'uploads/' . $random_filename . $ext);
chmod(ABS_PATH . $random_filename, 0666);
$random_filename = 'uploads/' . $random_filename . $ext;
// add watermark codes omitted
}
After the file is uploaded, the file permission becomes 644. Then I tried to use chmod()
to change it to writable ( 666 ), but the permission doesn't change.
The /uploads
folder has permission 777. Is there any reason that makes chmod()
function fails to change permission? or is there a workaround?
Note: PHP 5 is used. GD is working properly.
Looks like you need to swap your last two lines, eg
$random_filename = 'uploads/' . $random_filename . $ext;
chmod(ABS_PATH . $random_filename, 0666);
Be very careful when using relative paths such as 'uploads/' . $random_filename . $ext
. If the working file is included into another file, the current directory may differ.
I would recommend something like this
$destFile = __DIR__ . '/uploads/' . $random_filename . $ext;
move_uploaded_file($_FILES['file_poster']['tmp_name'], $destFile);
chmod($destFile, 0666);
where the magic __DIR__
constant always contains the absolute path to the parent directory of the file you're actually in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With