Okey so I can't quite see how to do this but this is what I am trying to do. I need to update a SESSION that is used on multiply places on the website. I do this with ajax but when I change the SESSION it remains the same in the website as before the ajax call. here is an example:
index.php
<?php
session_start();
?>
<script>
function sessionUpdate()
{
//Do a get ajax call that send the 2 parameters to updateSession.php
}
</script>
<?php
$_SESSION['foo'] = "foo";
$_SESSION['bar'] = "bar";
echo"<div>";
echo"<p onclick="sessionUpdate()>Update Session</p>";
echo"{$_SESSION['foo']} {$_SESSION['bar']}";
echo"</div>";
?>
updateSession.php
<?php
session_start();
$_SESSION['foo'] = "new foo";
$_SESSION['bar'] = "new bar";
?>
Now, the sessions are used al over the site so I can't just replace the information from the ajax call in the example div with a innerHTML=data.responseText; at just that place. Anyway when I do this teh echo of the foo and bar sessions don't change, are they just static variables that can't be changed without a page reload or what is the problem?
As far as I understand, you open index.php and example div contains default values of session variables ('foo bar' in your example). After you click Update Session, doing innerHTML=data.responseText you can see updated session values ('new foo new bar' according to example). But after you reload index.php - it shows 'foo bar' again. According to your code, you do not check if you should set default session variables. Try to replace in your index.php
<?php
$_SESSION['foo'] = "foo";
$_SESSION['bar'] = "bar";
echo"<div>";
With
<?php
if(!isset($_SESSION['foo']))
$_SESSION['foo'] = "foo";
if(!isset($_SESSION['bar']))
$_SESSION['bar'] = "bar";
echo"<div>";
Updated code will check if session variable is set (user open index.php at the first time). Once it is not set - default values will be assigned, but once that is done, it will not override any future changes (so, after ajax call foo and bar variables will be set and your code will not rewrite its values)
Related
Hey guys I'm trying to pass a php variable to another page. I tried it with sessions but no result.
newspaper.php
$newspaper= $newspaper['newspath'];
print_r($newspaper);
this outputs:
path/to/the/newspaper.
Now I want to use the variable in the second page.
newspaperviewer.php
echo $newspaper;
$SESSION = $newspaper;
I tried the first one but no result. The second one seems to be faulty.
Hope you guys can help me out.
Session is what you are looking for. A session variable can store a value and use this value on all pages of your project.
First thing to do is to start session on each file on your project. You can do this like this example
<?php
session_start(); //declare you are starting a session
$_SESSION['newspaper'] = "New York Times"; //Assign a value to the newspaper session
?>
On the other file you can use the value of the session by trying something like this
<?php
session_start(); //always start session don't forget!!
echo $_SESSION['newspaper'];
// This will echo New York Times
?>
Store the variable after starting session on page A, like so:
// FIRST PAGE (foo.php)
session_start();
$_SESSION['name'] = 'Jack';
Now, on the second page (or any page that you want to have access to $_SESSION, simply do the same but pull the variable.
// SECOND PAGE (bar.php)
session_start();
$name = $_SESSION['name'];
$_SESSION['name'] = null; // Or use session_unset() to delete all SESSION vars.
And that's how you pass variables using $_SESSION.
Please use this code to set session
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
You can write like this
newspaper.php
session_start();
$newspaper= $newspaper['newspath'];
$_SESSION['newspaper'] = $newspaper;
Now you can use this session variable in
newspaperviewer.php
session_start();
$newspaper = $_SESSION['newspaper'];
echo $newspaper;
session_unset(); // remove all session variables
First
newspaper.php
$newspaper= $newspaper['newspath'];
//print_r($newspaper);
session_start(); //it starts your session here
$_SESSION['newspaper']=$newspaper; //it sets a session variable named as newspaper
Second
$newspaper= isset($_SESSION['newspaper'])?$_SESSION['newspaper']:''; //checks and sets value
echo $newspaper; //outputs value
For more see session_start
http://php.net/manual/en/session.examples.basic.php
First you will need to start the session by using session_start() at the top of your page. Second, a session variable is written like this: $_SESSION['foo'].
I suggest you read these pages to get a better understanding of what's going on.
http://php.net/manual/en/reserved.variables.session.php
http://www.w3schools.com/php/php_sessions.asp
I have this:
page1.php
Number of students<input type="number" name="number">
page2.php
I get the data from the <input> using the $_POST method and assign it to a var $a.
<? $a = $_POST['number']; ?>
page3.php
I define a fucntion in order to calculate something using a global variable.
<? function Calculate(){
global $a;
include 'page2.php'
echo (3+10)/$a;
}?>
Now, it says Warning: Division by zero in C:/.../page3.php on line 4
But if you define a var $a = 3, for example, in the page2.php and call it in page3.php
<? function Calculate(){
global $a;
include 'page2.php';
echo (3+10)/$a;
}?>
It works perfectly.
Assuming that $_POST method gather vars, why isn't working with a global allocation? Am I doing something wrong?
Any help or suggestion will be appreciate.
The value of $a will be set only when a POST request is made to page2.php. But then, you won't be able to call your function as it is in page3.php.
If you go directly to page3.php, then there is no POST request and the value of $a will be 0. Thus the Division by Zero error.
If you want, you can include the page3.php in your page2.php and call your function from there when the POST request is made. But when doing this, you won't be needing that declaration of $a in the function. Instead you can pass it as an argument to the function.
function calculate($a=1) {
/* Your code */
}
The $a=1 in the function header is used to supply default value when nothing is passed when the function is called.
So your page2.php will look like
<?php
$a = $_POST['number'];
include 'page3.php';
Calculate($a);
?>
and your page3.php will look like
<?php
function Calculate($a=1) {
echo (3+10)/$a;
}
?>
Good Luck!
The problem is not at the global variables, I doubt if you should use them in this case.
It's because of the $_POST['number']; your code fails.
When you include a page, the data of POST-request you did before (by submitting the form) does not exist anymore, resulting in no value being assigned to $a
However, when you're hard-coding $a = 3, the code will work because it's not depending on any kind of submitted data.
I would suggest you to go from page1 directly to page3 and retrieve the form values there, because I'm not getting the point of adding an extra page in-between.
I want to pass a couple of variables from one PHP page to another. I am not using a form. The variables are some messages that the target page will display if something goes wrong. How can I pass these variables to the other PHP page while keeping them invisible?
e.g. let's say that I have these two variables:
//Original page
$message1 = "A message";
$message2 = "Another message";
and I want to pass them from page1.php to page2.php. I don't want to pass them through the URL.
//I don't want
'page2.php?message='.$message1.'&message2='.$message2
Is there a way (maybe through $_POST?) to send the variables? If anyone is wondering why I want them to be invisible, I just don't want a big URL address with parameters like "&message=Problem while uploading your file. This is not a valid .zip file" and I don't have much time to change the redirections of my page to avoid this problem.
Sessions would be good choice for you. Take a look at these two examples from PHP Manual:
Code of page1.php
<?php
// page1.php
session_start();
echo 'Welcome to page #1';
$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();
// Works if session cookie was accepted
echo '<br />page 2';
// Or pass along the session id, if needed
echo '<br />page 2';
?>
Code of page2.php
<?php
// page2.php
session_start();
echo 'Welcome to page #2<br />';
echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);
// You may want to use SID here, like we did in page1.php
echo '<br />page 1';
?>
To clear up things - SID is PHP's predefined constant which contains session name and its id. Example SID value:
PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1
Here are brief list:
JQuery with JSON stuff. (http://www.w3schools.com/xml/xml_http.asp)
$_SESSION - probably best way
Custom cookie - will not *always* work.
HTTP headers - some proxy can block it.
database such MySQL, Postgres or something else such Redis or Memcached (e.g. similar to home-made session, "locked" by IP address)
APC - similar to database, will not *always* work.
HTTP_REFERRER
URL hash parameter , e.g. http://domain.com/page.php#param - you will need some JavaScript to collect the hash. - gmail heavy use this.
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['firstMessage'] = $message1;
$_SESSION['secondMessage'] = $message2;
?>
Stores the sessions on page 1 then on page 2 do
<?php
session_start();
echo $_SESSION['firstMessage'];
echo $_SESSION['secondMessage'];
?>
Have you tried adding both to $_SESSION?
Then at the top of your page2.php just add:
<?php
session_start();
Use Sessions.
Page1:
session_start();
$_SESSION['message'] = "Some message"
Page2:
session_start();
var_dump($_SESSION['message']);
In MVC, you can pass variable one page to another like this:
<?php $this->load->view('Overview', ['customer' => $customer , 'job_id' => $job_id , 'email' => $emailid]);?>
In Overview.php page you can display variable data like this
echo $customer; // it will display customer value
echo $job_id;
echo $email; // it will display email id
I am using Magento and trying to save a value in the session as follows in its index.php file, but the value is not being retained.
$_SESSION['myvar'] = '1';
How do I do it?
Thanks
Let's say you want to save the value "Hello world" to the "welcome message" variable in the session. The code would be :
$inputMessage = 'Hello World';
Mage::getSingleton('core/session')->setWelcomeMessage($inputMessage);
Now you want to echo the "welcome message" somewhere else in your code/site.
$outputMessage = Mage::getSingleton('core/session')->getWelcomeMessage();
echo $this->__($outputMessage);
Following the example given by Ali Nasrullah, I would do:
$session = Mage::getSingleton("core/session", array("name"=>"frontend"));
// set data
$session->setData("device_id", 4);
// get data
$myDeviceId = $session->getData("device_id");
Make sure you include [Mage-root]/app/Mage.php befor calling the code above!
#Ali Nasrullah: Pass the value of device:id as second parameter of the setData function.
Mage::getSingleton('core/session')->setMySessionVariable('MyValue');
$myValue = Mage::getSingleton('core/session')->getMySessionVariable();
echo $myValue;
Take Look For More:
Here are code to Get, Set, and Unset Session in Magento
Here are code to Get, Set, and Unset Session in Magento
frontend: Mage::getSingleton('core/session')->setYourNameSession($session_value);
backend: Mage::getSingleton('admin/session')->setYourNameSession($session_value);
First timer to the site, not an overly experienced php programmer here :)
I have a problem, i am using an iframe within a site which im attempting to use a session variable inside, firstly ive just been trying to display the session variable to make sure they are accessible from within the iframe:
echo "session of productcheck ".$_SESSION['productcheck']." ";
echo "session of productcheck1 ".$_SESSION['productcheck1']." ";
echo "session of productcheck2 ".$_SESSION['productcheck2']." ";
echo "session of productcheck3 ".$_SESSION['productcheck3']." ";
this just shows "session of product check" with nothing after each one, I set the session variable as such:
$_SESSION['productcheck'] = $productBox;
the $productBox is a GET from the URL:
echo " <iframe src=\"homeview.php?productBox=$product1\" name=\"FRAMENAME\" width=\"594\" height=\"450\" scrolling=\"No\" id=\"FRAMENAME\" allowautotransparency=\"true\" > </iframe >";
What's strange is if i just take the $productBox variable retrieved from the URL and use that then the code works, its only when i store it in a session variable that it gets confused. I want to retrieve a second $productBox and assign it to session var productcheck1 and so forth down the line. Unfortunately, i have to take one var in at a time, otherwise i could just pass all 4 products and not worry about the sessions.
Perhaps I'm making this far too complicated, any help would be much appreciated Thank you!!
You have to use session_start() in both scripts, the one setting the values (and presumably printing the <iframe>-element?) and the script that produces the contents for the iframe.
e.g. the "outer" script
<?php // test.php
session_start();
$_SESSION['productcheck'] = array();
$_SESSION['productcheck'][] = 'A';
$_SESSION['productcheck'][] = 'B';
$_SESSION['productcheck'][] = 'C';
session_write_close(); // optional
?>
<html>
<head><title>session test</title></head>
<body>
<div>session test</div>
<iframe src="test2.php" />
</body>
</html>
and the script for the iframe content
<?php // test2.php
session_start();
?>
<html>
<head><title>iframe session test</title></head>
<body>
<div>
<?php
if ( isset($_SESSION['productcheck']) && is_array($_SESSION['productcheck']) ) {
foreach( $_SESSION['productcheck'] as $pc ) {
echo $pc, "<br />\n";
}
}
?>
</div>
</body>
</html>
Not sure what's up with your session variables, but you can definitely pass all four variables through the url in your iframe. You just need to separate your key value pairs with an ampersand. So something like this:
file.php?key1=val1&key2=val2&key3=val3 and so on.
This is probably a better way than using session variables if your just trying to get data into that other file.