Delete file on server php

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

Источник

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.

Источник

ftp_delete

ftp_delete() deletes the file specified by filename from the FTP server.

Parameters

Return Values

Returns true on success or false on failure.

Changelog

Examples

Example #1 ftp_delete() example

// set up basic connection
$ftp = ftp_connect ( $ftp_server );

// login with username and password
$login_result = ftp_login ( $ftp , $ftp_user_name , $ftp_user_pass );

// try to delete $file
if ( ftp_delete ( $ftp , $file )) echo » $file deleted successful\n» ;
> else echo «could not delete $file \n» ;
>

// close the connection
ftp_close ( $ftp );
?>

User Contributed Notes 4 notes

You can make a script delete itself with ftp_delete!

It’s pretty useful when creating an install script which you want to destroy at the end of the installation to prevent it from being run later.

On Linux machines, very often the user uploads third party scripts, and gets asked to CHMOD this and delete that manually because the webserver user is different from the FTP user ; make them enter their FTP info and get rid of the tedious file manipulation step!

Be careful, though. You will need to flush the output buffer and call ftp_delete at the end of the script, or else the script will die before it fully executes. Look up ob_end_flush for more info.

if you want to upload the file on server and thn do delete it.. this script works well

// connect and login data
$web = ‘111.111.111.111’ ;
$user = ‘123abc’ ;
$pass = ‘abc123’ ;
// file location
$server_file = ‘/public_html/upload/test.csv’ ;
$local_file = ‘test.csv’ ;
//connect
$conn_id = ftp_connect ( $web );
$login_result = ftp_login ( $conn_id , $user , $pass );
//uploading
if ( ftp_put ( $conn_id , $server_file , $local_file , FTP_BINARY ))

else

// try to delete $file
if ( ftp_delete ( $conn_id , $server_file )) echo » $server_file deleted successful\n» ;
> else echo «could not delete $server_file \n» ;
>

// close the connection
ftp_close ( $conn_id );
?>

$file = ‘public_html/plentyport.com/jobs/employee/resumes/4216:54:38Resume (1).docx’ ;
$ftp_server = «your server address» ;
// set up basic connection
$conn_id = ftp_connect ( $ftp_server );
$ftp_user_name = «your user server name» ;
$ftp_user_pass = «your server password» ;
// login with username and password
$login_result = ftp_login ( $conn_id , $ftp_user_name , $ftp_user_pass );

// try to delete $file
if ( ftp_delete ( $conn_id , $file )) echo » $file deleted successful\n» ;
> else echo «could not delete $file \n» ;
>

// close the connection
ftp_close ( $conn_id );
?>

Generally speaking, unlink will work just fine for most applications, however, if you are using multiple servers, you’re going to have to connect to the other server using FTP.

Источник

PHP Delete File From Server

InsideTheDiv

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

$delete = unlink($location_with_file_name); if($delete)< echo "delete success"; >else

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"; >>

Источник

Читайте также:  System arraycopy java примеры
Оцените статью