I want to run an external script, within the current script (for tidyness purposes) based on a series of if and else if statements.
Essentialyl what I want do is this...
if ($business_type == "Restaurant"); {require 'scripts/php/insert.php'}
else if ($business_type == "Hotel"); {require 'scripts/php/insert-hotel.php'}
Is this i the right way to call this external script?
That is the proper way of calling the scripts, but your syntax is just a little off :)
if ($business_type == "Restaurant"){
require 'scripts/php/insert.php';
}
else if ($business_type == "Hotel"){
require 'scripts/php/insert-hotel.php';
}
You might want to look into the documentation for Require and Include, but require is perfectly fine for what you're doing here.
Related
I have a PHP script which is typically run as part of a bigger web application.
The script essentially makes some changes to a database and reports back to the web user on the status/outcome.
I have an opening section in my PHP:
require $_SERVER['DOCUMENT_ROOT'].'/security.php';
// Only level <=1 users should be able to access this page:
if ( $_SESSION['MySecurityLevel'] > 1 ) {
echo '<script type="text/javascript" language="JavaScript">window.location = \'/index.php\'</script>';
exit();
}
So, basically, if the authenticated web user's security level is not higher than 1, then they are just redirected to the web app's index.
The script works fine like this via web browsers.
Now to my issue...
I want to also cron-job this script - but I don't know how to bypass the security check if ran from the CLI.
If I simply run it from the CLI/cron with 'php -f /path/to/report.php' and enclose the security check in a "if ( php_sapi_name() != 'cli' )", it spews out errors due to multiple uses of $_SERVER[] vars used in the script (there may be other complications but this was the first error encountered).
If I run it using CURL, then the php_sapi_name() check won't work as it's just being served by Apache.
Please can anyone offer some assistance?
Thank you! :)
If you invoke the script through the CLI some of the $_SERVER variables will be defined however their values may not be what you expect: for instance $_SERVER['DOCUMENT_ROOT'] will be empty so your require will look for a file called 'security.php' in the filesystem root. Other arrays such as $_SESSION will not be populated as the CLI does not have a comparable concept.
You could get around these issues by manually defining the variables (see "Set $_SERVER variable when calling PHP from command line?" however a cleaner approach would be to extract the code that makes the database changes to a separate file which is independent from any specific and that does not depend on any SAPI-specific variables being defined.
For instance your PHP script (let's call it index.php) could be modified like this:
require $_SERVER['DOCUMENT_ROOT'].'/security.php';
require $_SERVER['DOCUMENT_ROOT'].'/db_changes.php';';
// Only level <=1 users should be able to access this page:
if ( $_SESSION['MySecurityLevel'] > 1 ) {
echo '<script type="text/javascript" language="JavaScript">window.location = \'/index.php\'</script>';
exit();
} else {
do_db_changes();
}
Then in the SAPI-agnostic db_changes.php you would have:
<?
function do_db_changes() {
// Do the DB changes here...
}
?>
And finally you would have a file, outside the web root, which you can invoke from cron (say cron.php):
<?
require("/absolute/path/to/db_changes.php");
do_db_changes();
?>
Like this you can continue using index.php for the web application and invoke cron.php from cron to achieve your desired results.
Does anyone here know when PHP executes include and include_once calls?
I'm wondering because I come from a Flash and Desktop development background where you have to import your classes at the beginning of each class.
But now that I am starting to build more complex PHP code, it seems like it would be better to just include classes when I actually need them to save on loading time. For example, look at the following psuedo code:
if (I_need_to_check_login)
{
include_once "Class.class.php";
$C = new Class();
}
If I do this, is the file Class.class.php going to be included everytime the code is run or only when I execute the include_once.
I'm a bit of a Class freak and usually build a class for just about any functionality used by my apps, so I often have lots of class files.
include, include_once are standard PHP instructions. This means the interpreter executes each include, include_once when he finds one in the flow of the program. If a control structure avoids to execute a piece of code which has an include instruction, this one won't be executed.
In your example, the include_once, will be executed if, and only if, I_need_to_check_login is true.
Includes are only performed if interpreter ever gets there. eg:
$variable = false;
if ($variable) {
include 'a.php';
} else {
include 'b.php';
}
In this case only b.php would be included.
For more on its behavior: PHP Manual - include
Yes, every time you have to call: $C = new Class(); you will have to require or include the file. Now what you can do instead of include_once is:
if (!class_exists('MyClass')) {
include("Class.class.php");
}
which mean you might not have you include it again, if you already included it before. This will also improve performance since include is faster to execute than include_once.
Files are actually included only if you perform include_once command.
So if that I_need_to_check_login evaluates to false - file will not be included at all
It can be easily checked by yourself with adding echo "I've been included"; exit; to the first line of that file.
I have several pages which use the include or require language constructs within PHP. Many of these lie within IF, ELSE statements.
I do realize that a page will not load at all if a require'd file is missing but the main purpose of including this way is to:
1) reduce code clutter on the page
2) not load the file unless a statement is met.
Does issuing an include or require statement load the file regardless (and thus eliminating the benefits I was trying to achieve by placing within the if/else statement?
Brief example:
<?php
$i = 1
if($i ==1) {
require_once('somefile.php');
} else {
require_once('otherfile.php');
}
?>
At page load, are both files checked AND loaded?
If you place an include/require statement in the body of an if (or else), it'll be executed if the if's condition is true.
if ($a == 10) {
// your_first_file.php will only be loaded if $a == 10
require 'your_first_file.php';
} else {
// your_second_file.php will only be loaded if $a != 10
require 'your_second_file.php';
}
And, if you want, you can test this pretty easily.
This first example :
if (true) {
require 'file_that_doesnt_exist';
}
will get you :
Warning: require(file_that_doesnt_exist) [function.require]: failed to open stream: No such file or directory
Fatal error: require() [function.require]: Failed opening required 'file_that_doesnt_exist'
i.e. the require is executed -- and fails, as the file doesn't exist.
While this second example :
if (false) {
require 'file_that_doesnt_exist';
}
Will not get you any error : the require is not executed.
At page load, are both files checked AND loaded?
No, at least not since (IIRC) PHP 4.0.1.
If you want to reduce include clutter, and you are working with mainly object-oriented code, also take a look at PHP's autoloading.
No, only one of those files would be loaded.
The include and require constructs are only evaluated when passed. The files are only read when your expression is met.
It's simple to explain by considering that the constructs might contain variables:
require_once("otherfile-{$i}.php");
That's supported. But it could not possibly work before PHP runs over that particular line, because it needs to know the state of $i to load the right file.
The question its self-explanatory. Example:
$x = 0;
if($x == 2)
{
include("stackoverflow.php");
}
Does the file "stackoverflow.php" will be included?
and a Complementary Question:
Look to this example:
//thispage.php contents
$x = $_GET['x'];
if($x == 2)
{
include("stackoverflow.php");
}
Click Here
Lets suposse that the file "thispage.php" is sent to a lot of computers every second. does including the IF codes inside "stackoverflow.php" will make the file smaller to send to people if the IF has not been triggered?
Thankyou in advance
No, stackoverflow.php will not be included.
Actually, why didn't you just try it?
The code is only executed on the web server, so it really depends if there's content in the include, or more code.
If the code executes and doesn't send anything to the client, then it wouldn't make anything smaller either way.
Is the following example appropriate for PHP's require_once construct?
function foo( $param )
{
require_once "my_file.php" ;
//
// do something here
}
Or is it more appropriate to only have require_once constructs at the beginning of the file?
Even though the file being included is useful only in the context of the function, is it not better to have includes at the top for readability and maintainability?
It comes down to a matter of coding style and opinion. Personally I keep all my require_once statements at the very top of my files so I can easily see which files are included where, nothing worse then some buried include messing with your scripts. However, if you have several large required scripts that are only required for certain functions, then putting the require_once inside a function would be OK from a performance stand-point, just make sure to put a note at the top of the page.
<?php
//require_once "my_file.php" (see function foo)
function foo($param) {
require_once "my_file.php";
}
This is something of a religious debate.
PROS for require and include statements at the top of the file:
dependencies are clearly documented in a consistent reliable place.
increased readability/maintainability
OP code caching is simpler (although you could argue that this doesn't affect the developer directly)
CONS for require and include statements at the top of the file:
If you're doing some kind of dynamic runtime including (such as with __autoload()), a hardcoded statement at the top of the file is impossible.
If only one execution path in the code uses an include, having it included every time, unconditionally is a waste of resources.
long list of include or require statement is just noise the developer must scroll past when editing a file. Of course, a long list of dependencies can be viewed as a sign that the code should be broken up into smaller more focused pieces, so maybe you could spin this one as a PRO because it makes a code smell stand out.
If you don't want to load a file unless it's needed, look into autoloading - on newer PHP via spl_autoload_register().
Maybe you only need the included file in certain cases, and you'd like to avoid including it if you don't need it at all, if it's a big file. So, I guess you could go for a require_once only in one branch of an if - else statement.
When using require_once keep in mind that this is not some pre-processor directive. The require_once statements are executed when PHP runs the code and it only executes if the specific script has not already been included during the execution.
For example:
conf.php:
<?php
$maxAge = 40;
?>
myscript.php
<?php
function foo($age) {
require_once("conf.php");
if($age > $maxAge)
return "1";
else
return "0";
}
echo foo(30); // Echos 1
echo foo(30); // Echos 0
?>
The require_once is not executed on the second call to foo(..) since conf.php has already been included once.