pTutorial

New way to learn PHP

PHP 5 File delete

Delete file

You can delete the server file using unlink() function that take one argument that is path of the file. It return one (1) if file successfully deleted otherwise return zero (0). Syntax of unlink function are following below.

Syntax

unlink($location);	

$location: Location means file name with complete path. If file is in same folder then there is no need to give the complete path.

Example

<?php

$a=unlink("pt.txt");
if($a)
{
echo "File deleted successfully";	
}
else
{
echo "File not deleted";
}
?>

output

File deleted successfully

If file is not there unlink function return the warning massege like that Warning: unlink(uk1.txt): No such file or directory in D:\wamp\www\php\test.php


To suppress the warnning message we used @ sign in front of unlink function as shown in below example.

Example

<?php

$a=unlink("pt.txt");
if($a)
{
echo "File deleted successfully";	
}
else
{
echo "File not deleted";
}
?>

output

File not deleted

file_exists fuction

You can also use file_exists fuction to remove the warnning message. file_exist function is used to check the file is exsit or not shown in following example.

Example

<?php

$b = "pt.txt";
if(file_exists($b))
{
$a=unlink($b);
if($a)
{
echo "file deleted successfully.";	
}
else
{
echo "file not deleted.";
}
}
else
{
echo"There is no such file in this folder.";	
}

?>

output

There are no such file in this directory.

Note: You can use is_file function, that is more secure than file_exists function.


QUOTES OF THE DAY

Eat to live, and not live for eat.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER