Delete file from folder and subfolder - php

I have a php script that uploads a photo to a main folder and copies it into a subfolder. I also have a php script that deletes the photo. The problem is that it only deletes the photo from the main folder and not the subfolder. This is the code I tried to come up with but nothing happens. Any thoughts?
$deletefile = $galleriesfolder.$folder.$dir.$image;
$deletefile1 = $galleriesfolder.$folder.$dir."/thumbs/".$image;
unlink($deletefile);
if (!is_file($deletefile)):
die("no file");
endif;
unlink($deletefile1);
if (!is_file($deletefile1)):
die("no file");
endif;

Deletes all subfolders and files in a directory recursively
/**
* Deletes a directory and all files and folders under it
* #return Null
* #param $dir String Directory Path
*/
function rmdir_files($dir) {
$dh = opendir($dir);
if ($dh) {
while($file = readdir($dh)) {
if (!in_array($file, array('.', '..'))) {
if (is_file($dir.$file)) {
unlink($dir.$file);
}
else if (is_dir($dir.$file)) {
rmdir_files($dir.$file);
}
}
}
rmdir($dir);
}
}
This is quite a nasty function.
You want to handle it with care. Make sure you don't delete any directories that you do not intend to delete. It will attempt to remove the whole directory, and all files in it.
It does no error checking apart from making sure a directory handle was opened successfully for reading.

This code will deletes all subfolders and files in a directory recursively.
$dir = "/";
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, `enter code here`RecursiveIteratorIterator::CHILD_FIRST);
foreach ($ri as $file)
{
$file->isDir() ? rmdir($file) : unlink($file);
}

Related

How can i move all image files from a directory to a sub-directory using php

I am attempting to move all images from my /webfiles directory to my /webfiles/images directory. I have managed to do it to a single image using the below code:
$imgfiles = glob("webfiles/28.png");
rename($imgfiles[0], "webfiles/images/28.png");
However i have multiple images and the names will be unknown so cannot specify as per the above.
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "webfiles/";
$destination = "webfiles/images/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach($delete as $file) {
unlink($file);
}

Access files from path above root in PHP

I'm writing a simple upload/download page in PHP. With the following code I can see files being the content of folder above the root but it's impossible to access those files. What could be the reason?
$targetdir="/../cat/";
if ($dir = #opendir($targetdir))
{
while ($file = readdir($dir))
{
if ($file != "." && $file != "..")
echo "<td>".$file."</td>";
}
closedir($dir);
}
You cannot access files above the web root directory, instead you will need to write a script to do this for you.
downloadfile.php?file=somefile.txt
<?php
$file = $_GET['file'];
if (strpos($file, '..') !== false) {
throw new \Exception('Illegal path requested');
}
/**
* this will restrict files to this directory or above as
* to not allow reading of files which you do not want a user to access
*/
$basePath = __DIR __ . '/../cat';
$fullPath = sprintf('%s/%s', $basePath, $file);
/** check to see if the file exists and is readable **/
if (false === is_readable($fullPath)) {
throw \Exception('file does not exist or is not accessible');
}
echo file_get_contents($file);
exit;
You must be very cautious when doing this, as you could allow someone to access files you don't want them to, including your source code, so make sure you're sanitizing the input.
As well you should change $target dir to the following, as it stands you're trying to go to the absolute root of the file system instead relative to the file which started the execution.
/** relative to the file that started the execution **/
$targetdir = "../cat/"
/** relative to the file that contains this variable declaration**/
$target = __DIR__ . "/../cat/"

PHP Remove all Files From a Directory - Exclude File Extension

I am trying for the life of me to find the best way to delete all files in a single directory excluding a single file extension, ie anything that is not .zip
The current method I have used so far which successfully deletes all files is:
$files = glob('./output/*');
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
I have tried modifying this like so:
$files = glob('./output/**.{!zip}', GLOB_BRACE);
foreach($files as $file)
{
if(is_file($file))
unlink($file); // delete file
}
However, I am not hitting the desired result. I have changed the line as follows which has deleted only the zip file itself (so I can do the opposite of desired).
$files = glob('./output/*.{zip}', GLOB_BRACE);
I understand that there are other methods to read directory contents and use strpos/preg_match etc to delete accordingly. I have also seen many other methods, but these seem to be quite long winded or intended for recursive directory loops.
I am certainly not married to glob(), I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
Any help/advice is appreciated.
$exclude = array("zip");
$files = glob("output/*");
foreach($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if(!in_array($extension, $exclude)) unlink($file);
}
This code works by having an array of excluded extensions, it loads up all files in a directory then checks for the extension of each file. If the extension is in the exclusion list then it doesn't get deleted. Else, it does.
This should work for you:
(I just use array_diff() to get all files which are different to *.zip and then i go through these files and unlink them)
<?php
$files = array_diff(glob("*.*"), glob("*.zip"));
foreach($files as $file) {
if(is_file($file))
unlink($file); // delete file
}
?>
How about calling to the shell? So in Linux:
$path = '/path/to/dir/';
$shell_command = escapeshellcmd('find ' . $path .' ! -name "*.zip" -exec rm -r {}');
$output = shell_exec($shell_command);
I would simply like to know the simplest/most efficient way to delete all files in a single directory that are not a .zip file.
SPL Iterators are very effective and efficient.
This is what I would use:
$folder = __DIR__;
$it = new FilesystemIterator($folder, FilesystemIterator::SKIP_DOTS);
foreach ($it as $file) {
if ($file->getExtension() !== 'zip') {
unlink($file->getFilename());
}
}
Have you tried this:
$path = "dir/";
$dir = dir($path);
while ($file = $dir->read()) {
if ($file != "." && $file != ".." && substr($file, -4) !== '.zip') {
unlink($file);
}
}

Retrieving contents of several files in directory PHP

I need to get the contents of several files within a directory but which is the best way of doing this?
I am using
$data = file_get_contents('./files/myfile.txt');
but I want every file without having to specify the file individually as above.
You can use glob to get particular file extention and file_get_contents to get the content
$content = implode(array_map(function ($v) {
return file_get_contents($v);
}, glob(__DIR__ . "/files/*.txt")));
/**
* Change the path to your folder.
* This must be the full path from the root of your
* web space. If you're not sure what it is, ask your host.
*
* Name this file index.php and place in the directory.
*/
// Define the full path to your folder from root
$path = "/home/content/s/h/a/shaileshr21/html/download";
// Open the folder
$dir_handle = #opendir($path) or die("Unable to open $path");
// Loop through the files
while ($file = readdir($dir_handle)) {
$data = file_get_contents('$filet');
}
// Close
closedir($dir_handle);
You can dir the directory and loop through it to get the contents of all files.
<?php
$path = './files';
$d = dir($path);
$contents = '';
while (false !== ($entry = $d->read())) {
if (!($entry == '..' || $entry == '.')) {
$contents .= file_get_contents($path.'/'.$entry);
}
}
$d->close();
?>
If you only want .txt files you can change the if statement of the code above from:
if (!($entry == '..' || $entry == '.')) {
to:
if (substr($entry, -4) == '.txt') {
This will result to a variable $contents that is type string and has all the contents of all the files (or only txt files if you select the 2nd solution) that are in the ./files dir.

Copy entire directory and content from one location to another using PHP

I am trying to copy an entire folder from one location to another using PHP, but it doesn't seem to work:
$username = "peter" //this is just an example.
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder
// copy image folder
$source = "templates/template1/images/";//copy image folder -source
$dest = $userdir;
function copyr($source, $dest){
// Simple copy for a file
if (is_file($source)) {
$c = copy($source, $dest);
chmod($dest, 0777);
return $c;
}
// Make destination directory
if (!is_dir($dest)) {
$oldumask = umask(0);
mkdir($dest, 0777);
umask($oldumask);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}
}
// Clean up
$dir->close();
return true;
}
I have also tried other solutions I saw online without success. Would appreciate any help possible
I also just tried this script without any luck.
I just tried another script and still no luck :(.
$template_homepage = "templates/template1/index.php";//path to default template homepage
$homepage = file_get_contents($template_homepage);//get default homepage structure
$username = testuser;// folder name for store
if (trim($username) == '') {
die("An error occured.");
} else {
$userdir = "../Users/".$username."/";
mkdir($userdir);// create folder for new website
// copy image folder
$src = 'templates/template1/images';//copy image folder -source
$dst = $userdir;
function rcopy($src, $dst) {
if (file_exists($dst)) rrmdir($dst);
if (is_dir($src)) {
mkdir($dst);
$files = scandir($src);
foreach ($files as $file)
if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
}
else if (file_exists($src)) copy($src, $dst);
}
$fh = fopen($userdir."index.php", 'w') or die("An error occured. ");// create home page in users folder
// $stringData = $title; //."\n";//
fwrite($fh, $homepage);// write homepage structure into new homepage file.
fclose($fh);// close new homepage file.
$launchpage = "../Users/".$username."/"; // launch new homepage file.
header("Location: $launchpage");
}
Why don't you use exec and use the OS command to copy the folder over?
exec('cp -r sourcedir destdir');

Categories