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.
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.
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.
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.
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 */
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With