move_uploaded_file() won't replace existing image

A better way would be un-linking the file if it exists

if(file_exists('your-filename.ext')) {
    chmod('your-filename.ext',0755); //Change the file permissions if allowed
    unlink('your-filename.ext'); //remove the file
}

move_uploaded_files($_FILES['image']['tmp_name'], 'your-filename.ext');

If move_uploaded_file fails, it returns false. In that case, no SQL is executed at all, so mysql_error, which is echoed in the else branch, indeed won't output an error.

if move_uploaded_file fails, it issues a warning, that will become visible depending on your PHP settings. However, this problem doesn't have anything to do with MySQL.

If you try to explicitly delete the target file first, if it exists. Check with file_exists and then with unlink to delete the file. If unlink fails, it's probably a permissions issue than won't allow you to delete or overwrite the file.


No, your logic is wrong.. take a look at the URL of your profile image, either here, in facebook or twitter..do you see they use a fixed predictable name ? They don't, and there is a very good reason for that, you need unique, unpredictable filenames.

Try this:

$file = hash('sha256', openssl_random_pseudo_bytes(8)) . 'yourallowedextension';

Then query the name of the old picture from your database, after that, upload the new pic, if that succeeds, update the user's profile picture in the database and unlink() the old file using the information previously obtained if any.

Ensure that you are not allowing to upload php files or any other nasty stuff, for that you can use php fileinfo extension.

Tags:

Php