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.
Related
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);
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
i try to do
<?php
$i = new \GlobIterator('/test/file*.gz');
echo $i->count();
With file*.gz may not exist. And when no file found i got this error
Fatal error: Uncaught exception 'LogicException' with message 'The parent constructor was not called: the object is in an invalid state ' in /in/qHHhR:3
Stack trace:
0 /in/qHHhR(3): SplFileInfo->_bad_state_ex()
As you can see here http://3v4l.org/qHHhR, it's not working only 5.3.7+
PHP bug or what am i doing wrong?
Ok so, as CBroe say it's a php bug.
A solution (found on https://bugs.php.net/bug.php?id=55701) is to do like this:
// Next works as expected: no xml files found = no output
foreach (new GlobIterator($path_to_files . '/*.xml') as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
$it = new GlobIterator($path_to_files . '/*.xml');
// Expected result: count = 0
// Instead next line will crash php if no xml files are found
if ($it->count()) {
// do something...
}
Another method that looks cleaner to me:
try {
$count = $i->count();
} catch ( \LogicException $e) {
$count = 0;
}
Another method using iterator_to_array
count(iterator_to_array($i))
// return 0
I have the following bit of code that is giving me problems.
#$fullfilename="/data/extract/".$curpkg."/".$curfilename;
$fullfilename = "/tmp/test.txt";
$readline = 0;
$lictext="";
try {
$file = new SplFileObject($fullfilename);
$readline=$curline-1;
while ($readline <= ($curline -1 + $curlinecount)) {
$file->seek($readline);
$lictext = $lictext . $file->current()."\n<br>";
$readline = $readline + 1;
}
} catch (Exception $e) {
$lictext = "couldn't open it $fullfilename<br> Exception: $e<br>";
}
When I use the currently uncommented $fullfilename variable declaration, it works fine, but when I use the code that is commented out it does not. I get the following error:
couldn't open it /data/extract/test.txt
Exception: exception 'RuntimeException' with message \
'SplFileObject::__construct(/data/extract/test.txt):\
failed to open stream: No such file or directory' in \
/srv/www/htdocs/legal/index.php:70
Stack trace:
#0 /srv/www/htdocs/legal/index.php(70): \
SplFileObject->__construct('/data/extract/test.txt')
The only difference is that the data I want to use is a separate drive mounted at /data.
Permissions for the entire structure are 777: drwxrwxrwx 2 root root 53248 Jan 7 14:31 data.
I am at a loss here, I have the same problem with file_exists() and is_readable(). Can anyone give me some guidance here?
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