PHP Delete File From Server

Delete a file from server using PHP is so easy. You just need to unlink the file using the default PHP β€œunlink()” function. This function will take the file name with a complete path and return the true or false. It will return true if delete is successful otherwise false.
So, In this post, we will learn how to delete a file from a server if the file exists using the PHP unlink function.

php delete file from server

Deleting a file from a directory using the PHP unlink function.

If you want to delete the file from the front end, you need to pass the name of the file from the front end to the backend. Inside the PHP script(back-end), you need to catch the file name then pass the file name with the actual location in the unlink() function.

Note: before delete, make sure the "file exists" or not using the file_exists() function.

PHP check file exists or not.

if(file_exists($location_with_file_name)){
	echo "File Found";
}else{
	echo "File Not Found";
}

PHP File Delete using the unlink function

$delete  = unlink($location_with_file_name);
if($delete){
	echo "delete success";
}else{
	echo "delete not success";
}

PHP script to delete files on server

$file_name = $_POST['file_name']; // file name from front end
$location_with_image_name = "../upload/".$file_name;
if(file_exists($location_with_image_name)){
	$delete  = unlink($location_with_image_name);
	if($delete){
		echo "delete success";
	}else{
	echo "delete not success";
	}
}

Note: Make sure you upload file with unique name.

Still you face problems, feel free to contact with me, I will try my best to help you.