Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php-how to delete files from directory if files already exist?

Tags:

php

I tried deleting file if its already existing .

But i ended up with no result.

Can any one help me with this!!!

$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';
if (!file_exists($path_user)) {
    if (mkdir( $path_user,0777,false )) {
        //
    }
} 

unlink($path_user);

if(move_uploaded_file($file['tmp_name'],$path_user.$path)){
    echo "Your File Successfully Uploaded" . "<br>";
}
like image 336
R9102 Avatar asked May 26 '16 10:05

R9102


People also ask

How can you delete file from PHP?

In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only: file name. It is similar to UNIX C unlink() function. PHP unlink() generates E_WARNING level error if file is not deleted.

Which function is used to delete an existing file in PHP?

The unlink() function deletes a file.


2 Answers

Organize your code, try this:

$path = 'filename.ext'; // added reference to filename
$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';

// Create the user folder if missing
if (!file_exists($path_user)) {
   mkdir( $path_user,0777,false );
}
// If the user file in existing directory already exist, delete it
else if (file_exists($path_user.$path)) {
   unlink($path_user.$path);
}

// Create the new file
if(move_uploaded_file($file['tmp_name'],$path_user.$path)) {                 
    echo"Your File Successfully Uploaded"."<br>";
}

Keep in mind that PHP will not recursively delete the directory contents, you should use a function like this one

like image 153
Nil Llisterri Avatar answered Oct 21 '22 02:10

Nil Llisterri


Maybe you missing else condition ?? And file_name variable :

$file_name = 'sample.jpg';

$path_user = '/wp-content/plugins/est_collaboration/Files/'.$send_id.'/';

if (!file_exists($path_user.$file_name)) 
{                   
  if (mkdir( $path_user,0777,false )) {

  }

} else {

  unlink($path_user.$file_name);
}
like image 29
SonDang Avatar answered Oct 21 '22 00:10

SonDang