Is there any way to pass values and variables between php scripts?
Formally, I tried to code a login page and when user enter wrong input first another script will check the input and if it is wrong, site returns to the last script page and show a warning like "It is wrong input". For this aim, I need to pass values from scripts I guess.
Regards... :P
To pass info via GET:
header('Location: otherScript.php?var1=val1&var2=val2');
Session:
// first script
session_start();
$_SESSION['varName'] = 'varVal';
header('Location: second_script.php'); // go to other
// second script
session_start();
$myVar = $_SESSION['varName'];
Post: Take a look at this.
You should look into session variables. This involves storing data on the server linked to a particular reference number (the "session id") which is then sent by the browser on each request (generally as a cookie). The server can see that the same user is accessing the page, and it sets the $_SESSION superglobal to reflect this.
For instance:
a.php
session_start(); // must be called before data is sent
$_SESSION['error_msg'] = 'Invalid input';
// redirect to b.php
b.php
<?php
session_start();
echo $_SESSION['error_msg']; // outputs "Invalid input"
Can't you include (or include_once or require) the other script?
The quick way would be to use either global or session variables.
global $variable = 'something';
The 'better' way of doing it would be to include the script and pass the variable by parameter like
// script1.php contains function 'add3'
function add3( $value ) {
return $value + 3;
}
// script2.php
include "script1.php";
echo 'Value is '.add3(2); // Value is 5
I would say that you could also store a variable in cache if you really need.
You can use:
temporary file (e.g. tempnam()),
cache (NoSQL: memcached, redis),
session variable ($_SESSION), but you need to start the session first.
I use extract() method to pass variable among PHP Scripts. It look like below example:
1. File index.php
<?php
$data = [
'title'=>'hello',
'content'=>'hello world'
];
extract($data);
require 'content.php';
2. File content.php :
<?php
echo $title;
echo $content;
Related
I'm trying to pass variables between consecutive pages of an automated php process. Because this is automated, I tried setting the variables like this in the prior page:
$_POST['index1'] = $variable1;
$_POST['index2'] = $variable2;
$_POST['index3'] = $variable3
$_POST['index4'] = "hard coded string";
I also have alert statements printing out these values on the prior page just to make sure they're getting set, which they are. But when I move to the following page and try to access those variables, I get undefined index errors for all of these variables. What's happening to the variables from one page to the next that they're not getting passed as expected?
Let's try the following since the information is sensitive.
At the very, very, very, very top of each of the PHP pages connected to this function add:
<?
session_start();
?>
Make sure nothing else is above it, no html, no nothing! Otherwise it will mess up whatever you are trying to do.
On the page you were originally setting your $_POST variables do the following:
$_SESSION["variable1"] = "You";
$_SESSION["variable2"] = "Shall";
$_SESSION["variable3"] = "Not";
$_SESSION["variable4"] = "Pass";
You can ofcourse change the "variable1","variable2" and all of its values into whatever you like.
On whichever page you have included
<?
session_start();
?>
You can now call echo/print/assign each of the $_SESSION variables you set before by echoing:
echo $_SESSION['variable1'];
This would produce the following: "You"
This is a more secure way of transferring data (however sessions can still be hijacked unless you're using HTTPS).
Whenever you are done using the data you can simply unset each $_SESSION variable by using either session_unset(); or session_destroy();
I hope this helps!
So I have a a variable called json that stores all of the json. I want to load this once in the site, and be able to use it through any php function that I have. So let's say I have this line of code placed at the beginning of index.php:
$json = file_get_contents('http:/xxxxxxxx/bp.json');
I want to be able to use this variable from a function somewhere else in the page, WITHOUT loading it again.
Thanks!
You could store your variables in the PHP session and call it anywhere in your application.
$_SESSION["favcolor"] = "green";
http://www.w3schools.com/php/php_sessions.asp
Also best practices is to destroy and/or clear all your session variables upon exiting your application.
1) Use global variables
<?php
$myVar = 1;
function myFunction()
{
global $myVar;
$myVar = 2;
}
myFunction();
echo $myVar; //will be 2
include 'another.php'; //you can use $myVar in another.php too.
?>
variables PHP manual
2) Use cookies
If you want your variable to be access from any browser window or after loading another page, you have to use COOKIES since HTTP is stateless. These cookies can be accessed via javascript since those are stored in client side browser and can be accessed by client.
<?php
setcookie("myVar","myValue",time()+86400);
/*
86400 is time of cookie expires. (1 day = 86400)
*/
?>
<?php
/*
Getting cookie from anywhere
*/
$myVar = $_COOKIE["myVar"];
echo $myVar;
?>
cookies PHP manual
3) Use a session
Best method to store your variables in server side which is secure than using cookies directly is by using a HTTP_SESSION
<?php
/*
Start a session.
Call this line top of every page you want to use session variables
*/
session_start();
// set variable
$_SESSION["myVar"] = "value";
?>
<?php
session_start();
// Access session variables from another php.
$myVar = $_SESSION["myVar"];
?>
sessions PHP manual
A simple way do this ,you can use Superglobals
Superglobals — Superglobals are built-in variables that are always available in all scopes
I think you must used supergloabls variables before like $_SERVER,$_GET,$_POST etc,and supergloabls variables also include $GLOBALS.
What is $GLOBALS
Note: Variable availability
Unlike all of the other superglobals, $GLOBALS has essentially always been available in PHP.
So you can do this
Get data from json file
Assign data to $GLOBALS
User $GLOBALS variable instead of $json
I have an array in one php1 file which I want to access in another php2 file but if i use either include or require once am also getting the output of the php1 file. I want to access only the variables from php1 but not the output. Can anyone suggest how to do that. In php1 I have lot of menus and boxes which I don't want to include in php2 except the variables.
<?
session_start();
require_once('home.php');
if($_GET["reset"]==1)
{
session_destroy();
header('Location: index.php');
}
?>
if i use this am getting all the output from the home.php page. I want only the variables.
Convert the variables on the home page to be accessible via a function or better still, make them session variables
is there some way without using function or session to access the variables
As per your request. A simple skeleton to show you how it is done.
We pass the variable $myVar through the URL and use $_GET in the next page to use it. We use htmlspecialchars(); to clean user input.
We use the if (isset($_GET['myVar'])) so it doesn't throw Notice: Undefined index error.
pageOne.php
<?php
$myVar = "My variable one.";
echo "<a href='pageTwo.php?myVar=" . $myVar . "'>Page Two</a>"
?>
pageTwo.php
<?php
if (isset($_GET['myVar'])) {
$myVar = htmlspecialchars($_GET['myVar'], ENT_QUOTES);
// Now you can use $myVar.
}
?>
I have two pages of php on the same folder , Im wondering what can I do to use that variable in another page like page2.php
page1.php
$variable = "Variable";
page2.php
//get $variable value from page1.php here
Any suggestions? Thank You
Use Sessions.
On page1.php:
session_start();
$_SESSION['var1'] = 'some text';
On Page2.php:
if(!isset($_SESSION)){
session_start();
}
echo $_SESSION['var1'];
You will get some test as output.
Use session variables.
Just write session_start() at the beginning of files to start a session and assign the session variables.
eg:
File-1
session_start();
$_SESSION['var'] = "var";
File-2
session_start();
if(isset($_SESSION['var']))
echo $_SESSION['var']; // will print "var"
You can use this throughout till the session destroyed. To destroy the session (may be on logout)-
if(isset($_SESSION['var']))
unset($_SESSION['var']);
To completely destroy the session-
session_destroy();
Or you can try constants like so:
constants.php
<?php
define("VARIABLE_1", "Hotdog");
?>
page2.php
<?php
include_once("constants.php");
echo VARIABLE_1;
// output == Hotdog
?>
Just include the constants php script in the pages you want to use the variables in.
Check PHP Sessions:
page1.php
session_start();
$_SESSION['variable'] = "Variable";
page2.php
session_start();
echo $_SESSION['variable']
You can require_once("page2.php") in page1.php
That will allow you to use variables in page 2 across page 1.
Alternatively, you can also use sessions.
session_start() starts a new session or resumes an existing session. Include this on the first line of both pages.
Session parameters are set using $_SESSION["parameter-name"] = "something";
You can use the variables anywhere in the script.
To terminate sessions, use session_destroy()
You can use Sessions to achieve this , also you should know about QueryStrings.
For example:
Navigate to another page say "location2.php?Variable=123" here ?Variable is your var and 123 is value.
And on location2.php you can get this by simply $_GET["Variable"];
This can be achieved in many ways. You can use php session, you can include a file where you create that variable, or you can define it as a consant.
All of that depends how complex is that problem and which suits you best in this case.
As I try to retrieve the variable status from the $_REQUEST[] array I set in the first script (and then do a redirect), I see nothing but a warning Undefined index: status. Why is that ?
<?php
$_REQUEST['status'] = "success";
$rd_header = "location: action_script.php";
header($rd_header);
?>
action script.php
<?php
echo "Unpacking the request variable : {$_REQUEST['status']}";
It is because your header() statement redirects the user to a brand new URL. Any $_GET or $_POST parameters are no longer there because we are no longer on the same page.
You have a few options.
1- Firstly you can use $_SESSION to persist data across page redirection.
session_start();
$_SESSIONJ['data'] = $data;
// this variable is now held in the session and can be accessed as long as there is a valid session.
2- Append some get parameters to your URL when redirecting -
$rd_header = "location: action_script.php?param1=foo¶m2=bar";
header($rd_header);
// now you'll have the parameter `param1` and `param2` once the user has been redirected.
For the second method, this documentation might be usefull. It is a method to create a query string from an array called http_build_query().
What you're looking for is sessions:
<?php
session_start();
$_SESSION['status'] = "success";
$rd_header = "location: action_script.php";
header($rd_header);
?>
<?php
session_start();
echo "Unpacking the request variable : {$_SESSION['status']}";
Note the addition of session_start() at the top of both pages. As you'll read in the link I posted this is required and must be on all pages you wish to use sessions.
What you are looking for is probably sending a GET parameter:
$rd_header = "Location: action_script.php?status=success";
header($rd_header);
that can be retrieved in the action_script.php via:
$_GET['status'];
You don't really need sessions or cookies in this case but you have to consider the fact that a GET post can be easily edited by the user.