I'm trying to get the last modification time to display when the file(s) were uploaded, but I am getting this error: Warning: stat(): stat failed for image.jpeg in /var/www/html/module/Admin/File.php on line 116
Here is the code that handles it:
public function getModificationTime($dir)
{
if (!is_dir($dir)) {
return false;
}
$scandir = scandir($dir);
$holder = array();
foreach ($scandir as $key => $values) {
$holder = stat($values);
}
return $holder;
}
What am I doing wrong? Any help would be appreciated.
stat() cannot find the file. Use the full path ($values contains only the file name):
$holder = stat($dir.'/'.$values);
You need to concatenate the directory name. It's looking for the file in the current directory, not the directory you're scanning.
$holder = stat($dir . '/' . $values);
Related
I am trying to get content of all the files in my directory and I am getting an error that says
ErrorException in Util.php line 114:
preg_match() expects parameter 2 to be string, array given
. Below is the code that I am using.
public function store(Request $request)
{
$directory = storage_path('app/xmlentries/uploads');
$files = File::files($directory);
foreach ($files as $file)
{
$contents = Storage::get($file);
dd($contents);
}
How would i get the contents of all my files in this folder?
Try this:
$directory = storage_path('app/xmlentries/uploads/');
foreach (glob($directory . "*") as $file) {
$fileContent = file_get_contents($file);
dd($fileContent); // change this per your need
}
Please note this will display the first file and then stop!
I want to write a function which reads all the files in a dir and pushes a common variable value in each file to an array.
The idea is kinda to have a wordpress like feature in a way... You add a php file to a plugins folder with certain characteristics. For example every file you add must have a $fileName variable. My goal here is to grab each of the $fileName from each file in the dir and push them to an array so I can call on the array to create a navigation. The navigation will then load the php file into a content area when the link is activated with ajax.
My file path is,
/plugins/reports.php
/plugins/RandomPlugin2.php
/plugins/RandomPlugin3.php
I was trying to get this done doing something like this,
in /assets/load-plugins.php
function loadPlugins(){
$files = scandir('../plugins/');
foreach($files as $file) {
if(($file_handle = fopen($file, "r")))
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $fileName;
}
fclose($file_handle);
}
}
loadPlugins();
But this is the error I get,
Warning: fopen(reports.php) [function.fopen]: failed to open stream: No such file or directory in /Applications/AMPPS/www/wubase/assets/load-plugins.php on line 12
Warning: fclose() expects parameter 1 to be resource, boolean given in /Applications/AMPPS/www/wubase/assets/load-plugins.php on line 17
It tells me there is no such file or directory but it even mentions the file currently in the plugins directory. Could this be a permission problem because I am trying to open a file from a different directory?
Also if someone has a better idea to achieve my goal I am all ears and would appreciate the constructive criticism.
Thanks,
Try this:
function loadPlugins() {
$files = glob('../plugins/');
foreach($files as $file) {
if(($file_handle = fopen($file, "r"))) {
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line;
}
}
fclose($file_handle);
}
}
Switch the function to glob() instead of scandir() (the former returns the full Unix path when the latter returns only the filename).
Take the habit of always use curly brackets for your if() statements, even when they are optional.
$fileName was not set, I assumed you meant $line (which is set right above).
scandir returns just name of file or directory(not full path). So, for example
.
├── 1.txt
├── 2.txt
├── 3.txt
└── public
└── script.php
Your script in public folder, required files in ../ folder. scandir('../') will return
array (
0 => '.',
1 => '..',
2 => '1.txt',
3 => '2.txt',
4 => '3.txt',
5 => 'public',
);
So you need function, that returns full path to files, or make this path by yourself.
UPD: as D4V1D mentioned, glob() will solve your problem.
Seems you have problem with file path, you can define and use this function to read your directory all files with ab
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value){
if (!in_array($value,array(".",".."))){
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result = array_merge(
$result,
dirToArray($dir . DIRECTORY_SEPARATOR . $value)
);
}else{
$result[] = $dir . DIRECTORY_SEPARATOR . $value;
}
}
}
return $result;
}
it will give you all files with absolute path located in that mentioned directory or subsirectories
I have pdf files which are report cards of students.The report card names format is <student full name(which can have spaces)><space><studentID>.I need to download files.For this I have used the following code.
if(file_exists($folder_path.'/') && is_dir(folder_path)) {
$report_files = glob(folder_path.'/*'.'_*\.pdf' );
if(count($report_files)>0)
{
$result_data = '';
$result_data = rename_filenamespaces($report_files);
var_dump($result_data);//this shows the edited filename
foreach ($result_data as $file) {
if (strpos($file,$_GET['StudentID']) !== false) {
//code for showing the pdf docs to download
}
}
}
}
//function for renaming if filename has spaces
function rename_filenamespaces($location)
{
$new_location = $location;
foreach ($location as $file) {
//check file has spaces and filename has studentID
if((strpos($file," ")!==false)&& (strpos($file,$_GET['StudentID']) !== false))
{
$new_filename = str_replace(" ","-",$file);
rename($file,$new_filename);
$new_location = $new_filename;
}
}
return $new_location;
}
The variable $result_data gives me the filename without spaces,but the for each loop is showing Warning:Invalid argument supplied for foreach(). But the filename is changed in the server directory immediately after running the function. This warning shows only for first time. I am unable to solve this.
$new_location = $new_filename;
$new_location is a array
$new_filename is a string
You have to use $new_location[$index]
or try
foreach ($new_location as &$file) {
...
...
$file = $new_filename;
I'm trying to list all PHP files in a specified directory and for it to recursively check all sub-directories until it finds no more, there could be numerous levels.
The function I have below works fine with the exception that it only recurses down one level.
I've spent hours trying to see where I'm going wrong, I'm calling the scanFiles() when it finds a new directory but this only seems to work one level down and stop, any help greatly appreciated.
Updated:
function scanFiles($pParentDirectory)
{
$vFileArray = scandir($pParentDirectory);
$vDirectories = array();
foreach ($vFileArray as $vKey => $vValue)
{
if (!in_array($vValue, array('.', '..')) && (strpos($vValue, '.php') || is_dir($vValue)))
{
if (!is_dir($vValue))
$vDirectories[] = $vValue;
else
{
$vDirectory = $vValue;
$vSubFiles = scanFiles($vDirectory);
foreach ($vSubFiles as $vKey => $vValue)
$vDirectories[] = $vDirectory.DIRECTORY_SEPARATOR.$vValue;
}
}
}
return $vDirectories;
}
You can do this easily like this:
// helper function
function getFiles(&$files, $dir) {
$items = glob($dir . "/*");
foreach ($items as $item) {
if (is_dir($item)) {
getFiles($files, $item);
} else {
if (end(explode('.', $item)) == 'php') {
$files[] = basename($item);
}
}
}
}
// usage
$files = array();
getFiles($files, "myDir");
// debug
var_dump($files);
myDir looks like this: has php files in all dirs
Output:
P.S. if you want the function to return the full path to the found .php files, remove the basename() from this line:
$files[] = basename($item);
This will then produce result like this:
hope this helps.
This is because $vDirectory is just a folder name, so scanDir looks in the current folder for it, not the sub folder.
What you want to do is to pass in the path to the folder, not just the name. This should be as simple as changing your recursive call to scanFiles($pParentDirectory . DIRECTORY_SEPARATOR . $vDirectory)
Your main problem is functions like scanDir or isDir need the full file path to work.
If you pass the full file path to them, it should work correctly.
Using PHP 5.3.3 (stable) on Linux CentOS 5.5.
Here's my folder structure:
www/myFolder/
www/myFolder/testFolder/
www/myFolder/testFile.txt
Using scandir() against the "myFolder" folder I get the following results:
.
..
testFolder
testFile.txt
I'm trying to filter out the folders from the results and only return files:
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
The expected results are:
testFile.txt
However I'm actually seeing:
testFile.txt
testFolder
Can anyone tell me what's going wrong here please?
You need to change directory or append it to your test. is_dir returns false when the file doesn't exist.
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir("myFolder/$file"))
{
echo $file.'\n';
}
}
That should do the right thing
Doesn't is_dir() take a file as a parameter?
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
Already told you the answer here: http://bugs.php.net/bug.php?id=52471
If you were displaying errors, you'd see why this isn't working:
Warning: Wrong parameter count for is_dir() in testFile.php on line 16
Now try passing $file to is_dir()
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
If anyone who comes here is interested in saving the output to an array, here's a fast way of doing that (modified to be more efficient):
$dirPath = 'dashboard';
$dir = scandir($dirPath);
foreach($dir as $index => &$item)
{
if(is_dir($dirPath. '/' . $item))
{
unset($dir[$index]);
}
}
$dir = array_values($dir);