How to put proper error handling on include php file - php

I'm linking a php file but I want to be handle it when it errors and notify the user, is this the proper way of error handling of include? Or is it too long? What is the better way?
<?php
try{
if ((include 'File.php') == TRUE){
}
else{
throw new Exception('Error loading the Parent Page: File.php ');
}
}
catch(Exception $e){
echo 'Message: ' .$e->getMessage(). ' Return to HomePage';
}

Just remove the if-statement and use require_once('File.php'); inside your try-catch-block.
Now change your Exception to Throwable and it should work.
<?php
try{
require_once('File.php');
} catch(Throwable $e) {
echo 'Message: ' .$e->getMessage(). ' Return to HomePage';
}
To check if the file exists, use:
if(file_exists('File.php')){
require_once('File.php');
}else {
echo "File not found";
}

It's good to use if-else block for checking whether you can include or require a file in the flow like this.
if( ! file_exists( 'File.php' )){
echo 'File does not exist' . 'Return to HomePage';
}
else{
require_once 'File.php';
}

Related

How to check if included file from a loop comes with errors

I have this kind of loop. On each iteration it should include a file, Included files can come with errors. Once some of included files gets an error the whole process of getting lost. How to prevent breaking of the process?
I tried this try catch but it errors from included files still cause stopping execution of file.
Thanks
foreach ($li_arrays as $index => $li_array) {
if($index == 0){
try {
require 'update.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}
elseif ($index == 1){
try {
require 'update1.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}else{
try {
require 'update2.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}
Errors in php are not recoverable, so they will always lead to the termination of your script.
I am not even sure that you are even talking about Errors, though if you are, this is the answer to your question.
Another thing to be aware of:
Require will throw an E_COMPILE_ERROR if the required file doesn't exist, which is also something you won't be able to catch.
If you don't want to terminate if the script isn't found, use include instead.
At the end I changed "require" with "include" and used this try-catch approach inside each included file.
$attempts = 0;
do {
try
{
////PHP code ///
} catch (Exception $e) {
echo "\n\n======EXCEPTION======\n\n";
var_dump($e);
$attempts++;
sleep(30);
continue;
}
break;
} while($attempts < 5);

Difficulties in working with If statement in PHP multiple form validation

I have been trying to Validate an HTML form with PHP which of course has worked successfully. Th problem then i'm kinda having problems on where to add include file which contain a successful message after all validation is made.
Here is my code:
<?php
$status=$codeErr="";
if (isset($_GET['check'])) {
$number=$_GET['number'];
$code=$_GET['code'];
if($number!=""){
if(preg_match("/[0-9]/",$number) and strlen($number)=="11"){
$four=substr($number, 0,4);
if($four!="0706" and $four!="0813" and $four!="0803" and $four!="0806" and $four!="0703" and $four!="0816" and $four!="0810" and $four!="0814" and $four!="0903"){
$status='<p class="status">Number Entered is not an MTN Number</p>';
}
}
else{
$status='<p class="status">Invalid Number Format</p>';
}
}
else{
$status='<p class="status">Please Enter an MTN Number</p>';
}
if($code!=""){
if($code!=="324"){
$codeErr='<p class="status">Winning Code Not Recognized</p>';
}
}
else{
$codeErr='<p class="status">Please Enter Your Winning Code</p>';
}
}
This include file displays the form if not set.
else if(!isset($_GET['check'])){
include('includes/check.php');
}
?>
Now i have another include file which contains a message to be displayed if all conditions are met while the check form goes off. Where do i include it?
You should use exceptions:
try {
if (!$somethingOne) {
throw new Exception('Something wrong one!');
}
if (!$somethingTwo) {
throw new Exception('Something wrong two!');
}
if (!$somethingMore) {
throw new Exception('Something wrong more!');
}
// success here only
echo 'All right!';
} catch (Exception $e) {
echo $e->getCode() . '<p>' . $e->getMessage() . '</p>';
}

How to catch require_once/include_once exception?

I'm trying to write code similar this:
<?php
$includes = array(
'non_existing_file.php', //This file doesn't exist.
);
foreach ($includes as $include) {
try {
require_once "$include";
} catch (Exception $e) {
$message = $e->getMessage();
echo "
<strong>
<font color=\"red\">
A error ocurred when trying to include '$include'.
Error message: $message
</font>
</strong>
";
}
}
I'd tried require_once and include_once, but try catch doesn't catch the exception.
How could I catch this fatal errors/warning exceptions?
Since include/require does not throw an exception, check before if the file your want to include exists and is readable. eg:
$inc = 'path/to/my/include/file.php';
if (file_exists($inc) && is_readable($inc)) {
include $inc;
} else {
throw new Exception('Include file does not exists or is not readable.');
}
These functions are throwing E_COMPILE_ERROR, and are not catchable like this.
To handle these errors see set_error_handler.
This solution (adapted from here) worked fine to me:
register_shutdown_function('errorHandler');
function errorHandler() {
$error = error_get_last();
$type = $error['type'];
$message = $error['message'];
if ($type == 64 && !empty($message)) {
echo "
<strong>
<font color=\"red\">
Fatal error captured:
</font>
</strong>
";
echo "<pre>";
print_r($error);
echo "</pre>";
}
}

Class to manipulate .ini files in php

I've been playing around with a php class I found on the net called Config Magik that I use to store some info in a INI file but have recently run into some problems when using removeKey. I wanted to know if someone can point me to a similar class that would work as well or better. Or if there is a better way to go about this.
This is my function right now, after playing around with it like crazy, so it is probably very faulty.
require_once('class.ConfigMagik.php');
$config = new ConfigMagik('config.ini', true, true);
if(!empty($_GET)){
if(!is_writeable('config.ini')){
echo 'Could not write to config.ini';
return false;
}
//if there is no section parameter, we will not do anything.
if(!isset($_GET['section'])){
echo false; return false;
} else {
$section_name = $_GET['section'];
unset($_GET['section']); //Unset section so that we can use the GET variable to manipulate the other parameters in a foreach loop.
if (!empty($_GET)){
foreach ($_GET as $var => $value){
echo $var.'='.$_GET[$var].'<br />';
//Check if said variable $var exists in the section.
if($config->get($var, $section_name) !== NULL){
//Set variable value.
try{
$config->set($var, $value, $section_name);
echo 'Setting variable '. $var.' to '.$value.' on section '.$section_name;
} catch(Exception $e) {
echo 'Could not set variable '.$var;
echo $e;
return false;
}
} else {
echo $var.' does not exist <br />';
}
}
}
try{
$section = $config->get($section_name); //Get the entire section so that we can manipulate it.
echo '<pre>';print_r($section);echo '</pre>';
foreach ($section as $title=>$value){
if(!isset($_GET[$title]) && isset($section[$title])){
try{
$config->removeKey($title, $section_name);
echo '<b>'.$title.'</b>: removed <br />';
} catch(Exception $e){
echo $e;
}
}
}
} catch(Exception $e){
echo $e;
}
$config->save();
//echo $config->toString('HTML');
echo true;
return true;
}
} else { RUN SOME HTML }
It basically saves the settings I pass on from the GET parameters and if the parameters are not there it is supposed to delete it. When I get to $config->removeKey($title, $section_name); in the last try catch statement it won't save automatically (as it should), so I tried running $config->save() and I ended up with a ini file that had section = array everywhere. Any advice will be appreciated as I've been learning PHP on the web for the last few weeks so I believe I've got a ways to go.
I have definitely isolated the problem to the $config->save() part, just don't know how to solve it.
Thanks in advance.
I have been using Zend_Config_Ini and Zend_Config_Writer_Ini in the past and was satisfied with the features. You will have extract the whole library/Zend/Config folder from Zend Framework and make Zend_Exception available though.

Try Catch cannot work with require_once in PHP?

I can't do something like this ?
try {
require_once( '/includes/functions.php' );
}
catch(Exception $e) {
echo "Message : " . $e->getMessage();
echo "Code : " . $e->getCode();
}
No error is echoed, server returns 500.
You can do it with include_once or file_exists:
try {
if (! #include_once( '/includes/functions.php' )) // # - to suppress warnings,
// you can also use error_reporting function for the same purpose which may be a better option
throw new Exception ('functions.php does not exist');
// or
if (!file_exists('/includes/functions.php' ))
throw new Exception ('functions.php does not exist');
else
require_once('/includes/functions.php' );
}
catch(Exception $e) {
echo "Message : " . $e->getMessage();
echo "Code : " . $e->getCode();
}
As you can read here : (emph mine)
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
This is about require, but that is equivalent to require_once(). This is not a catchable error.
By the way, you need to enter the absolute path, and I don't think this is right:
require_once( '/includes/functions.php' );
You might want something like this
require_once( './includes/functions.php' );
Or, if you're calling this from a subdir or from a file that is included in different dirs, you might need something like
require_once( '/var/www/yourPath/includes/functions.php' );
This should work, but it is a bit of a hack.
if(!#include_once("path/to/script.php")) {
//Logic here
}

Categories