Fatal error: Uncaught exception 'RuntimeException' - php

I'm running PHP version 5.2.11
When I run the function below:
function get_dirs($path = '.') {
$dirs = array();
foreach (new DirectoryIterator($path) as $file) { // This is line 462.
if ($file->isDir() && !$file->isDot()) {
$dirs[] = $file->getFilename();
}
}
return $dirs;
}
I get this error:
Fatal error: Uncaught exception 'RuntimeException' with message 'DirectoryIterator::__construct(/home/test/test.com/wp-content/themes/mytheme/images) [<a href='directoryiterator.--construct'>directoryiterator.--construct</a>]: failed to open dir: No such file or directory' in /home/test/test.com/testing123/wp-content/themes/mytheme/functions.php:462 Stack trace: #0 /home/test/test.com/testing123/wp-content/themes/mytheme/functions.php(462): DirectoryIterator->__construct('/home/test/wie...') #1 /home/test/test.com/testing123/wp-content/themes/mytheme/functions.php(31): get_dirs('/home/test/wie...') #2 /home/test/test.com/testing123/wp-settings.php(717): include('/home/test/wie...') #3 /home/test/test.com/testing123/wp-config.php(76): require_once('/home/test/wie...') #4 /home/test/test.com/testing123/wp-load.php(30): require_once('/home/test/wie...') #5 /home/test/test.com/testing123 in /home/test/test.com/testing123/wp-content/themes/mytheme/functions.php on line 462
UPDATE: The problem here I've found is that the theme was installed under a virtual directory off the main URL. My scripts are expecting that the theme is installed off the main root url.
For example, the theme in this case was installed at: http://www.example.com/testing123/wp-content/themes/mytheme
However, I'm expecting this: http://www.example.com/wp-content/themes/mytheme
AND SO...
My path function fails since it does not take into consideration that it could be installed under a virtual directory.
How could I account for this scenario in my feeding of this function?
$mydir = get_dirs("$_SERVER[DOCUMENT_ROOT]/wp-content/themes/mytheme/images");
function get_dirs ($path = '.') {
$dirs = array();
foreach (new DirectoryIterator($path) as $file) {
if ($file->isDir() && !$file->isDot()) {
$dirs[] = $file->getFilename();
}
}
return $dirs;
}

Enclose it in a try-catch block?
function get_dirs($path = '.') {
$dirs = array();
try{
foreach (new DirectoryIterator($path) as $file) { //this is line 462
if ($file->isDir() && !$file->isDot()) {
$dirs[] = $file->getFilename();
}
}
} catch(Exception $e) {
//log exception or process silently
//just for test
echo $e;
}
return $dirs;

The class is there, but apparently your images directory is not:
/home/test/test.com/wp-content/themes/mytheme/images
The key part of the message being:
failed to open dir: No such file or directory
Or, if it is there, PHP doesn't have permissions to read from it.

It looks like the third line is telling you that the directory cannot be found:
failed to open dir: No such file or directory
I would check your path from the script being called and adjust that appropriately

Related

Fatal error when trying to Parse a XML file to CSV in PHP

I am stuck on a bit of code for my program, where I am attempting to convert a XML document to CSV using a function in PHP. The code for the function is:
function createCsv($xml, $f)
{
foreach ($xml->children() as $item)
{
$hasChild = (count($item->children()) > 0) ? true : false;
if (!$hasChild)
{
$put_arr = array($item->getName(), $item);
fputcsv($f, $put_arr, ',', '"');
}
else
{
createCsv($item, $f);
}
}
}
And I am calling it in the main script here:
if (file_exists($FilePath))
{
echo "Converting, please stand by /n";
$xml = $_FILES;
$f = fopen('.csv', 'w');
createCsv($xml, $f);
fclose($f);
//calling function to convert the xml file to csv
$UploadDirectory = $UploadDirectory . basename($_FILES["fileToUpload"]["tmp_name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $UploadDirectory))
{
echo "The file has been uploaded and converted. Please click the link below to download it";
echo ''.$File.'';
//giving link to click and download converted CSV file
}
else
{
echo "There was a problem uploading and converting the file. Please refresh the page and try again.";
}
}
the error message I get when running the script through XAMPP is:
Fatal error: Uncaught Error: Call to a member function children() on array in C:\xampp\htdocs\XMLtoCSV\convert.php:4 Stack trace: #0 C:\xampp\htdocs\XMLtoCSV\convert.php(73): createCsv(Array, Resource id #3) #1 {main} thrown in C:\xampp\htdocs\XMLtoCSV\convert.php on line 4
Line 4 that it is referencing is the foreach statement in the createCSV function. I am really at a loss, and very new to PHP. I have had to teach myself PHP with mixed results, and any assistance would be highly appreciated.
You are considering $_FILES as the xml file, which is incorrect.
$_FILES is an associative array of uploaded files. You need to open the file and read the data. To do so you can use simplexml_load_file:
$xml = simplexml_load_file($_FILES["fileToUpload"]["tmp_name"]);
createCsv($xml, $f);

Directory is Different When I Run PHP Script IN Scheduled Tasks Of Plesk

I use this clear.php script that remove all files and folders in correct clear directory:
<?php
function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
deleteDir($file);rmdir($file);
} else {
unlink($file);
}
}
}
deleteDir('clear');
?>
when i run the code mydomain.com/clear.php it work and remove all files and folders but when i create a Scheduled Tasks in plesk and use this code it shows:
Task "httpdocs/clear.php" completed with error in 0 seconds. See
details
and when i click the see details it shows:
Task "httpdocs/clear.php" completed with error in 0 seconds, output:
PHP Fatal error: Uncaught InvalidArgumentException: clear must be a directory in /var/www/vhosts/domain_name.com/httpdocs/clear.php:4
Stack trace:
#0 /var/www/vhosts/domain_name.com/httpdocs/clear.php(19): deleteDir('clear')
#1 {main}
thrown in /var/www/vhosts/domain_name.com/httpdocs/clear.php on line 4

Fatal error: Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(public/user_/,public/user_/)

I am getting this error while using the RecursiveDirectoryIterator.
Fatal error: Uncaught exception 'UnexpectedValueException' with
message
'RecursiveDirectoryIterator::__construct(public/user_/,public/user_/):
The system cannot find the path specified. (code: 3)' in
D:\xam\htdocs\s\upload.php:101 Stack trace: #0
D:\xam\htdocs\s\upload.php(101):
RecursiveDirectoryIterator->__construct('public/user_/') #1
D:\xam\htdocs\s\upload.php(138): dirSize('public/user_/') #2 {main}
thrown in D:\xam\htdocs\s\upload.php on line 101
Here is the code i am using.
function dirSize($directory) {
$size = 0;
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
$size+=$file->getSize();
}
return $size;
}
Please help!!!
There is a limited context here to see what is going wrong. However it would appear that your giving a directory to D:\xam\htdocs\s\upload.php that is not valid to start the iteration and find the size.
The try/catch option would stop it from throwing an error and failing
function dirSize($directory) {
$size = 0;
try {
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file) {
$size += $file->getSize();
}
} catch(Exception $e) {
echo "Error: " . $e;
echo "On: " . $directory;
}
return $size;
}

Using DirectoryIterator to loop through a D: drive directory

I am trying to loop through this directory:
$path = "D:\\import\\statsummary\\";
Here is my code:
$path = "D:\\import\\statsummary\\";
//$path = "C:\\test";
//function load_csv($path, $filename){
if(is_null($filename)){
header('Content-type: text/plain');
$output = array();
foreach (new DirectoryIterator($path) as $file){
if($file->isFile()){
$output[] = $i++ . " " . $file->getFileName() . "\n";
$output[] = file($file->getPathName());
$output[] = "\n------------\n";
}
}
}
echo implode('', $output);
When I run this script, I get this error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(D:\import\statsummary\,D:\import\statsummary\): Access is denied. (code: 5)' in C:\inetpub\wwwroot\include\file_importer.php:10
Stack trace:
#0 C:\inetpub\wwwroot\include\file_importer.php(10): DirectoryIterator->__construct('D:\import\...')
#1 {main}
thrown in C:\inetpub\wwwroot\include\file_importer.php on line 10
But when I change it to a test directory on my C:\ drive, it runs just fine. I've even created a username to run PHP as directed in this post:
php - Unable to connect to network share - Stack Overflow
Based on the DirectoryIterator class, something like this should work:
<?php
$path = "D:/import/statsummary";
$output=array();
$iterator = new DirectoryIterator(path);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
$filename= $fileinfo->getFilename();
$path=$fileinfo->getPathname();
$output[][$filename]=$path;
}
}
print_r($output);
?>
Update
Since you're getting access denied, you'll need to run the command prompt (CMD) window as Administrator more than likely. If this is on a link (lnk) you can change the permissions in the link settings.
For instance if you right-click on the shortcut for cmd as select properties, you would go to shortcut>advanced>Run as Administrator.

RecursiveDirectoryIterator throws UnexpectedValueException on "Too many open files"

The following code:
$zip = new ZipArchive();
if ($zip->open('./archive.zip', ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./folder/"));
foreach ($iterator as $key => $value) {
try {
$zip->addFile(realpath($key), $key);
echo "'$key' successfully added.\n";
} catch (Exception $e) {
echo "ERROR: Could not add the file '$key': $e\n";
}
}
$zip->close();
Throws the following exception if there are too many files in a sub-folder which you're trying to iterate over:
Uncaught exception 'UnexpectedValueException' with message 'RecursiveDirectoryIterator::__construct(./some/path/): failed to open dir: Too many open files' in /some/other/path/zip.php:24
Stack trace:
#0 [internal function]: RecursiveDirectoryIterator->__construct('./some/path/')
#1 /some/other/path/zip.php(24): RecursiveDirectoryIterator->getChildren()
#2 {main}
thrown in /some/other/path/zip.php on line 24
How can you successfully iterate over a large amount of folders and files without experiencing this exception?
Simply by converting the iterator to an array with the iterator_to_array function, it seems like you can iterate over as many files as you'd like:
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./folder/"));
$files = iterator_to_array($iterator, true);
// iterate over the directory
// add each file found to the archive
foreach ($files as $key => $value) {
try {
$zip->addFile(realpath($key), $key);
echo "'$key' successfully added.\n";
} catch (Exception $e) {
echo "ERROR: Could not add the file '$key': $e\n";
}
}

Categories