How to delete file in php

How to delete a file using PHP.

This is a short tutorial on how to delete a file using PHP.

To do this, we will be using the PHP function unlink.

For those of you who are not in the know, the unlink function takes in one parameter: The $filename.

This $filename parameter can contain a relative path or an absolute path to the file.

Let’s take a look at the following snippet, in which we delete a file called file.txt:

//Full path or relative path to the file that //you want to delete $filePath = ‘file.txt’; //Other examples of file paths that be used // «../file.txt» // «/home/storage/file.txt» // «uploads/file.txt» // «C:\wamp64\www\file.txt» //Delete the file using PHP’s unlink function $deleted = unlink($filePath); //If the file was deleted, unlink will //return a TRUE value if($deleted) < echo 'File ' . $filePath . ' was deleted!'; >//Otherwise, unlink will return FALSE else

If the file is successfully deleted, then the unlink function will return a boolean TRUE value.

However, if the file cannot be deleted, then it will return a FALSE value. Furthermore, a warning error will be omitted by PHP.

For example, if the file does not exist, then the following warning will occur:

Warning: unlink([filename]): No such file or directory in /path/to/file on line [line number]

As a result, it is probably a good idea to check if the file exists before you attempt to delete it.

Using PHP to delete a file if it exists.

In most cases, you will want to make sure that a file actually exists before you attempt to delete it. Thankfully, this is pretty easy to do with the is_writable function:

//If the file exists and is writeable if(is_writable($filePath))< //Delete the file $deleted = unlink($filePath); >

In the example above, our code will only attempt to delete the file if is_writable returns a TRUE value.

As a result, we can avoid any ugly E_WARNING messages.

The reason we used is_writable instead of is_file is that is_writable will help protect against permission issues.

This is because the function doesn’t just check to see if the file exists. It also checks to see if PHP has write access to the file. If PHP does not have write access to the file, then it will not be able to delete it.

If PHP does not have permission to delete the file in question, the following warning message will be omitted:

Warning: unlink([filename]) [function.unlink]: Permission denied

In cases like this, you will need to give PHP write access to the directory in question. However, that is far outside the scope of this article.

Delete a file if it is older than X days.

If you only want PHP to delete files that are older than a day, etc., then you can do something like this:

//Full path or relative path to the file that //you want to delete $filePath = 'file.txt'; //Get the last modified time of the file $lastModified = filemtime($filePath); //Get the current timestamp $now = time(); //Calculate the number of seconds that have passed //since the file was last modified. $secondsSince = $now - $lastModified; //There are 86400 seconds in a day. $deleteAfter = 86400; //If the file is older than a day if($secondsSince >= $deleteAfter) < if(is_writable($filePath))< unlink($filePath); >>

In the PHP snippet above, we got the file’s last modification date. If 86400 seconds have passed since the file was last modified, we will attempt to delete it.

Obviously, you can change this time period to suit your own needs. For example, if you wanted to delete the file if it was older than an hour, then you would change the $deleteAfter variable to 3600.

Источник

Deletes filename . Similar to the Unix C unlink() function. An E_WARNING level error will be generated on failure.

Parameters

If the file is a symlink, the symlink will be deleted. On Windows, to delete a symlink to a directory, rmdir() has to be used instead.

Return Values

Returns true on success or false on failure.

Changelog

Version Description
7.3.0 On Windows, it is now possible to unlink() files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed.

Examples

Example #1 Basic unlink() usage

$fh = fopen ( ‘test.html’ , ‘a’ );
fwrite ( $fh , ‘

Hello world!

‘ );
fclose ( $fh );

See Also

User Contributed Notes 12 notes

This will delete all files in a directory matching a pattern in one line of code.

Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS?

The unlink() is not about removing file, it’s about removing a file name. The manpage says: «unlink — delete a name and possibly the file it refers to».

Most of the time a file has just one name — removing it will also remove (free, deallocate) the `body’ of file (with one caveat, see below). That’s the simple, usual case.

However, it’s perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive’, so to say. Only when all the names are removed, the body of file actually is freed.

The caveat:
A file’s body may *also* be `kept alive’ (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there’s a fancy way of resurrecting a file removed by a mistake but still held open by a process.

unlink($fileName); failed for me .
Then i tried using the realpath($fileName) function as
unlink(realpath($fileName)); it worked

just posting it , in case if any one finds it useful .

Here the simplest way to delete files with mask

$mask = «*.jpg»
array_map ( «unlink» , glob ( $mask ) );
?>

To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function. Say I wanted to delete all jpgs .

foreach ( glob ( «*.jpg» ) as $filename ) echo » $filename size » . filesize ( $filename ) . «\n» ;
unlink ( $filename );
>

I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.

Though, I have been breaking my head for about an hour on why I couldn’t get my persmissions right to unlink the main file.

Finally I knew what was wrong: because I was working on the file and hadn’t yet closed the file, it was still in use and ofcourse couldn’t be deleted 🙂

So I thought of mentoining this here, to avoid others of making the same mistake:

// First close the file
fclose ( $fp );

// Then unlink 🙂
unlink ( $somefile );
?>

To anyone who’s had a problem with the permissions denied error, it’s sometimes caused when you try to delete a file that’s in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with «../»).

So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.

$old = getcwd (); // Save the current directory
chdir ( $path_to_file );
unlink ( $filename );
chdir ( $old ); // Restore the old working directory
?>

This might seem obvious, but I was tearing my hair out with this problem — make sure the file you’re trying to delete isn’t currently being used. I had a script that was parsing a text file and was supposed to delete it after completing, but kept getting a permission denied error because I hadn’t explicitly closed the file, hence it was technically still being «used» even though the parsing was complete.

if you’re looking for a recursive unlink:

/**
* delete a file or directory
* automatically traversing directories if needed.
* PS: has not been tested with self-referencing symlink shenanigans, that might cause a infinite recursion, i don’t know.
*
* @param string $cmd
* @throws \RuntimeException if unlink fails
* @throws \RuntimeException if rmdir fails
* @return void
*/
function unlinkRecursive ( string $path , bool $verbose = false ): void
if (! is_readable ( $path )) return;
>
if ( is_file ( $path )) if ( $verbose ) echo «unlink: < $path >\n» ;
>
if (! unlink ( $path )) throw new \ RuntimeException ( «Failed to unlink < $path >: » . var_export ( error_get_last (), true ));
>
return;
>
$foldersToDelete = array();
$filesToDelete = array();
// we should scan the entire directory before traversing deeper, to not have open handles to each directory:
// on very large director trees you can actually get OS-errors if you have too many open directory handles.
foreach (new DirectoryIterator ( $path ) as $fileInfo ) if ( $fileInfo -> isDot ()) continue;
>
if ( $fileInfo -> isDir ()) $foldersToDelete [] = $fileInfo -> getRealPath ();
> else $filesToDelete [] = $fileInfo -> getRealPath ();
>
>
unset( $fileInfo ); // free file handle
foreach ( $foldersToDelete as $folder ) unlinkRecursive ( $folder , $verbose );
>
foreach ( $filesToDelete as $file ) if ( $verbose ) echo «unlink: < $file >\n» ;
>
if (! unlink ( $file )) throw new \ RuntimeException ( «Failed to unlink < $file >: » . var_export ( error_get_last (), true ));
>
>
if ( $verbose ) echo «rmdir: < $path >\n» ;
>
if (! rmdir ( $path )) throw new \ RuntimeException ( «Failed to rmdir < $path >: » . var_export ( error_get_last (), true ));
>
>
?>

On OSX, when fighting against a «Permission Denied» error, make sure, the directory has WRITE permissions for the executing php-user.

Furthermore, if you rely on ACLs, and want to delete a file or symlink, the containing directory needs to have «delete_child» permission in order to unlink things inside. If you only grant «delete» to the folder that will allow you to delete the container folder itself, but not the objects inside.

unlink works the same as the rm command on nix based loses or del command on windows, it will not resolve the file but remove the exact path given even if that path is just a link.

E.G
/var/www/test/index.php = symlink(/home/test/www/index.php)
unlink ( «/var/www/test/index.php» );
?>
Will just delete the link, not the original file where as
unlink ( «/home/test/www/index.php» );
?>
Will unlink the original file path and break the symlink, and allow the system to overwrite as the filesystem will not know of the file’s location anymore.

The best way to delete files by mask is as follows:
array_walk ( glob ( ‘/etc/*’ ), ‘unlink’ );
?>
Do not use array_map mentioned below — it’s purpose is to process values in a given array AND COLLECT data returned by the callback function. So, array_map is slower and uses additional memory compared to array_walk.

Источник

PHP Delete File

Summary: in this tutorial, you will learn how to delete a file in PHP using the unlink() function.

Introduction to the PHP delete file function

To delete a file, you use the unlink() function:

unlink ( string $filename , resource $context = ? ) : boolCode language: PHP (php)

The unlink() function has two parameters:

  • $filename is the full path to the file that you want to delete.
  • $context is a valid context resource.

The unlink() function returns true if it deletes the file successfully or false otherwise. If the $filename doesn’t exist, the unlink() function also issues a warning and returns false .

PHP delete file examples

Let’s take some examples of using the unlink() function.

1) Simple PHP delete file example

The following example uses the unlink() function to delete the readme.txt file:

 $filename = 'readme.txt'; if (unlink($filename)) < echo 'The file ' . $filename . ' was deleted successfully!'; > else < echo 'There was a error deleting the file ' . $filename; > Code language: HTML, XML (xml)

2) Delete all files in a directory that match a pattern

The following example deletes all files with the .tmp extension:

 $dir = 'temp/'; array_map('unlink', glob("*.tmp"));Code language: HTML, XML (xml)
  • First, define a variable that stores the path to the directory in which you want to delete files.
  • Second, use the glob() function to search for all files in the directory $dir that has the *.tmp extension and pass it result to the array_map() function to delete the files.

Generally, you can change the pattern to delete all matching files in a directory using the array_map() , unlink() and glob() functions.

Summary

Источник

Читайте также:  Php win 10 установка
Оцените статью