Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can check a php file is successfully included?

Tags:

include

php


I want to check if 'dbas.php' is included in 'ad.php'. I wrote the code -

ad.php

<?php if(file_exists("dbas.php") && include("dbas.php")){
// some code will be here
}
else{echo"Database loading failed";}
?>

I successfully tested the file_exists() part but don't know if the include() will work well or not, cause I tried in localhost and if the file is in directory then it never fails to include. So I don't know how this code would behave in the server if much traffic be there. So please tell me is my code correct ?

-Thanks.

Solved: Thank you so much for your answers.

like image 397
user1844626 Avatar asked Dec 06 '12 07:12

user1844626


People also ask

How do you check if file is already included PHP?

PHP's include() and include_once() functions can return values to the calling script which can be useful for testing to see if the file was actually included, for example if a configuration file whose filename is based on the website's domain name was included.

What is the correct way to include the file in PHP?

PHP Include Files. The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.

Why PHP include is not working?

You need to try the path of functions. php within the system and not its url. Do you have console access? If so just find out what directory is the file in and include it using the full path.


2 Answers

Using php's require method is more suitable if you want to be absolutely sure that the file is included. file_exists only checks if the file exists, not if it's actually readable.

require will produce an error if inclusion fails (you can catch the error, see Cerbrus' answer).

Edit:

However, if you don't want the script to halt if the inclusion fails, use the method is_readable along with file_exists, like:

if( file_exists("dbas.php") && is_readable("dbas.php") && include("dbas.php")) {
    /* do stuff */
}
like image 156
Alasjo Avatar answered Oct 12 '22 04:10

Alasjo


Simply use require:

try {
    require 'filename.php';
} catch (Exception $e) {
    exit('Require failed! Error: '.$e);
    // Or handle $e some other way instead of `exit`-ing, if you wish.
}

Something that wasn't mentioned yet: you could add a boolean, like:

$dbasIncluded = true;

In your dbas.php file, then check for that boolean in your code. Although generally, if a file doesn't include properly, you'd want php to hit the brakes, instead of rendering the rest of the page.

like image 25
Cerbrus Avatar answered Oct 12 '22 04:10

Cerbrus