how to delete a file from folder in php - php

I have a folder 'items' in which there are 3 files item1.txt, item2.txt and item3.txt.
I want to delete item2.txt file from folder. I am using the below code but it not deleting a file from folder. Can any body help me in that.
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($file);
}
}
closedir($dirHandle);
?>

Initially the folder should have 777 permissions
$data = "item2.txt";
$dir = "items";
while ($file = readdir($dirHandle)) {
if ($file==$data) {
unlink($dir.'/'.$file);
}
}
or try
$path = $_SERVER['DOCUMENT_ROOT'].'items/item2.txt';
unlink($path);

No need of while loop here for just deleting a file, you have to pass path of that file to unlink() function, as shown below.
$file_to_delete = 'items/item2.txt';
unlink($file_to_delete);
Please read details of unlink() function
http://php.net/manual/en/function.unlink.php

There is one bug in your code, you haven't given the correct path
<?php
$data="item2.txt";
$dir = "items";
$dirHandle = opendir($dir);
while ($file = readdir($dirHandle)) {
if($file==$data) {
unlink($dir."/".$file);//give correct path,
}
}
closedir($dirHandle);
?>
unlink

if($file==$data) {
unlink( $dir .'/'. $file);
}

It's very simple:
$file='a.txt';
if(unlink($file))
{
echo "file named $file has been deleted successfully";
}
else
{
echo "file is not deleted";
}
//if file is in other folder then do as follows
unlink("foldername/".$file);

try renaming it to the trash or a temp folder that the server have access **UNLESS IT'S sensitive data.
rename($old, $new) or die("Unable to rename $old to $new.");

Related

php rmdir or unlink file from folder

The following code deletes the files in a folder uploads.How do I delete the folder as well when a user clicks Delete Folder (or similar).
I tried using rmdir but I am not getting errors only blank move.php file.
What's the correct/recommended way of doing it ? Please advice.
<?php
$actfolder = $_REQUEST['folder'];
require_once("models/config.php");
if(!securePage($_SERVER['PHP_SELF'])){
die();
}
require("models/db-settings.php");
if(isset($_GET['file'])){
$filename = "uploads/$loggedInUser->username$actfolder/" . ltrim($_GET['file'], '/\\');
// make sure only deleting a file in files/ directory
if (dirname(realpath($filename)) == realpath("uploads/$loggedInUser->username$actfolder/")) {
unlink($filename);
}
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Just try something like this:
$filename = "uploads/$loggedInUser->username$actfolder/";
if (is_dir($filename) === true)
{
$files = array_diff(scandir($filename), array('.', '..'));
foreach ($files as $file)
{
unlink(realpath($filename) . '/' . $file);
}
rmdir($filename); //remove directory
}

Using php to rename all files in folder

new php programmer here. I have been trying to rename all the files in a folder by replacing the extension.
The code I'm using is from the answer to a similar question on SO.
if ($handle = opendir('/public_html/testfolder/')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($fileName, $newName);
}
closedir($handle);
}
I get no errors when running the code, but no changes are made to the filenames.
Any insight on why this isn't working? My permission settings should allow it.
Thanks in advance.
EDIT: I get a blank page when checking the return value of rename(), now trying something with glob() which might be a better option than opendir...?
EDIT 2: With the 2nd code snippet below, I can print the contents of $newfiles. So the array exists, but the str_replace + rename() snippet fails to change the filename.
$files = glob('testfolder/*');
foreach($files as $newfiles)
{
//This code doesn't work:
$change = str_replace('php','html',$newfiles);
rename($newfiles,$change);
// But printing $newfiles works fine
print_r($newfiles);
}
Here is the simple solution:
PHP Code:
// your folder name, here I am using templates in root
$directory = 'templates/';
foreach (glob($directory."*.html") as $filename) {
$file = realpath($filename);
rename($file, str_replace(".html",".php",$file));
}
Above code will convert all .html file in .php
You're probably working in the wrong directory. Make sure to prefix $fileName and $newName with the directory.
In particular, opendir and readdir don't communicate any information on the present working directory to rename. readdir only returns the file's name, not its path. So you're passing just the file name to rename.
Something like below should work better:
$directory = '/public_html/testfolder/';
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
Are you sure that
opendir($directory)
works? Have you checked that? Because it seems there might be some Document Root missing here...
I would try
$directory = $_SERVER['DOCUMENT_ROOT'].'public_html/testfolder/';
And then Telgin's solution:
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace(".php",".html",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
That happens if the file is opened. Then php cannot do any changes to the file.
<?php
$directory = '/var/www/html/myvetrx/media/mydoc/';
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$dd = explode('.', $fileName);
$ss = str_replace('_','-',$dd[0]);
$newfile = strtolower($ss.'.'.$dd[1]);
rename($directory . $fileName, $directory.$newfile);
}
closedir($handle);
}
?>
Thank you so much for the suggestions. it's working for me!

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

Checking if thumbnail exists in PHP

My directory structure looks like that.
...photo-album1/
...photo-album1/thumbnails/
Lets say we have image1.jpg inside photo-album1/. Thumbnail of this file is tn_image1.jpg
What I wanna do is to check every file inside photo-album1/ if they have thumbnail in photo-album1/thumbnails/. If they have just continue if not, send file name to another function : generateThumb()
How can I do that?
<?php
$dir = "/path/to/photo-album1";
// Open directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
// Walk through directory, $file by $file
while (($file = readdir($dh)) !== false) {
// Make sure we're dealing with jpegs
if (preg_match('/\.jpg$/i', $file)) {
// don't bother processing things that already have thumbnails
if (!file_exists($dir . "thumbnails/tn_" . $file)) {
// your code to build a thumbnail goes here
}
}
}
// clean up after ourselves
closedir($dh);
}
}
$dir = '/my_directory_location';
$files = scandir($dir);//or use
$files =glob($dir);
foreach($files as $ind_file){
if (file_exists($ind_file)) {
echo "The file $filexists exists";
} else {
echo "The file $filexists does not exist";
}
}
The easy way is to use PHP's glob function:
$path = '../photo-album1/*.jpg';
$files = glob($path);
foreach ($files as $file) {
if (file_exists($file)) {
echo "File $file exists.";
} else {
echo "File $file does not exist.";
}
}
Credit to soul above for the basics. I'm just adding glob to it.
EDIT: As hakre points out, glob only returns existing files, so you can speed it up by just checking to see if the filename is in the array. Something like:
if (in_array($file, $files)) echo "File exists.";

check file exists or not in folder in php

i want to know how to check the filename in folder with some condition.
for example :
the folder name is "output"
this folder containing the following the images.
2323a.Png
5235v.Jpeg
2323s.jpg
23523s.JPEG
etc..,
if i check the file name is "2323a.png" but there is file name is 2323a.Png.
how to i check the filename is incasesensitive.
thanks in advance
Imho you have to read the directory contents
function file_exists_ignore_case($path) {
$dirname = dirname($path);
$filename = basename($path);
$dir = dir($dirname);
while (($file = $dir->read()) !== false) {
if (strtolower($file) == strtolower($filename)) {
$dir->close();
return true;
}
}
$dir->close();
return false;
}
Use strtolower on your filenames to check if they exist.
if(strtolower($filename) === '2323a.png')

Categories