I'm fairly new to PHP and am having trouble with variables. When I put everything in one PHP file, it works but my question is should this work? I am under the impression that when you include a file then the variables are also included. Assuming that is true, when connecting to a DB, is it good practice to connect in a separate PHP file then include that into pages where you need to use the DB?
page1.php
<?php
$test = "true";
?>
page2.php
<?php
$test = "false";
?>
home.php
<?php
include 'page1.php';
include 'page2.php';
echo $test;
?>
Expected output false but I am getting true.
When you include a file, PHP compiler extends the code with code in included file.
Basically the code:
include 'page1.php';
include 'page2.php';
echo $test;
changes to:
$test = "true";
$test = "false";
echo $test;
And you overwriting the $test variable.
including files is one of the methods to split and order logic in your project.
In some matters it provides performance benefits, when you include files only when you need them, and saves you from code duplication.
As for databases, it doesn't matter when or how you connect to it, often database connection related logic is held by separate file, just because it's easier to edit and mantain, similar to config files.
Also consider this part of code:
$PRODUCTION = 0; // defines if we are at home computer or at work
if( $PRODUCTION == 0 )
include ("connect_home.php");
elseif( $PRODUCTION == 1 )
include ("connect_work.php");
else
die("Oops, something gone wrong."); //don't connect if we are in trouble!
Related
I have been looking for a way to run one piece of code only once in php. I want to create and set a variable at the beginning of the webpage and whenever I call that file, the code will ignore that line.
I found this in which there are basically two suggestions: setting a session variable and creating a lock file which I don't want to since there might be many users at the same time and I need to have a lock file for each one of them.
I tried the first option but it doesn't work.
Here are my two files:
config.php
<?php
if (at the beginning){
$variable = something
echo 'hello';
}
else
do something
?>
second.php
<?php
require_once 'config.php'
//do some other stuff
?>
Whenever second.php is called, it prints 'hello' in the webpage, so if (at the beginning) returns true even though it is not at the beginning. Note that, I check whether at the beginning by if(!isset($_SESSION['done'])){ $_SESSION['done'] = 'done'; }
I wonder what is my mistake and how can I solve the problem. Any help is appreciated.
The program flow for config.php should be:
<?php
session_start();
if (!isset($_SESSION['done'])) {
$_SESSION['done'] = 1;
echo 'hello';
}
else {
// do something
}
?>
Hypothetical scenario, I have these files:
file1.php:
#!/bin/php
<?php
echo "starting\n";
$pid = pcntl_fork();
define('ME', 'Parent');
if($pid == 0) {
include 'file2.php';
exit;
}
echo "I am: ".ME;
file2.php:
#!/bin/php
<?php
define('ME', 'File2');
echo "Defined: ".ME;
When I run file1.php, I get an error, because ME is already defined and you can't re-define a constant. How can I tell php to reset ALL defined constants and variables, so that it can include a new file without carrying anything over? As far as I can see, my only options is to use shell_exec or similar to run a shell command to start a new php process, but that seems really roundabout - is there any way to clear out existing defined constants?
My specific use case is a large framework with many files included at various stages, much of which I can't touch, so you can assume that the only thing I'm able to modify in the above example is the contents of the if($pid == 0) { ... } brackets.
I am using PHP Include:
<?php include 'file1.php'; ?>
i want to only include the first few lines of file1.php - is this possible?
If you really want to include (run as PHP), then just pull those lines out into a new file:
new.php:
<?php
// line 1
// line 2
And include it in both files:
existing.php and other.php:
<?php
include('new.php');
...
<?php
$return_from_inc = include('file1.php');
?>
file1.php
<?php
if ($x === 1) { return 'A'; }
else { return 'B'; }
//... return ("break") running script wherever you want to
?>
Depending on the content of those first lines, why don't you use PHP Functions?
file1.php
<?php
function what_i_want_to_include(){
//"First lines" content
}
}
existing.php
<?php
include('file1.php');
what_i_want_to_include();
?>
Using functions it's the simplest way to do it.
You can simply use return on the line of your choice and control will be sent back to the calling file.
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call. return will also end the execution of an eval() statement or script file.
If called from the global scope, then execution of the current script file is ended. If the current script file was included or required, then control is passed back to the calling file. Furthermore, if the current script file was included, then the value given to return will be returned as the value of the include call. If return is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.
Source: PHP Manual
There are a few options to achieve this, but let me stress out that if this is necessary for your application to work you should really consider reviewing the app design.
If you want it programatically you can either grab the first x lines and use eval() to parse them. Example:
$file_location = '/path/to/file.php';
$number_of_lines = 5; //
$file_array = file($file_location);
if(!$file) {
return false; // file could not be read for some reason
}
$first_lines = array_slice($file_array, 0, $number_of_lines);
$to_be_evaluated = implode('', $first_lines);
eval($to_be_evaluated);
But you should take not that eval expects a string without the php opening tag (<?php), at least, not at the start. So you should search for it and delete it in the first line (if present):
if(strpos($first_lines[0], '<?php') !== false) {
$first_lines[0] = substr(strpos($first_lines[0], '<?php') + 5);
}
Another, and better option, and as suggested above, just pull out the required lines, save them to another file, and include them in both. You could also do this programatically, you could even extract the needed lines and save them to a temporary file on the fly.
Edit it is a 'weird' question, in the sense that it should not be necessary. Could you explain what exactly you are trying to do? Most probably we can come up with a nice alternative.
Edit
As I understand it correctly you have in the file-to-be-included a lot of stuff, but only the database settings are needed. In that case, put them elsewhere! Example:
settings.php
$connection = new mysqli($host, $user, $pass, $db);
if($connection->connect_error) {
die('This failed...');
}
header.php
<?php require_once('settings.php'); ?>
<html>
<head>
<title>My awesome website</title>
... other stuff
</head>
other_file.php
<?php
require_once('settings.php');
$r = $connection->query('SELECT * FROM `my_table` WHERE `random_field`=`random_value`');
etc. etc.
In settings.php you could also put everything in functions to ensure pieces are only executed when needed. You could in example create a get_connection() function, which checks if a database connection exists, otherwise creates it and returns it for usage.
No need for fancy eval() functions at all!
Please bear in mind that it isn't a crime to divide your application in a thousand files. It really isn't!
I'd like to include the results of a given script (let's say a.php) into another script (let's say b.php).
Although there is the PHP include statement and their other counterparts (include_once, require and require_once), it seems all of them include the file contents instead of its processing results as I would expect.
So how can I get a.php processed first and then include its results (not the file contents itself) into b.php script ?
On the other hand, if my included file (a.php) has a return statement, is the entire file expected to be processed first or its contents are also included into b.php as is ?
Thanks in advance for your replies.
a.php:
<?php
echo "world";
b.php:
<?php
ob_start();
include("a.php");
$a= ob_get_clean();
echo "Hello, $a!";
perhaps?
Sounds like you want to use the backtick operator followed by eval.
Something like this:
$code = `/path/to/myscript.php`;
eval($code);
If myscript.php isn't executable you'll have to prefix it with php, as in:
$code = `php /path/to/myscript.php`;
Note that you need to completely trust myscript.php, otherwise this is an security problem.
This probably isn't a very good design, you might want to think hard about whether or not there's a better way to do what you want.
If a.php is accessible via the web, you could use file_get_contents with an http:// (or https://) URL. This will access your script like an ordinary web page, having your web server process it through PHP and return the results.
a.php:
<?php
echo 2+2;
b.php:
<?php
echo file_get_contents('http://example.com/a.php');
Output:
4
You can also use output buffering, as mentioned in DaveRandom's comment above. That said, this is generally not exemplary application design. It's preferred to have code that will return the results you need rather than echo them. So maybe something like this:
a.php:
<?php
function calculateA()
{
return 2+2;
}
b.php:
<?php
include('a.php');
echo calculateA();
Output:
4
Edit: Several alternatives are nicely detailed on the include page in the PHP documentation.
Summary:
If php file belongs to your server:
ob_start();
$result = eval(file_get_contents('/path/to/your/script.php'));
ob_end_clean();
If not, but it's accessible via HTTP:
$result = file_get_contents('http://path.to/your/script.php');
I want to have a config file that basically says something like (Account: on/off), where an admin can choose on or off. And then, in my main script, i want a bunch of if else statements that says if its on, do this, if off, do this.
Any suggestions?
config.php:
<?php
$account = 'off';
main_script.php:
<?php
include('config.php');
if ($account == 'on') {
//do this
} else {
//do something else
}
Config files usually define global constants available everywhere in your code and often seen in the variable $GLOBALS['config']. Config files are normal PHP files that get included using include() or better include_once() at the very top of your applications main file.
include_once('config.php');
if ($GLOBALS['config']['admin']) doThis();
else doThat();
http://php.net/manual/de/reserved.variables.globals.php