Friday, January 4, 2013

How To Creating and Deleting Files Through Code in PHP

We can create or delete files through code using the touch() function to create them, and the unlink() function to delete them. Both functions are part of the Filesystem family of functions. You can check to see whether a file exists before you attempt either function, and you can also check to see if the file exists to verify that touch created it for you if it was not already there.

touch() will create the file if it does not exist already.

unlink() will delete any type of file from your server.

Here is an example showing how to use the touch() function to create a file:
Learn HTML
<?php  // you can create any extension type file(html, php, xml, etc...)
$file_x "my_file.txt"
$createFile touch($file_x);

if (
file_exists($file_x)) {
    echo 
"The file has been created";
} else {
    echo 
"The file has not been created";
}
?>

Develop PHP browser display window
The file has been created


Here is an example showing how to use the unlink() function to delete a file:
Learn HTML
<?php  // you can delete any extension type file(html, php, jpg, gif, flv, swf, etc...)
$file_x "my_file.txt";

if (
file_exists($file_x)) {

    
unlink($file_x); // delete it here only if it exists
    echo "The file has been deleted";

} else {
    echo 
"The file was not found and could not be deleted";
}
?>

Develop PHP browser display window
The file has been deleted

Retweet this story

No comments:

Post a Comment