PHP | Deleting files from local machine (unlink(): No such file or directory)

Assume following is the path on your system in which you want to delete some files through code (unlink function):

C:\wamp\www

Now if we use the same address in source variable (“C:\wamp\www”), it gives the following error:

unlink(): No such file or directory

This is because of \ in the path. To use this we need to escape \ with another \.

$source1= “C:\\wamp\\www\\”;

Sample code:

$source1= "C:\\wamp\\www\\";
if (is_dir($source1)) 
{
  $files1 = scandir($source1);
  $attachFiles = array_diff($files1, array('.', '..'));
  foreach($attachFiles as $file) // iterate files
  {  
   if(is_file($file))
   unlink($source1.$file); // delete file
  }//end foreach
}
  else 
      {
	 echo "No such directory";
      }

Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Web development or any other software development assistance please contact us at webdevelopment@webners.com

Leave a Reply

Your email address will not be published. Required fields are marked *