try catch a failed include - php

This is a simple question one hour of Googling do not seem to solve. How do you catch a failed include in PHP? For the following code:
try {
include_once 'mythical_file';
} catch (Exception $e) {
exit('Fatal');
}
echo '?';
With mythical_file not existing, I get the output '?'. I know PHP can not catch failed required because it triggers a Warning Error, but here? What is the best way to catch a failed include? For example, the following works:
(include_once 'unicorn') or exit('!');
but it does not trigger an exception so I cannot retrieve file, line and stack context.

You can use require_once instead of include_once

include and include_once trigger warning (E_WARNING), require and require_once trigger error (E_COMPILE_ERROR). So you should use require or require_once.
php.net quote:
"require() is identical to include()
except upon failure it will also
produce a fatal E_COMPILE_ERROR level
error. In other words, it will halt
the script whereas include() only
emits a warning (E_WARNING) which
allows the script to continue. "

Related

Class 'MyDatabaseException' not found in /public_html/Connections/pdo.php on line 17

I'm not new to php but I'm unfamiliar with exceptions and OOP.
The problem here is that sometimes mysql doesn't load or loads after the web server. So I'm getting this fatal error:
PHP message: PHP Stack trace:
PHP message: PHP 1. {main}() /public_html/jpa.php:0
PHP message: PHP 2. require_once() /public_html/jpa.php:9
PHP message: PHP 3. require_once() /public_html/common/japan.php:9
PHP message: PHP 4. PDO->__construct('mysql:host=localhost;dbname=xxx;charset=utf8', 'xxx', 'xxx') /public_html/Connections/pdo.php:10
PHP message: PHP Fatal error: Class 'MyDatabaseException' not found in /public_html/Connections/pdo.php on line 17
Here is my code, copied directly from the PHP page.
<?php
try
{
$db = new PDO("mysql:host={$hostname_data_connect};dbname={$database_data_connect};charset=utf8", "{$username_data_connect}", "{$password_data_connect}");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $Exception )
{
// Note The Typecast To An Integer!
throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}
What I would like to achieve is to return a 503 maintenance message or redirect the user to a custom 503 maintenance message page instead of throwing a fatal exception. The time mysql finishes loading.
I have no idea how to do that. Please help.
Or perform a php check to test whether mysqld is up and running before executing the code above. Again I have no idea how to do that.
A snippet of code would be greatly appreciated. Dealing with that error for 3 years now.
MyDatabaseException is not a pre-defined PHP class, it's just an example name of something that you might create yourself, like $myString or myFunction(). But you haven't created any such class. Instead of just re-throwing the exception, perform your desired action in the catch block:
try {
// some db stuff
} catch PDOException($e) {
// maybe dynamically generate a 503 page
header('HTTP/1.1 503 Service Unavailable');
// output page content here
exit();
// or redirect to an existing one
header('Location: http://your.domain/your/503/page');
exit;
}

php session_start general error handling

I'm looking for a general way to handle session_start errors, not a way to handle one specific error. There are numerous errors which can happen, such as the session directory being full, which cause a fatal error. I want a way to trap those errors and handle them cleanly, without having to write custom handlers for each possibility.
Something like this (but not this as it doesn't work):
try{
session_start();
}catch(Exception $e){
echo $e->getMessage();
}
All help appreciated, thanks in advance.
The regular PHP session functions don't throw exceptions but trigger errors. Try writing an error handler function and setting the error handler before calling session_start.
function session_error_handling_function($code, $msg, $file, $line) {
// your handling code here
}
set_error_handler('session_error_handling_function');
session_start();
restore_error_handler();
However, this is just for capturing the session errors. A better way would be to create a general error handler that creates exceptions from errors and surround code parts that may throw errors with try ... catch blocks.

try/catch doesn't work in PHP

Why am I getting this error?
Warning: file_get_contents(http://www.example.com) [function.file-get-contents]: failed to open stream: HTTP request failed! in C:\xampp\htdocs\test.php on line 22
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\test.php on line 22
Here is the code:
try {
$sgs = file_get_contents("http://www.example.com");
}
catch (Exception $e) {
echo '123';
}
echo '467';
Aren't try\catch supposed to continue the excecution of the code? Or maybe there is some different way to do it?
try... catch is more for null object exceptions and manually thrown exceptions. It really isn't the same paradigm as you might see in Java. Warnings are almost deceptive in the fact that they will specifically ignore try...catch blocks.
To suppress a warning, prefix the method call (or array access) with an #.
$a = array();
$b = #$a[ 1 ]; // array key does not exist, but there is no error.
$foo = #file_get_contents( "http://somewhere.com" );
if( FALSE === $foo ){
// you may want to read on === there;s a lot to cover here.
// read has failed.
}
Oh, and it is best to view Fatal Exceptions are also completely uncatchable. Some of them can be caught in some circumstances, but really, you want to fix fatal errors, you don't want to handle them.
catch cannot catch a fatal error.
Just search for timeout in the manual for file_get_contents, there are several solutions listed there, here is one:
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 1
)
)
);
file_get_contents("http://example.com/", 0, $ctx);
try..catch will only catch exceptions. A fatal error is not an exception.
If PHP exceeds its maximum execution time, there's nothing you can do. PHP simply stops dead. It's the same if PHP runs out of memory: Nothing you can do to fix it after it's happened.
In other words, exceptions are errors you can potentially recover from. Fatal errors are, well, fatal and unrecoverable.
In PHP a fatal error will halt execution of the script. There are ways to do something when you run into them, but the idea of a fatal error is that it should not be caught.
Here are some good details: http://pc-technic.blogspot.com/2010/10/php-filegetcontents-exception-handling.html
Basically change your code to do the following:
try {
#$sgs = file_get_contents("http://www.example.com");
if ($sgs == FALSE)
{
// throw the exception or just deal with it
}
} catch (Exception $e) {
echo '123';
}
echo '467';
Note the use of the '#' symbol. This tells PHP to ignore errors raised by that particular piece of code. Exception handling in PHP is very different than java/c# due to the "after the fact" nature of it.
Fatal errors in PHP are not caught. Error handling and Exception handling are two different things. However if you are hell bent on handling fatal errors as exception, you will need to set up your own error handler and direct all errors to it, make your error handler throw exceptions and you can then catch them.
file_get_contents doesn't throw exception (and thus errors and warnings it throws aren't catchable). You are getting PHP warning and then fatal error, which explains you why the script doesn't continue - it exceeded limit for loading scripts set in php.ini.

Difference between "include" and "require" in php

Is there any difference between them? Is using them a matter of preference? Does using one over the other produce any advantages? Which is better for security?
require will throw a PHP Fatal Error if the file cannot be loaded. (Execution stops)
include produces a Warning if the file cannot be loaded. (Execution continues)
Here is a nice illustration of include and require difference:
From: Difference require vs. include php (by Robert; Nov 2012)
You find the differences explained in the detailed PHP manual on the page of require:
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.
See #efritz's answer for an example
Use include if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.
Using require means your script will halt if it can't load the specified file, and throw a Fatal error.
The difference between include() and require() arises when the file being included cannot be found: include() will release a warning (E_WARNING) and the script will continue, whereas require() will release a fatal error (E_COMPILE_ERROR) and terminate the script. If the file being included is critical to the rest of the script running correctly then you need to use require().
For more details : Difference between Include and Require in PHP
As others pointed out, the only difference is that require throws a fatal error, and include - a catchable warning. As for which one to use, my advice is to stick to include. Why? because you can catch a warning and produce a meaningful feedback to end users. Consider
// Example 1.
// users see a standard php error message or a blank screen
// depending on your display_errors setting
require 'not_there';
// Example 2.
// users see a meaningful error message
try {
include 'not_there';
} catch(Exception $e) {
echo "something strange happened!";
}
NB: for example 2 to work you need to install an errors-to-exceptions handler, as described here http://www.php.net/manual/en/class.errorexception.php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");
<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>
A very simple Practical example with code.
The first echo will be displayed. No matter you use include or require because its runs before include or required.
To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.
If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.
In case of Include Program will not terminate and display warning on browser,On the other hand Require program will terminate and display fatal error in case of file not found.

include or required

What should I use in the following statement? Include or required.
if(a ==b){
require 'requiredfile.php';
} else {
require 'requiredfile_2.php'
}
If in a function, I know that one, either include or require, only includes the file when called, the other one will include the file regardless. Am I correct?
The difference between include and require is that include will only emit a warning when the file is not found, and require will terminate with a fatal error.
If you are loading vital program parts, you probably want to go with require.
Manual
require() is identical to include() except upon failure it will also produce a fatal E_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.

Categories