How to delete file in php? Unlink PHP - delete files How to delete PHP file

PHP is a programming language that is mainly used to create dynamic Web pages. As well as any other programming language, PHP contains a lot of opportunities, among which are very useful. For example, the ability to delete a file you can use in your scripts.

This advice will help you learn how delete file in php Using a function unlink.

Step-by-step instruction:

You can use the function to delete a file in PHP unlink. On the example of a simple script, we will analyze work unlink:

  1. Create a text file in a text editor (VI / VIM, Nano, Gedit or simply in standard notebook).
  2. Dial or simply copy the following code into it:$ file \u003d "example.log";
    unlink ($ File);
    ?>
  3. Save (for example, under the name testunlink.php) and place the created script file on your test Web server. In the same directory, create an example.log file with any content. It is we will delete it.
  4. Run the script by calling it in the browser, and looking again to the directory, you will find that the file example.log is no longer there. Unlink Made his job!

How it all works:

The first row of the script code: Determine the type of our script.

The second line of code: After starting the script created by us, the File variable will be assigned the value example.log. (Note that the file with the same name must be present in the same directory as the script we created. Just create it with any content!).

The third line of code: Delete the example.log file by passing it as an unlink function argument.

The fourth row of the script code: the end of the PHP code.

Often, when creating a program, there is a need to delete files (causes can be the most different) and in this case, Unlink PHP comes to help us. Today we will learn to delete files in PHP and consider several examples.

Delete files using Unlink PHP

To delete files, the Unlink () function is used. The syntax of this feature is as follows:

unlink (File Name)

This function is logical and therefore, in the case of successful deletion of the file, returns TRUE, and in case of failure - FALSE. Consider use unlink () For example:

It should be noted that when reloading this page, the program will give an error. This is due to the fact that when the function is first calling, it has already deleted the file and the next time it cannot detect it.

There are several ways to solve this problem. For example, you can use a more complex internal architecture of the program, using conditional IF statements. Or it is enough to put the @ symbol in front of the function itself to ignore emerging errors. In this case, even if the file is not detected, the error will not be initiated:

Delete files in PHP with Unlink is not at all difficult, as they say, breaking - do not build. Next time we will learn to check the status of the files.

Let's try to solve a simple task to delete one file or multiple files with PHP. In general, there is nothing complicated here, but there is a lot of details, as well as options for solutions that you need to know. In my article, I do not undertake to argue the immense, but express a couple of questions and bring some examples, I think I can. Let's proceed?

PHP function unlink ()

And I will start with the PHP functions unlink (), which also deletes the file:

bOOL unlink(string $ FileName [ resource. $ context])

Here $ filename - path to the file, and $ context (optional) - description of contexts to work with threads (supported in PHP, starting with 5.0.0). The function returns TRUE in case of successful completion or false in case of error.

An example of using PHP functions Unlink ():

$ filename \u003d "./path/to/file.txt";

Why is this function called unlink ()?

The fact is that in the UNIX file system there is a distinction between the physical location of files on the carrier and the corresponding directory structure. Therefore, when saving a file at a specific point of the file system, this point of the directory tree is associated with the physical storage location of the file. In other words, the path to the file in UNIX, in fact, is a unique identifier for one of these nodes.

It is noteworthy here that in UNIX you can associate several such points with the same data. Taki data will exist until there is at least one link to them. But if all links are destroyed, then the data themselves will be destroyed. Thus, the unlink () function is designed to delete exactly links, and already as a result of the file data.

There is no such thing in Windows and the Unlink () function deletes the file. Moreover, some of PHP versions for Windows do not support Unlink (). In this case, the DEL command is used via System () or Exec (), for example:

$ filename \u003d "/2014/04/file.txt";
if (ISset ($ _ env ["windir"])) (
@Exec ("Del". $ FileName);
if (File_exists ($ FileName)) DIE ("Error Delete File");
) ELSE if (! (@ unlink ($ filename))) (
DIE ("Error Delete File");
}

In this case, the $ _env environment variable ["WINDIR"] can serve marker Using a Windows Platform, and checking the execution of a file deletion through the File_existS () PHP function, which carries out the existence of the file.

How to delete file (s) in PHP?

In some cases, it may turn out that the unlink () function will not have access to the deletion of the file, i.e. We get a mistake : Permission Denied.. This may be associated with the wrong way to file or the lack of access rights.

An interesting option to work with the paths to the file is the use of GETCWD PHP functions () (Gets the name of the current working directory) and CHDIR () (Changes the current directory to the specified), eg:

$ File_Path \u003d "Path / To";
$ file_name \u003d "/2014/04/file.txt";
$ old \u003d getcwd ();
if (! (@ CHDIR ($ file_path))) DIE ("Error Open Path.");
if (! (@ Unlink ($ file_name))) DIE ("Error Delete File");
cDIR ($ old);

As you can see, so something easier to navigate and track the problem. At the same time, it will not be superfluous after the deletion returns to the current $ old catalog.

As for access problems, you can try to use php-function chmod () (Changes file access mode), eg:

$ filename \u003d "/2014/04/path/to/file.txt";
@chmod ($ FileName, 0666);
if (! (@ unlink ($ filename))) DIE ("Error Delete File.");

If you need delete all files in the directory It is convenient to use a combination of PHP functions array_map () (Applies Callback function to all elements of the array) and glob () (finds file paths that match the template), eg:

array_map ("Unlink", Glob ("Some / Dir / *. TXT"));

Solving the problem of multithreading when deleting files

It is much more difficult when it comes to major sites where the number of simultaneous queries (streams) to the script is large. There are a number of solutions here. I will give only one of them, the main on use semaphore.

As such, semaphore Serves peculiar marker process. When capturing the semaphore in one process, its value decreases per unit, and when released - increases by one. At the same time, if the current value of the semaphore is zero, the process will not be able to capture it and it will expect the release of the semaphore.

For the semaphore resource, the SEM_GET () function is used. A function can be obtained by a semaphore with a value that differs from one, and then semaphore will be able to capture semaphore. The capture uses the SEM_ACQUIRE () function. Example:

$ SEM \u003d SEM_GET (1);
if (SEM_ACQUIRE ($ SEM) && File_exists ($ FileName)) @unlink ($ FileName);
sEM_REMOVE ($ SEM);

Pay attention to the fact that an additional check is used here to exist File_exists () file. The fact is that when the first thread will capture the semaphore, deletes the file and release the semaphore, the second stream will be able to continue execution without deleting a file that is no longer.

An important role is played by the SEM_REMOVE () function, which lets the occupied semaphore. If the semaphore is not released, then the parallel stream will remain in the standby state until the end of the current work. Therefore, the function must be outside the condition.

I have everything on this. Hope my article was useful to you or just informative. Thanks for attention. Good luck!

at 8:00 Edit Message

8 Years Ago.

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 "Sue 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 ...

10 Years Ago.

I Have Been Working On Some Little Tryout Where a Backup File Was Created Before Modifying The Main Textfile. 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);
?>

14 YEARS AGO.

To Delete All Files of a Particular Extension, OR Infact, Delete All 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);
}

?>

10 Years Ago.

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 Higer in the Hierarchy to Your Working Directory (Ie 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 \u003d getcwd (); // Save the Current Directory
cHDIR ($ Path_TO_FILE);
unlink ($ FileName);
cDIR ($ old); // Restore the Old Working Directory
?>

4 Years Ago.

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 WANE "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.

4 Years Ago.

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.

11 Years Ago.

Ggarciaa "s Post Above Has Already One Small Error, Closedir Has to Be Used Even if $ Deleteme is False











}

Closedir ($ DH);
if ($ deleteme) (
@ rmdir ($ dir);
}
}

?>

9 Monhs Ago.

Handling "Resource Unavailable" Error by Unlink () AS Exception Using Try Catch

Even is_file () OR File IS EXISTIS () Will Check for File IS EXISTS OR NOT, THERE ARE CHANCES THAT FILE IS BEING USED by Some Applications That Will Prevent Deletion and Unlink () Will Display "Resource Unavailable" Error.

So After Trying Many Methods Like: `Is_Resource ()`, `is_writable ()`, `stream_get_meta_data ()` ... etc, i reached the only best way to handle error while * "deleting" * a file that is either * * Not exists ** or ** IS EXISTS But Being Used by Some Application **

function Delete_File ($ PFILENAME)
{
if (File_exists ($ PFILENAME)) (
// Added by Muhammad.begawala
// "@" Will Stop Displaying "Resource Unavailable" Error Because of File Is Open Some Where.
// "Unlink ($ PFILENAME)! \u003d\u003d True" Will Check if File Is Deleted Successfully.
// Throwing Exception SO That We Can Handle Error Easily Instead of Displaying to Users.
if (@unlink ($ pfileName)! \u003d\u003d TRUE)
Throw New Exception ("Could Not Delete File:" $ PFILENAME. "Please Close All Applications That A using it.");
}
RETURN TRUE;
}

/ * \u003d\u003d\u003d usage \u003d\u003d\u003d * /

try (
if (delete_file ("hello_world.xlsx") \u003d\u003d\u003d TRUE)
Echo "File Deleted";
}
catch (Exception $ E) (
Echo $ e-\u003e getMessage (); // Will Print Exception Message Defined ABOVE.
}

11 Years Ago.

Ggarciaa "s Post Above Has One Small Error, It Will Ignore File And Directory Strings That Are Evaluated As False (IE." 0 ")

Fixed Code IS Below (False! \u003d\u003d)

// Ggarciaa at Gmail Dot COM (04-July-2007 01:57)
// I Needed to Empty A Directory, But Keeping It
// So i SLightly Modified The Contribution From
// Stefano at Takys Dot IT (28-Dec-2005 11:57)
// A Short But Powerfull Recursive Function
// That Works Also IF The Dirs Contain Hidden Files
// $ Dir \u003d The Target Directory
// $ Deleteme \u003d If True Delete Also $ Dir, if false leve it alone

FUNCTION SUREREMOVEDIR ($ dir, $ deleteme) (
if (! $ DH \u003d @ OpenDir ($ dir)) Return;
While (False! \u003d\u003d ($ OBJ \u003d READDIR ($ DH))) (
if ($ OBJ \u003d\u003d "." || $ OBJ \u003d\u003d "..") Continue;
if ( [Email Protected] Unlink ($ dir. "/" $ OBJ)) SUREREMOVEDIR ($ dir. "/". $ OBJ, TRUE);
}
if ($ deleteme) (
closedir ($ DH);
@ rmdir ($ dir);
}
}

// SUREREMOVEDIR ("EMPTYME", FALSE);
// SUREREMOVEDIR ("REMOVEME", TRUE);

?>

8 Years Ago.

Unlink Can Fail After Using ODBC Commands on the File.

NeiTher. NOR. DID THE TRICK.

ONLY. Released The File Such That It Could Be Deleted Afterwards ...

We continue the lesson that is dedicated to the topic " Working with PHP files" If you did not read the previous one, I recommend to read, but those who read, moving on. In this lesson, you will learn to delete the created or existing file using PHP, copy or rename, block the file.
Well, if you are ready, then in battle ...

Deleting a file on PHP

If you need to delete any file, use the php function unlink ():

Unlink (File name);

File name - here specify the name of the file to be deleted.

Let's write down, we need to delete the file "file.txt", an example for filling will be this:

Unlink ("file.txt");

Ready code:



If the file "file.txt" was present, the script is removed.

Copying a file on PHP

If you need from a single file to recharge the contents to another file, use the php function Copy ().

Copy ("File1", "File2");

File1 - the file name from where the text will be copied
- File2 - file name where text will be copied

For example, create a file called "file2.txt" on the local server in the "TEST-1" folder. Let the file be empty. Now insert this code copy ("File.txt", "file2.txt"); In php code "file.php":



What did we do? Created through the PHP file called "file.txt", recorded in the file "file.txt" through PHP " I am glad to see you on the blog site "Displayed the result in the browser, copied the text from the file" file.txt "and inserted into the file" file2.txt ". Do not believe that everything happened? Do you remember that file "file2.txt" was empty?! Open it! And what do you see? Yes, right, the text that was in the file "file.txt":

Rename file to PHP

To make the file renaming, use the PHP function RENAME ():

RENAME ("File1", "File2");

File1 - the name of the file to be replaced ( rename)
- File2 - Here you need to give a new file name

Example for filling this:

RENAME ("File2..txt");

Here is a ready code:



File "file2.txt" is renamed to the "Site.txt" file.

On this, I think you should finish our lesson. But this is not all, in the next lesson, will continue working with files.

Did you like the article? To share with friends: