PHP Filesystem delete() Function



The PHP Filesystem delete() function is not included in PHP. However, PHP offers a number of methods for deleting files or data, depending on the type of deletion required.

To delete a particular file you can use the unlink() function. Take a look at unset() to remove a variable from the local scope.

The delete() function is now deprecated in PHP.

Syntax

Below is the syntax of the PHP Filesystem delete() function −

void delete ( string file )

Parameters

The parameter needs to use the delete() function is mentioned below −

Sr.No Parameter & Description
1

file(Required)

The file that you want to delete.

Return Value

The delete() function returns null if the given file has been successfully deleted.

Example

So in this example we will use unlink() at place of PHP Filesystem delete() function. The unlink() function will basically delete the associated file from the directory.

<?php
   $file = "/Applications/XAMPP/xamppfiles/htdocs/mac/myfile.txt";

   if (file_exists($file)) {
      unlink($file);
      echo 'File deleted successfully';
   } else {
      echo 'File not found';
   }
?>

Output

Following is the outcome of the above code −

File deleted successfully

Example

To remove data from a database, we mostly use a SQL DELETE command with PHP's database utilities, like MySQLi or PDO.

<?php
   $servername = "localhost";
   $username = "username";
   $password = "password";
   $dbname = "database";

   // Create connection
   $conn = new mysqli($servername, $username, $password, $dbname);

   // Check connection
   if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
   }

   $sql = "DELETE FROM tablename WHERE id=1";

   if ($conn->query($sql) === TRUE) {
      echo "Record deleted successfully";
   } else {
      echo "Error deleting record: " . $conn->error;
   }

   $conn->close();
?> 

Output

This will produce the following result −

Record deleted successfully

Summary

For file we can use unlink() to delete files. And for database records we can use SQL DELETE with database functions like MySQLi or PDO.

php_function_reference.htm
Advertisements