So I've made this Upload file function on my php page. What this function does is uploading the file into a folder with the same name as the file. The user can choose a lot of different projects, from a dropdown. When the user picks a project with a existing file, another function will scan all the information from the Excel file.
My question here is:
How can I search for only existing Excel files, and not every single file in the directory?
Code:
/**
* Checks if there is an existing uploaded RVTM file. File was uploaded through 'upload.php'.
*
* #access public
* #param string $fileName Name of the spreadsheet file
* #param array $OverviewResult Array of information about verdicts, TestSuiteCollectionIds, and TestJobIds
* #author Mads Sander Hoegstrup
*/
function Create_Table_RVTM($fileName, $OverviewResult){
#Scan directory for any files, and return them (should only be a single file), when the file is deleted the directory is whiped clean: Delete_RVTM_file(...)
$dir = "./DashboardFiles/files/".$fileName;
$FindFiles = scandir($dir);
$files = array_values(array_diff($FindFiles, array('.', '..')));
if ($files) {
$path = "./DashboardFiles/files/".$fileName."/".$files[0];
echo "<br>The file $fileName exists";
RVTM_Excel($fileName, $OverviewResult, $path);
}else {
echo "<br>The file $fileName does not exists";
}
}
You can use PHP builds in glob with a wildcard something like
<?php
foreach (glob("/path/to/folder/*.xl*") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
You can do it by looking at the file extension, for example .xls.
Here is the full list
https://support.microsoft.com/en-us/office/file-formats-that-are-supported-in-excel-0943ff2c-6014-4e8d-aaea-b83d51d46247
.xlsx
.xlsm
.xlsb
.xltx
.xltm
.xls
.xlt
.xls
.xlam
.xla
.xlw
.xlr
and here you can see how to get a file extension
$ext = pathinfo($path, PATHINFO_EXTENSION);
and read the directory using spl
https://www.the-art-of-web.com/php/directory-list-spl/
use \DirectoryIterator;
function getFileList($dir)
{
// array to hold return value
$retval = [];
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// open directory for reading
$d = new DirectoryIterator($dir) or die("getFileList: Failed opening directory $dir for reading");
foreach($d as $fileinfo) {
// skip hidden files
if($fileinfo->isDot()) continue;
$retval[] = [
'name' => "{$dir}{$fileinfo}",
'type' => ($fileinfo->getType() == "dir") ? "dir" : mime_content_type($fileinfo->getRealPath()),
'size' => $fileinfo->getSize(),
'lastmod' => $fileinfo->getMTime()
];
}
return $retval;
}
Related
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);
}
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/"
I am having issue with RecursiveIteratorIterator moving to next item. I have a directory which has multiple files, and I am trying to go to each file, rename it, and do some other stuff on it. The RecursiveIteratorIterator picks the first file from the directory and renames it successfully. When I do $it->next(), it stays on same file, and tries to look for the file which was already renamed to something else. Below is my code sample. File permission are set to 777. Any ideas would be appreciated.
This only happens if I rename the file. If I remove renaming functionality, its moves to next item as expected.
//initialize iterator object
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, 0));
/* loop directly over the object */
while ($it->valid()) {
// check if value is a directory
if (!$it->isDot()) {
if (!is_writable($directory . '/' . $it->getSubPathName())) {
//direcotry not writable, throw error
} else {
// get current file info
$fileinfo = pathinfo($it->getSubPathName());
//get file extension
$ext = $fileinfo['extension'];
//if its a '.', move to next item
if (in_array($fileinfo['filename'], array(".", ".."))) {
$it->next();
}
// the current file name with complete path
$old_file = $directory . '/' . $it->getSubPathName();
throw new Exception('source file doesnot exist ' . $old_file, error::DOESNOTEXIST);
}
//generate new file name with path
$new_file = $directory . '/' . $it->getSubPath() . '/' . $filename . '.' . $ext;
//rename the file
rename($old_file, $new_file);
}
}
/* * * move to the next iteration ** */
$it->next();
}
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.
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