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
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);
This question already has answers here:
PHP - Failed to open stream : No such file or directory
(10 answers)
Closed 5 years ago.
I am just trying to make a simple PHP program that allows me to generate my page quickly.
I am completely new at PHP.. And I have no clue what I am doing.
/index.php
<?php
include "/base/startup.php";
echo "Test";
startPage("Home");
?>
I'm getting a 500 server error with this.. Please tell me what I'm doing wrong. Thank you.
/base/startup.php
$HOME = "/";
$SCRIPT = <<<EOD
EOD;
$IMPORTS = array(
"/scripts/script.js"
);
$STYLES = array(
"/styles/style.css"
);
function prnt($string) {
echo $string;
}
function map($func, $arr) {
foreach($arr as $i) {
call_user_func($func, $i);
}
}
function linkScript($script) {
prnt("<script src='$script'></script>");
}
function linkStyle($style) {
prnt("<link rel='stylesheet' href='$style'/>");
}
function startPage($title, $script="", $imports=array(), $styles=array()) {
$pre_tags = array(
"<html>",
"<head>"
);
$post_tags = array(
"</head>",
"<body>"
);
map(prnt, $pre_tags);
prnt("<title>$title</title>");
map(linkScript, $IMPORTS);
map(linkScript, $imports);
map(linkStyle, $STYLES);
map(linkStyle, $styles);
map(prnt, $post_tags);
}
function genNav() {
$nav_links = array(
"Home"=>$HOME,
"Walkthroughs"=>$HOME . "/walkthroughs/",
"Dex"=>$HOME . "dex.php"
);
prnt("<div class='nav'>");
foreach ($nav_links as $key => $value) {
prnt("<a class='link' href='" . $value . "'/>" . $key . "</a>");
}
}
function endPage() {
$endTags = array(
"</body>",
"</html>"
);
}
?>
This is the error:
Warning: include(/base/startup.php): failed to open stream: No such file or directory in /var/www/html/index.php on line 2
Warning: include(): Failed opening '/base/startup.php' for inclusion (include_path='.:/usr/share/php') in /var/www/html/index.php on line 2
Test
Fatal error: Uncaught Error: Call to undefined function startPage() in /var/www/html/index.php:4 Stack trace: #0 {main} thrown in /var/www/html/index.php on line 4
Since you mentioned you are on a Linux machine, it looks like the issue is caused because of the / here. The / is considered the root directory of linux machine. So removing the / must most probably work:
<?php
include "base/startup.php"; // Try removing the slash.
echo "Test";
startPage("Home");
?>
Since you haven't enabled the display of errors, the issue would be, there's no /base in your system and it would have thrown an error, like Fatal: Include file not found., which is not displayed because of your configuration, instead it would have shown Error 500 silently.
Update
Along with the above error, after seeing your code, the next one is you need to quote the function names. So replace the stuff with:
map("prnt", $pre_tags);
prnt("<title>$title</title>");
map("linkScript", $IMPORTS);
map("linkScript", $imports);
map("linkStyle", $STYLES);
map("linkStyle", $styles);
map("prnt", $post_tags);
The next error is, you haven't included the global variables correctly inside the function. You need to use:
global $IMPORTS, $STYLES;
Now your code works as expected.
And finally finishing the endPage() function:
function endPage() {
$endTags = array(
"</body>",
"</html>"
);
foreach($endTags as $tag)
echo $tag;
}
Below is the code that throws some errors while getting executed. What I'm trying to do is the last line of the code gets executed no matter what (Error or no Error).
<?php
require 'main.php';
function create_photo($file_path) {
# Upload the received image file to Cloudinary
#$result = \Cloudinary\Uploader::upload($file_path, array(
"tags" => "backend_photo_album",
));
#unlink($file_path);
error_log("Upload result: " . \PhotoAlbum\ret_var_dump($result));
$photo = \PhotoAlbum\create_photo_model($result);
return $result;
}
$files = $_FILES["files"];
$files = is_array($files) ? $files : array($files);
$files_data = array();
foreach ($files["tmp_name"] as $index => $value) {
array_push($files_data, create_photo($value));
}
?>
<script>window.location.replace('index.html')</script>
Any help would be much appreciated. Thanks
I think depending on your php version, you can use a "try/catch/finally" bloc like that:
try
{
// code that may throw an exception
}
catch(Exeption $e) // The exception you want to catch
{
// Exception treatment
}
finally
{
// Executed no matter what
}
Maybe take a look about how to use that.
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.
I am hoping that someone can help me: I have this scripts that if a file does not exists on my server, it goes to a remote server to check for the file. If the file exists it copies it to my local server, and does not check it again. So the Imagick part only works when the image does not exists on my local server.
The problem that I have is that if the file does not exists on the remote server - then the application throughs a error - Here is the code of my script:
<?php if (file_exists($filename))
{
echo '<img src="'.$imageurl1.'" width="'.$g_sites_img1.'" alt="'.$imageurlmeta.'" class="image1" align="left" />';
}
else { $imageurlfolder = dirname($filename);
#mkdir($imageurlfolder, 0755, true);
#copy($imgremoteurl, $filename);
$thumb = new Imagick($filename);
$thumb->scaleImage($g_sites_img1, 0);
$thumb->writeImage($filename);
$thumb->destroy(); }?>
Here is the error code:
> Fatal error: Uncaught exception
> 'ImagickException' with message
> 'Unable to read the file:
> /home/game1/public_html/images/small///.jpg'
> in
> /home/game1/public_html/includes/standard__1.php:15
> Stack trace: #0
> /home/game1/public_html/includes/standard__1.php(15):
> Imagick->__construct('/home/game1/pub...')
> #1 /home/game1/public_html/includes/news.php(127):
> require('/home/game1/pub...') #2
> /home/game1/public_html/index1.php(126):
> include('/home/game1/pub...') #3
> {main} thrown in
> /home/game1/public_html/includes/standard__1.php
> on line 15
How can I avoid this error but still make the page load normally?
I have tried error_reporting(0); <--- This stops the page from completely loading once the error has occured.
Any ideas would be appreciated.
I have found the solution with all the answers posted! thanks a million
<?php if(file_exists($filename))
{ echo ''; }
else { try {$imageurlfolder = dirname($filename);
#mkdir($imageurlfolder, 0755, true); #copy($imgremoteurl, $filename);
$thumb = new Imagick($filename);
$thumb->scaleImage($g_sites_img1, 0); $thumb->writeImage($filename);
$thumb->destroy();}
catch (ImagickException $e) {
echo "Exception caught!\n";
}
}
?>
Well, you should catch the exception, don't try ignoring the errors. After all, you are getting fatal error which prevents further logic from being executed.
try
{
// your logic
}
catch ( ImagickException $e )
{
// do something with it
}
You can use a default local image if the file does not exists on the remote server.
use a catch block
http://php.net/manual/en/internals2.opcodes.catch.php
This is an exception, not an error.
You need to catch it and then handle it:
try {
$thumb = new Imagick($filename);
// do your thing with it
$thumb->destroy();
} catch (ImagickException $e) {
// something went wrong, handle the problem
}
Yes, what you are looking for is called a try-catch statement.
Here is what PHP docs have to say about it
error_reporting(0); works for errors, not exceptions:
try {
// your code
} catch (Exception $e) {
// code that runs in case an error appears
}
if (copy($imgremoteurl, $filename)) {
// image functions
} else {
// error copying image
}
Enclose it in a try block and you can handle the error and choose to ignore it or whatever you want to do with it.
Fatal errors are just that -- FATAL. The script has died, and it's not going to go any farther because the rest of it depends on that data being present.
Add some error-handling in the event that the file doesn't exist on the remote server, and you should be ok.