Does include work like a function in php? - php

I have a PHP file as seen below that is a config file.
When I use return in my code and var_dump(include 'config.php');
I see an array, but when I delete return the result is
int 1
Does include work like a function in this case? And why I have to use return here?
<?php
return array(
'database'=>array(
'host'=>'localhost',
'prefix'=>'cshop_',
'database'=>'finalcshop',
'username'=>'root',
'password'=>'',
),
'site'=>array(
'path'=>'/CshopWorking',
)
);

The return value of includeis either "true"(1) or "false". If you put a return statement in the included file, the return value will be whatever you return. You can then do
$config = include config.php';
and $configwill then contain the values of the array you returned in config.php.

An include fetches PHP-code from another page and pastes it into the current page. It does not run the code, until your current page is run.
Use it like this:
config.php
$config = array(
'database'=>array(
'host'=>'localhost',
'prefix'=>'cshop_',
'database'=>'finalcshop',
'username'=>'root',
'password'=>'',
),
'site'=>array(
'path'=>'/CshopWorking',
)
);
And in your file, say index.php
include( 'config.php' );
$db = new mysqli(
$config['database']['host'],
$config['database']['username'],
$config['database']['password'],
$config['database']['database'] );
This way, you do not need to write all that stuff into every file and it is easy to change!
Here are some statements with similarities:
include - insert the file contents at that point and run it as if it were a part of the code. If the file does not exist, it will throw a warning.
require - same as include, but if the file is not found an error is thrown and the script stops
include_once - same as include, but if the file has been included before, it will not do so again. This prevents a function declared in the included file to be declared again, throwing an error.
require_once - same as include_once, but throws an eeror if the file was not found.

First off, include is not a function; it is a language construct. What that means is something you should Google for yourself.
Back to your question: what include 'foo.php does is literally insert the content of 'foo.php' into your script at that exact point.
An example to demonstrate: say you have two files, foo.php and bar.php. They look as follows:
foo.php:
<?php
echo "<br>my foo code";
include 'bar.php';
$temp = MyFunction();
bar.php:
<?php
echo "<br>my bar code";
function MyFunction()
{
echo "<br>yes I did this!";
}
This would work, because after evaluating the include statement, your foo.php looks like this (for your PHP server):
<?php
echo "<br>my foo code";
echo "<br>my bar code";
function MyFunction()
{
echo "<br>yes I did this!";
}
$temp = MyFunction();
So your output would be:
my foo code
my bar code
yes I did this!
EDIT: to clarify further, if you create variables, functions, GLOBAL defines, etc. in a file, these will ALL be available in any file in which you include that file, as if you wrote them there (because as I just explained, that is basically what PHP does).

Related

Resetting or deleting sessions/variables created in a require_once file?

If I create a php file and use require_once to include a php file in my project (paypalplatform.php). I then use one of the functions from paypalplatform.php in my own php file.
How do I remove paypalplatform.php from my own php file so all the sessions/variables etc set within paypalplatform.php are reset fully so I can use payypalplatform.php again later in my php file to call a different function from paypalplatform.php?
So basically the following works
--start of php file--
<?php
require_once("paypalplatform.php");
myarray = function_one_from_paypalplatform();
?>
--end of php file--
The following also works
--start of php file--
<?php
require_once("paypalplatform.php");
myarray = function_two_from_paypalplatform();
?>
--end of php file--
However, the following does not work:
--start of php file--
<?php
require_once("paypalplatform.php");
myarray = function_one_from_paypalplatform();
unset(myarray);
myarray = function_two_from_paypalplatform();
?>
--end of php file--
Let's say you'r using OOphp...
You have the file "something.php".
In something.php you have:
require_once('someelse.php');
On someelse.php you have:
public $var1 = 'test';
public $var2 = 'abc';
So, you have a index.php and use like that:
$obj = new something.php;
echo $obj->var1; //test
$obj->var1 = 'lol';
echo $obj->var1; //lol
unset($obj);
$obj = new something.php;
echo $obj->var1;//test
or use your include as a var.
$varinclude = require_once('something.php');
use as you wish, and when needs to reset, just include or something the phpfile on other var or rewrite the same.
Unset your session variables and variables. When you include a file, it becomes a part of a file into which you have included it.
The code above is not actually PHP though.

PHP Include an Array

I am creating a flat file login system for a client (as their IT team does not want to give us a database)
I have worked off this:Easy login script without database which works perfect however...
I need to add a large list of logins and wanted to include them in a septrate file rather than in that script.
I have something like this:
<?php
session_start();
// this replaces the array area of the link above
includes('users.php');
//and some more stuff
?>
And in the users file I have
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
However it just literally outputs the text from that file. Is there a way I can include it so it just runs like it was in the main script?
Cheers :)
Include in PHP works simply like a reference to other piece of code AND any other content. So you should enclose the contents of the file in the <?php tags so it would be parsed as PHP.
You may as well return anything from an included file (I mention this as this in your case is the best solution):
mainfile.php
<?php
session_start();
// this replaces the array area of the link above
$userinfo = include('users.php');
users.php
return array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
The statement name is actually include, and not includes.
Try the following:
include 'users.php';
And if your code is getting outputted as text, then it's probably because you've missed the opening <?php tags. Make sure they're present.
users.php should look something like this:
<?php
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
However, the closing tag is not a requirement and your code will work fine without it.
In Yii framework (configs for exmaple) it's done like this
$users = include('users.php');
users.php:
<?php
return array(
'user1' => array(...),
'user2' => array(...),
);
Make sure you have an opening PHP tag in the included file:
<?php
$userinfo = array(
'kate'=>'inciterocks!',
'nick'=>'inciterocks!'
);
users.php :
<?php
function getUsers(){
return array(
'user1' => array(...),
'user2' => array(...),
);
}
Some bootstrap file
include('users.php');
$myUsers = getUsers();

how to turn the output of a require statement into a string in php

im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get the final page. The thing is, i need some scrap of code developed by other member of the team, and i need it to be a string, but the code is available as a php file which im supposed to include or require inside my page.
Since im not writing an ht;ml page, but a function that generate that code, i need to turn the resulting html of the require statement into a string to concatenate it to the code generated by my function.
Is there any way to evaluate the require and concatenate its result to my strings?
Ive tried the function eval(), but didnt work, and read some thing about get_the_content(), but it isnt working either. I dont know if i need to import something, i think it have something to do with wordpress, and im using raw php.
thanks for all your help!!! =)
Try the ob_...() family of functions. For example:
<?php
function f(){
echo 'foo';
}
//start buffering output. now output will be sent to an internal buffer instead of to the browser.
ob_start();
//call a function that echos some stuff
f();
//save the current buffer contents to a variable
$foo = ob_get_clean();
echo 'bar';
echo $foo;
//result: barfoo
?>
If you want to put the echo'd result of an include into a variable, you could do something like this:
//untested
function get_include($file){
ob_start();
include($file);
return ob_get_clean();
}
or if you want to put the echo'd result of a function call into a variable, you could do something like this:
//untested
//signature: get_from_function(callback $function, [mixed $param1, [mixed $param2, ... ]])
function get_from_function($function){
$args = func_get_args();
shift($args);
ob_start();
call_user_func_array($function,$args);
return ob_get_clean();
}
Depending on how the other file works...
If the other file can be changed to return a value, then you should use:
$content = require 'otherfile';
If the other file simply uses echo or some other way to print directly, use:
ob_start();
require 'otherfile';
$content = ob_get_clean();
You can receive string with include or require but you have to update those files before including to add return statement.
the file to be included should return result like this
<?php
$var = 'PHP';
return $var;
?>
and you can receive the $var data by including that file
$foo = include 'file.php';
echo $foo; // will print PHP
Documentation section

Strange behavior when returning a value from an include

I am having a strange issue with getting an array returned from an include. The example taken from the manual shows the behavior I am expecting:
return.php
<?php
$var = 'PHP';
return $var;
?>
noreturn.php
<?php
$var = 'PHP';
?>
testreturns.php
<?php
$foo = include 'return.php';
// This is the expected behavior.
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>
My usage scnario gives different result. I load Zend_Config by calling it with a simple include that returns an array() :
config.php
<?php
/*
* Configuration options loaded in Zend_Config
*/
return array(
'localDB' => array('serverName' => 'TESTDB',
'uid' => 'TESTUSER',
'pwd' => 'TESTPW',
'DB' => 'TESTDB'
),
);
// in the app I can call Zend_config somewhat like this ...
$configfile = 'config.php';
// zend_config takes an array as parameter, returned by the included file...
$config = Zend_config(include $config);
All is fine. Except now I want to overide this array for test configuration, without changing the file, so I do this:
testConfig.php
$testsettings = include_once 'config.php';
// override the array
$testsettings['localDB']['serverName'] = "TEST";
//return the overriden array
return $testsettings;
Now, the weird part. It all works fine when I execute php -f testConfig.php and var_dump() $testsettings.
But if I include this file in a testcase to have orverriden settings value, the result is always a (bool) true, like the example include shown at top with no return value set.
I have thought of a few workarounds for this, but was wondering out of curiosity if anyone had a clue as to why it does this.
include_once returns true every time after the first one. So the line
$testsettings = include_once 'config.php';
sets $testsettings to true if you've included config.php anywhere in earlier code.
Perhaps it is not a bool, but a count of the array.
It's in the docs. Check out the section on Handling Returns - http://us2.php.net/manual/en/function.include.php. But basically - don't do this.

How do you eval() a PHP code through multiple levels?

I have this code:
$layout_template = template_get("Layout");
$output_template = template_get("Homepage");
$box = box("Test","Test","Test");
eval("\$output = \"$layout_template\";");
echo $output;
In the $template_layout variable is a call for the
variable $output_template, so then the script moves onto the $output_template variable
But it doesn't go any further, inside the $output_template is a call to the variable $box, but it doesn't go any further than one level
I would never want nested eval(), and especially not in any recursive logic. Bad news. Use PHP's Include instead. IIRC eval() creates a new execution context, with overhead whereas include() doesn't.
If you have buffers such as:
<h1><?php echo $myCMS['title']; ?></h1>
I sometimes have files like Index.tpl such as above that access an associative array like this, then you just do in your class:
<?php
class TemplateEngine {
...
public function setvar($name, $val)
{
$this->varTable[$name]=make_safe($val);
}
....
/* Get contents of file through include() into a variable */
public function render( $moreVars )
{
flush();
ob_start();
include('file.php');
$contents = ob_get_clean();
/* $contents contains an eval()-like processed string */
...
Checkout ob_start() and other output buffer controls
If you do use eval() or any kind of user data inclusion, be super safe about sanitizing inputs for bad code.
It looks like you are writing a combined widget/template system of some kind. Write your widgets (views) as classes and allow them to be used in existing template systems. Keep things generic with $myWidget->render($model) and so on.
I saw this on the PHP doc-user-comments-thingy and it seems like a bad idea:
<?php
$var = 'dynamic content';
echo eval('?>' . file_get_contents('template.phtml') . '<?');
?>
Perhaps someone can enlighten me on that one :P

Categories