Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move_uploaded_file() won't replace existing image

Tags:

php

I'm using the script below, so user can upload their profile picture. The first time an image is uploaded (when the image doesn't exist at the location) it works great. However, if the image is already exist at the path (if the user tries to change the profile picture) the new image won't replace the old one. I do get success for the query.

Any help would be very appreciated!

Thanks

<?php

ini_set('display_errors',1);

 error_reporting(E_ALL);


require_once('db.php'); 


$name = $_POST['name']; 

   $dir = '../uploadImages/'; 
   $file = basename($_FILES['image']['name']);

   $uploadfile = $dir . $file;


    if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile))
    {


        $path = $name; 
        $path .= 'Image.png';       
        $query = mysql_query("UPDATE users SET imagePath='$path' WHERE username='$name'");

        if ($query)
        {
            echo 'success'; 
        }
        else 
        {
            echo 'error'; 
        }


    }
    else 
    {
        echo mysql_error(); 
    }


 ?>
like image 452
BlackMouse Avatar asked Mar 25 '12 08:03

BlackMouse


1 Answers

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');
like image 164
Kishor Kundan Avatar answered Sep 27 '22 21:09

Kishor Kundan