I'm trying to add some error checking inside my PHP script. Is it valid to do this:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
echo json_encode($res);
die;
}
Is there a better way to exit the script after encountering an error like this?
That looks fine to me.
You can even echo data in the die like so:
if (!mkdir($dir, 0)) {
$res->success = false;
$res->error = 'Failed to create directory';
die(json_encode($res));
}
Throwing a exception. Put code into a try catch block, and throw exception when you need.
PHP has functions for error triggering and handling.
if (!mkdir($dir, 0)) {
trigger_error('Failed to create directory', E_USER_ERROR)
}
When you do this the script will end. The message will be written to the configured error log and it will also be displayed when error_reporting is enabled.
Related
I am developing a PHP script that allows me to modify tags in an XML file and move them once done.
My script works correctly but I would like to add error handling: So that if the result of my SQL query does not return anything display an error message or better, send a mail, and not move the file with the error and move to the next.
I did some tests but the code never displays the error and it moves the file anyway.
Can someone help me to understand why? Thanks
<?php
}
}
$xml->formatOutput = true;
$xml->save($source_file);
rename($source_file,$destination_file);
}
}
closedir($dir);
?>
Give this one a try
$result = odbc_fetch_array($exec);
if ($result === false || $result['GEAN'] === null) {
echo "GEAN not found for $SKU_CODE";
// continue;
}
$barcode = (string) $result['GEAN'];
echo $barcode; echo "<br>"; //9353970875729
$node->getElementsByTagName("SKU")->item(0)->nodeValue = "";
$node->getElementsByTagName("SKU")->item(0)->appendChild($xml->createTextNode($result[GEAN]));
I would like to use the following to detect if a file exists, however there is a warning triggered when when this is the case. It works fine when file_get_contents does not return false.
$nothing = "http://www.google.com/bababababa.doc";
if (false === file_get_contents($nothing,0,null,0,1)) {
echo "File Not Found";
} else {
echo "File Found";
}
First, I'll assume that you only want to hide this error from your logs, because of course you have display_errors turned off on a production server.
You could just hide your errors away with the # error suppression operator, but that's a bad road to start down. Instead you want to define an error handler:
<?php
// define the custom handler that just returns true for everything
$handler = function ($err, $msg, $file, $line, $ctx) {return true;}
$nothing = "http://www.google.com/bababababa.doc";
// update the error handler for warnings, keep the old value for later
$old_handler = set_error_handler($handler, E_WARNING);
// run the code
$result = file_get_contents($nothing);
// go back to normal error handling
set_error_handler($old_handler);
if (false === $result) {
echo "File Not Found";
} else {
echo "File Found";
}
Code:
if(isset($_POST['update_avatar'])) {
$url = $_POST['avatar'];
$info = getimagesize($url);
if(isset($info['name'])) {
echo "Exists";
} else {
echo "Error";
}
}
How can I avoid getting PHP errors when the user types an invalid URL, random piece of text or invalid image URL etc?
Use exception handling. Place your critical code into a try..catch block. You can find more information here.
If there's an error, getimagesize returns false, so test for that. And to suppress error messages from a function, put # before it:
$info = #getimagesize($url);
if (!$info) {
echo "Error";
} else {
// Process the image
}
How do I make the die() message to echo in a certain place in the HTML section of the same page?
$files = array();
$upload = $_FILES['upload']['tmp_name'];
foreach($upload as $uploaded){
if(!empty($uploaded)) {
if(isset($uploaded)){
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime= finfo_file($finfo, $uploaded);
switch($mime) {
case 'application/pdf':
break;
default:
die('pdf file only.');
break;
}
}
}
}
die will immediately stop execution and send anything in buffers to the browser.
Personally, I like to do something like this:
function halt($str="") {
if( $str) echo "<div class=\"server_notice\">".$str."</div>";
require("template/foot.php");
exit;
}
How about don't just use die, do something to insert html there and then die.
Alternatively, you have register_shutdown_function (Documentation: http://php.net/manual/es/function.register-shutdown-function.php) which will allow you to do things right after the script is ended with die;
There is no way to do that. die() or exit() will stop executing of your script.
Thouh, you can make some error reporting system.
$lastError = null
Then do what you want and set this error.
Then you can check it in some place:
if ($lastError == 2){
echo "The file is no in PDF format" ;
} //and so on.
Also you could create some constants like:
define("ERROR_WRONG_FORMAT", 2); //Make the error clear.
You'll need to echo out div tags and then position them using CSS.
die('<div id="error">pdf file only.</div>');
Then add the following text to your CSS:
#error{position:absolute;top:10;left:10;}
You'll need to change the top and left values depending on where you wnat them to be.
If you don't know what CSS is, I suggest you watch TheNewBoston's tutorials on YouTube!
when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.
I'm not sure how try catch works, but I want to do something like:
try: getimagesize($img) $works = true
catch: $works = flase
Like you said, if used on a non-existing file, getimagesize generates a warning :
This code :
if ($data = getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
will get you a
Warning: getimagesize(not-existing.png) [function.getimagesize]:
failed to open stream: No such file or directory
A solution would be to use the # operator, to mask that error :
if ($data = #getimagesize('not-existing.png')) {
echo "OK";
} else {
echo "NOT OK";
}
As the file doesn't exist, $data will still be false ; but no warning will be displayed.
Another solution would be to check if the file exists, before using getimagesize ; something like this would do :
if (file_exists('not-existing.png') &&
($data = getimagesize('not-existing.png'))
) {
echo "OK";
} else {
echo "NOT OK";
}
If the file doesn't exist, getimagesize is not called -- which means no warning
Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.
For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.
Finally :
I would allow errors to be displayed on your developpement server,
And would not display those on your production server -- see display_errors, about that ;-)
Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:
ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
print "NOT OK";
# We could even print out the warning here, just as PHP would do
print "$resize_warning";
} else {
print "OK"
}
Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.
I'm sorry that raise such old topic. Recently encountered a similar problem and found this topic instead a solution. For religious reasons I think that '#' is bad decision. And then I found another solution, it looks something like this:
function exception_error_handler( $errno, $errstr, $errfile, $errline ) {
throw new Exception($errstr);
}
set_error_handler("exception_error_handler");
try {
$imageinfo = getimagesize($image_url);
} catch (Exception $e) {
$imageinfo = false;
}
This solution has worked for me.
try {
if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
{
return $photoUrl;
}
} catch (\Exception $e) { return ''; }
Simple and working solution based on other answers:
$img_url = "not-existing.jpg";
if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
print_r($img_size);
echo "OK";
} else {
echo "NOT OK";
}