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.
Related
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).
I'm fairly new to PHP, and i have a problem in defining a function that returns an array containing a price and description strings.
I am using the "simple html dom" php files that facilitates parsing.
The function i create requires 2 arguments : the link (from which it will grab data) and the id (used to get the proper css syntax).
This is the get_product_details.php
<?
require_once 'simple_html_dom.php';
$priceMatchTable=('span[id=our_price_display]');
$descMatchTable=('div[id=short_description_content]');
function get_prod_details( $link , $id ) {
global $priceMatchTable, $descMatchTable;
$html = file_get_html($link);
$result['price'] = $html->find($priceMatchTable[$id],0);
$result['desc'] = $html->find($descMatchTable[$id],0);
return $result;
}
And this is the main php:
<?php
include 'get_product_details.php';
$link = 'http://micromedia.tn/barette-memoire/1170-barette-m%C3%A9moire-1go-ddr-ii.html';
$id = 0;
$result = get_prod_details($link, $id);
echo $result['price'];
?>
Finally i get an error which tell:
find($priceMatchTable[$id],0); $result['desc'] = $html->find($descMatchTable[$id],0); return $result; }
Fatal error: Call to undefined function get_prod_details() in C:\xampp\htdocs\dom\index.php on line 8
Best regards!
This may sound silliy, but is
include 'get_product_details.php';
really pointing towards "get_product_details.php"?
Disable (//) the function call in you index.php and add a simple echo to your "get_product_details.php" to see if the file gets included.
I think you need something like:
include '/path/from/root_to_your/directory/get_product_details.php';
If your trying this in Windows land, it will look something like:
include 'C:\Documents\something\get_product_details.php';
This is the weirdest bug! It is probably something silly, but I have no idea how to fix it. If anyone could help, I would be most grateful! I have three files, one is called items.php, another is called tableFunctions.php, and the third is called mysql.php. I use two global objects called 'mysql' and 'tableFunctions'. They are stored in the files 'mysql.php', and
'tableFunctions.php', respectively. In each file, I create an instance of its object, assigning it to the global variable $_mysql, or $_table. like this:
In the file mysql.php:
global $_mysql;
$_mysql = new mysql();
In the file tableFunctions.php:
global $_table;
$_table = new tableFunctions();
Here's how it is supposed to work:
The items.php file includes the tableFunctions.php file...
Which in turn, needs the mysql.php file, so it includes it too.
In the items.php file, I call the method getTable(), which is contained in the object tableFunctions.(and in the variable $_table.) Like this:
$t = $_table->getTable('items');
The getTable function calls the method, arrayFromResult(), which is contained within in the object mysql.(and in the variable $_mysql.) Like this:
$result = $_mysql->arrayFromResult($r);
That's where I get the error. PHP says that the variable '$_mysql' is undefined, but I defined it in the 'mysql.php' file.(see above) I also included mysql.php with the following code:
include_once 'mysql.php';
I have no idea what is wrong! If anyone can help that would be much appreciated.
The source files can be downloaded with the following link: https://www.dropbox.com/sh/bjj2gyjsybym89r/YLxqyNvQdn
That's a common mistake, in the place of definition you need only the line:
$_mysql = new mysql();
and when you want to use it inside a function, only there you have to declare it as a global variable (otherwise it is considered like any other function variable):
global $_mysql;
so, for example, if we'll take your method:
function getTable($tableName) {
$r = mysql_query("SELECT * FROM $tableName");
err($r, 'mysql returned null when getting table!');
$result = $_mysql->arrayFromResult($r);
return $result;
}
it should be changed to:
function getTable($tableName) {
global $_mysql;
$r = mysql_query("SELECT * FROM $tableName");
err($r, 'mysql returned null when getting table!');
$result = $_mysql->arrayFromResult($r);
return $result;
}
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
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