How can check a php file is successfully included? - 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.

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.

file_exists("dbas.php") Is doing the checking. If it exists, then do the include.
if(file_exists("dbas.php"){
include("dbas.php")
//continue with you code here
}

Put your functionality in a function and use function_exists to check if it is there.
include ("php_file_with_fcn.php");
if (function_exists("myFunc")) {
myFunc();
// run code
} else {
echo "failed to load";
}
In your case, the incusion file would be
function db_connect() {
$user = "user";
$pass = "pass";
$host = "host";
$database = "database";
mysql_connect($host, $user, $pass);
return mysql_select_db($database);
}
and the main file:
include("db_connect.php");
if (function_exists("db_connect")) {
if (db_connect() === TRUE) {
// continue
} else {
// failed to connect (this is a different error than the "can't include" one and
// actually **way** more important to handle gracefully under great load
}
} else {
// couldn't load database code
}

Use this code instead of your code, because in your code if file is not exist in server then php errors arise and that is not good so use this code:
if(file_exists("dbas.php")) {
include_once("dbas.php");
} else {
echo"file is not found";
}
This code means if file exists on server then function include else file is not found echo.

write
echo "file is includ"
at the end of "dbas.php"

Related

Phalcon: How to use Phalcon\Debug, but control the output for development/production environment?

I have a small application on the specified framework. I want to control what the user sees if my application fails. This should not be a standard web server response, which it is differently displayed by different browsers. In this regard, I want to use Falcon\Debug. But, as far as I understand, this component of the framework will always show something like this:
However, I would like to show this information only if debugging is enabled in my application (using an environment variable, for example). In other cases I would like to show just a page describing the error.
Question: how to implement this?
This is my implementation in the index.php file:
try {
$root = str_replace('\\', '/', dirname(dirname(__FILE__))) . '/';
require_once $root . 'apps/Bootstrap.php';
$bootstrap = new Bootstrap();
$bootstrap->run();
} catch (\Exception $e) {
if (DEV_MODE === true) {
$debug = new \Phalcon\Debug();
die($debug->listen()->onUncaughtException($e));
} else {
header('HTTP/1.1 500 Internal Server Error');
// Your fancy error page for users here!
die();
}
}
The idea is to have a variable somewhere in your config files which you can easily switch between true/false.
Update!
You can add this too:
if (DEV_MODE === true) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
} else {
error_reporting(0);
}
Complementing the proposal solution by Nikolay Mihaylov, maybe you want to redirect to a specific view and so not show blank page or default error 500 in browser, thereforce, only need add the NameSpace at the beginning
use Phalcon\Http\Response
and redirect in catch block, here a little example:
try {
// some code
} catch (\Exception $e) {
// ... some code
$response = new Response();
// Redirect...
$response->redirect('controller/view'); // for example, you could create a view to show error 500
// Send response to the client
$response->send();
}

Issue with PHP Include

I have a function called uploadfile:
<?php
function UploadFile (){
//ftp credentials set here
$connection = ftp_connect($server);
$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);
if (!$connection || !$login) { die('Connection attempt failed!'); }
$upload = ftp_put($connection, $dest, $source, FTP_ASCII, $startpos = 0);
if (!$upload) { echo 'FTP upload failed!'; }
ftp_close($connection);
}
I am calling it like this:
<?php
if( isset( $_REQUEST['modify'] ))
{
UploadFile();}
?>
The problem is that the code runs as soon as the page loads (without any call to the function). it seems to make no difference where the include_once 'upload file.php' is placed.
Obviously I don't want the code to run until the function is called.
Advice/pointers appreciated...
I believe the comments have pretty much answered the question.
The 'include_once' is not going to run the function, it just includes the reference to the function. You could even put the function in the same file as the if condition and it still won't run unless the if condition is met.
For a case where the function doesn't run, you could change the if condition to:
<?php
if(false){
UploadFile()
}
?>
If it is still running every time after this point, you have another call to UploadFile somewhere else in your code.

Check result of PHP include

I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.

An Include inside an if statement in Joomla-PHP

Im adding php inside an article using DirectPHP plugin.
My goal is to create a script that will include a file with text when the user has member = true; and when not to not show anything.
I have added this piece of code in a module in the top next to the logo:
<?php
if ($user =JFactory::getUser()->guest)
{
$member = false;
echo "Welcome guest, sign up and read nice quotes";
}
else
{
$member = true;
$user =& JFactory::getUser();
echo "Welcome " . $user->username;
}
?>
I have set member = true; now that the person has signed in. If he isnt signed in its on false.
Then inside the article I have:
<?php
if ($member == false)
{
$file = file_get_contents ('quotes/quotes.html');
echo $file;
}
?>
<hr id="system-readmore" />
<?php
if ($member == true)
{
include_once JPATH_SITE.'/quotes/random.php';
echo ShowQuotes();
}
?>
I cant find the problem making this not run. The quotes are shown for both $member = false; and $member = true; Are includes always being parsed despite the if statement? Same goes for file_get_contents? I tried to see if the $member declaration from the header is being kept within the parsing and wrote:
<?php
if ($member = true)
{
echo "Logged in";
}
?>
and it worked good so the problem is within the include_once and file_get_contents, I tried to pinpoint it as much as I can.
Thanks in advance for your help!
This is probably your issue:
if ($member = true)
{
echo "Logged in";
}
This is always assigning the value of true to $member.
Also here:
if ($user =JFactory::getUser()->guest)
You might have the same assignment problem (not sure if you intended to set $user and do a conditional at one here.
I might suggest getting in the habit of writing condditionals like this:
if (true === $member) { ... }
By inverting the order of the items, if you ever accidentally type = instead of == or ===, then you will get an error, instead of having the code silently perform unexpectedly.
You seem to have a scope issue here: you are declaring $member in a module, but $member won't be available to the article: and php will evaluate ($something == false) to always succeed if $something is undefined, if you want to check if a variable is really false you need to use ($something===false). Read more here: http://www.php.net/manual/en/language.types.boolean.php
That being said, since there is no real overhead to JFactory::getUser()->guest, just use that as well in you article!
btw, enable notices in your php configuration (either on screen or to a log file) and make sure you read that as you develop, it will tell you whatever is wrong, developing without seeing the errors is a guessing game, you can only bang your head against the wall so many times... you eventually need to switch on the light :-)

Cakephp - detect if unable to connect to database and recover gracefully

I have a few sites built with Cakephp. If any of these sites lose their connection to the database for whatever reason it does not handle it well. Basically it renders itself inside itself trying to display an error over and over until the browser crashes. The rendering itself inside itself is caused by the use of requestAction from elements.
What I want to know is how can I check if the database connection exists
I tried this in the app_controller before filter:
if(!ConnectionManager::getDataSource('default'))
{
die(); //this will be a message instead
}
but it does not seem to work.
Thanks
Use the following code:
<?php
$filePresent = true;
if (!file_exists(CONFIGS.'database.php')):
echo '<span class="notice-failure">Database configuration file is not present. Please contact admin#website</span>';
$filePresent = false;
endif;
if ($filePresent!=false):
uses('model' . DS . 'connection_manager');
$db = ConnectionManager::getInstance();
#$connected = $db->getDataSource('default');
if (!$connected->isConnected()):
echo '<p><span class="notice-failure">Not able to connect to the database. Please contact admin#website</span></p>';
endif;
endif;
?>
Here I'm printing messages (in those tags). You can replace the echo line with die().
(Cakephp 3.x)
Just follow the example given in PagesController's Home view:
Basically it is:
use Cake\Datasource\ConnectionManager;
try {
$connection = ConnectionManager::get('yourconnection');
$connected = $connection->connect();
} catch (Exception $connectionError) {
//Couldn't connect
}
//connected

Categories