Store a PHP variable once throughout a webpage. - php

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

Related

PHP session seen as local variable

I have a problem with PHP session. When i start session, and try to add a variable to it i can only get in the same PHP script where i declared it like it's normal variable. Browser debuger also seems to not see any variable in session.
<?php
echo session_start(); //This returns 1 so session is created
$_SESSION["A"] = "B";
echo $_SESSION["A"]; // And this prints "B" as predicted
?>
But there is nothing in session!
You are confusing server-side PHP sessions, with the client-side JavaScript sessionStorage here. Both are two completely different things.
https://www.php.net/manual/en/intro.session.php
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Browser debuger also seems to not see any variable in session.
PHP session data is kept on the server, the browser can never “see it”, unless you explicitly output it somewhere (as you did with echo $_SESSION["A"];, but even then it of course won’t show in the sessionStorage debug panel.)
i can only get in the same PHP script where i declared it like it's normal variable.
Then you most likely neglected to pick your session up again in the other script files. You need to call session_start at the beginning of all of them.

POST variables not persisting from page to page

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!

PHP session variables life

Newbie question, but I'm wondering if I'm missing something elementary here.
If I register a session variable in a page - isn't this variable supposed to be accessible from another page on the same site?
First, I register a variable in the file session_var_register.php:
<?php
$_SESSION["myusername"] = 'user';
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
When I open this page, it writes:
Session var myusername is set to user
As expected.
Then I open another tab and another page, check_session_var.php:
<?php
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>
This page is blank.
Isn't the point of a session variable that it should be accessible in the browser session, until the session is programatically destroyed or the browser closed?
I'm using IE 8 and Firefox 24, btw. Identical results.
You forgot
session_start()
On top, before using
$_SESSION
PS: Remember to call session_start() in every page you want to use $_SESSION.
The PHP docs state that you must call session_start() to start or resume a PHP session. This must be done before you try to access or use session variables. Read more here.
session_start();
Your session variables will be available on different pages of the same site but on top of each of these pages you must have at least:
session_start();
It works but not in all cases. You must also use the same session name (essentially a cookie name that stores id of your session) on all pages. Moreover cookies (which are essential (mostly) for sessions to work) may be made visible only in specific directory. So if for example you share the same host with other guys that use sessions too you do not want to see their variables and vice versa so you may want to have sth like that:
1) session_name( 'my_session_id' );
2) session_set_cookie_params( 0, '/my_dir', $_SERVER['HTTP_HOST'], false, true );
3) session_start();
You may also want to see your session variables on other servers and in such case custom session handlers may be useful. Take a day or two to implement yourself - great way to understand how sessions work hence I recommend.
Method
session_start();
Description
session_start() creates a session or resumes the current one based on a session identifier >passed via a GET or POST request, or passed via a cookie.
Usage in your case (and in the most of cases):
Put it before the $_SESSION usage.
Reference: session_start()
First Of all start session on that page
session_start();
your page like this way
<?php
session_start();
if (isset($_SESSION['myusername'])) {
echo 'Session var myusername is set to '.$_SESSION['myusername'];
}
?>

How to pass variables between php scripts?

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;

PHP: Over-writing session variables

Question related to PHP memory-handling from someone not yet very experienced in PHP:
If I set a PHP session variable of a particular name, and then set a session variable of the exact same name elsewhere (during the same session), is the original variable over-written, or does junk accumulate in the session?
In other words, should I be destroying a previous session variable before creating a new one of the same name?
Thank you.
$_SESSION works just like any other array, so if you use the same key each time, the value is overwritten.
Tom,
It depends on how you use the session variable, but it generally means "erasing" that variable (replacing the old value by the new value, to be exact).
A session variable can store a string, a number or even an object.
<?php
# file1.php
session_start();
$_SESSION['favcolor'] = 'green';
$_SESSION['favfood'] = array('sushi', 'sashimi');
?>
After this, the $_SESSION['favcolor'] variable and the $_SESSION['favfood'] variable is stored on the server side (as a file by default). If the same user visit another page, the page can get the data out from, or write to the same storage, thus giving the user an illusion that the server "remembers" him/her.
<?php
# file2.php
session_start();
echo $_SESSION['favcolor'], '<br />';
foreach ($_SESSION['favfood'] as $value) {
echo $value, '<br />';
}
?>
Of course, you may modify the $_SESSION variable in the way you want: you may unset() any variable, append the array in the example by $_SESSION['favfood'][] = 'hamburger'; and so on. It will all be stored to the session file (a file by default, but could be a database). But please beware that the $_SESSION variable acts magically only after a call to session_start(). That means in general, if you use sessions, you have to call session_start() at the beginning of every page of your site. Otherwise, $_SESSION is just a normal variable and no magic happens :-).
Please see the PHP reference here for more information.

Categories