I am totally confused with session variables. I thought that if I set a session variable, then that variable will be available in any php document that begins with session_start. But it's not working.
Form:
<?php
session_start();
if(isset($_POST['hour'])) {
$_SESSION['hour'] = $_POST['hour'];
}
?>
<!DOCTYPE html>
<html>
<body>
<form action='viewA.php' method='post'>
<input type="text" name='hour' value='24'>
<input type ='submit' name= 'submit' value='submit'>
</form>
</body>
</html>
I post to viewA.php, and it works:
<?php
$hour = $_POST['hour'];
echo 'I am view A, and hour is '.$hour;
?>
<html>
<a href='View_B.php'>See View B</a>
<a href='TEST_form.php' >Choose another hour</a>
</html>
The file viewA.php has a link to View_B.php; here's View_B's code:
<?php
session_start();
print_r($_SESSION);
//$hour = $_SESSION['hour'];
//echo '... and in view B, hour is '.$hour;
?>
<html>
<a href='aatestform.php' >Choose another hour</a>
</html>
No matter what I put into the input in the form, the print_r($_SESSION); View_B outputs only Array ( [hour] => 13 ), which is the first hour I chose way back when. I type in "22"; it outputs 13. I type in "08", it outputs 13.
According to w3schools, "To change a session variable, just overwrite it"
What am I doing wrong? Please help!
In your viewA.php you don't store / overwrite the session variable with the $_POST value.
You just do it in your TEST_form.php which doesn't get any $_POST so your if(isset(... is useless.
Your post destination (the action) is viewA.php, this means that your request will be made to viewA.php.
You're using session variabiles only in the form page and in View_B.php.
If you look carefully at your code in ViewA.php, you'll see that you're working only with POST variables, not session variables.
This php code, that you have in your form page
<?php
session_start();
if(isset($_POST['hour'])) {
$_SESSION['hour'] = $_POST['hour'];
}
?>
Should be moved to viewA.php.
Doing this, viewA.php will check if the POST variable "hours" is set. In that case, it overwrite (or create) the session variable "hours".
Related
I have test.php:
<html>
<?php
if (!isset($_SESSION))
{
echo 'session is not yet set';
session_start();
$_SESSION['comments'] = array();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" name="comment">
Click the button!
<input type="submit"/>
</form>
<?php
array_push($_SESSION['comments'], $_GET['comment']);
echo 'Current array count: ' . count($_SESSION['comments']) . '<br>';
foreach($_SESSION['comments'] as $comm)
{
echo $comm.'<br>';
}
?>
</html>
What should happen is that any text entered in the textbox should be pushed to the session array, but every time I click on submit, what is printed is the text I just entered instead of appending/storing the previous entries. I only get 1 as the array count all the time.
Every time I hit submit, session is not yet set always shows at the top of the page even when I have the if condition.
I can't seem to find what's wrong?
You need to do this:
<?php
session_start();
if (!isset($_SESSION))
{
?>
Otherwise you have header output from the HTML tag and the session can't start properly.
You should start the session at the top of the page always.
session_start(); //start the session
Then we can check session is exist or not.
if(!isset($_SESSION['user'])){
// your code
}else{
// your code
}
session_start() does not just start a NEW session. If the client already has a session it resumes that session. PHP Manual
If you are using sessions, just have session_start(); at the top of the page and PHP will do the lifting of starting or resuming a session.
How can i get the value of previous url in php code?
Here is the url page1.php
http://localhost/spk/kelulusan_process.php?lulus=10003
page2.php:
I want to get the parameter from the previous url in page1.php. I use
<?php
$_GET['lulus'];
?>
But the value is null.
For $_GET to work you have to redirect user using form action
Or you can do that by setting session variables and access them any page
You can try $_SERVER["HTTP_REFERER"]
But don't forget to escape $_SERVER["HTTP_REFERER"] since it's common for attacks.
Better is to store the current page in a $_SESSION var.
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['lastpage'] = $_SERVER['REQUEST_URI'];
Then when loading the next page:
if (!isset($_SESSION)) {
session_start();
}
// now you can access the last page
$lastpage = $_SESSION['lastpage'];
page2.php
<?php
echo htmlspecialchars($_GET["lulus"]);
?>
how are you trying to pass from page 1?
if through a form set the method to get and action to page2.php
in page1.php make sure you set the name
<form method="get" action="page2.php">
<input type="text" name="lulus">
<input id="submit" name="submit" type="submit" value="Send">
You cannot display $_GET['lulus']; in page2.php unless you write get parameter in page2.php.
Your code is redirect from page1.php to page2.php, You must set $_GET['lulus']; into one session and echo in page2.php
Page1.php
<?
$_SESSION['GET'] = $_GET['lulus'];
?>
Page2.php
<?
echo $_SESSION['GET'];
?>
Instead, echo $_GET['lulus'], you should echo in page2.php $_SESSION. Because $_SESSION variable was overrode by $_GET itself.
Use $_SERVER['HTTP_REFERER'] ... hopefully this will help you. And parse url something like below:
$url = $_SERVER['HTTP_REFERER'] ; //http://localhost/spk/kelulusan_process.php?lulus=10003
$array = explode("?lulus=",$url);
echo $array[1];
I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
if (!empty($_POST)) {
setcookie('Cname',$_POST['name'], time()+600);
setcookie('Cemail', $_POST['email'], time()+600);
// header("Location:HW2.php");
}
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$visibleForm = True;
if(isset($_COOKIE['name'])){
$visibleForm = False;
}
if(isset($_POST['submit'])){
$visibleForm = False;
echo "Your Name: ";
echo $_COOKIE['Cname'];
echo "<br>";
echo "Your Email: ";
echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
?>
<form action ="HW2.php" method="post">
Name:<font color = red>*</font> <input type="text" name="name"><br>
E-mail:<font color = red>*</font> <input type="text" name="email"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php // back to php
}
?>
</body>
</html>
I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds
session_start(); // starts the session, this will create a new session cookie on the client if there's not one already
if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
$_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
$_SESSION["email"] = $_POST["email"]; // same here
};
?>
<html>
<head>
<title> Assignment 2 Alcausin </title>
</head>
<body>
<?php
$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible
if ($visibleForm) { // if there's no session data, we display the form
echo '<form action ="HW2.php" method="post">Name:<font color = red>*</font> <input type="text" name="name"><br>E-mail:<font color = red>*</font> <input type="text" name="email"><br><input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
echo "Your Name: ";
echo $_SESSION["name"];
echo "<br>";
echo "Your Email: ";
echo $_SESSION["email"];
};
?>
</body>
</html>
First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";
Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))
You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.
When I post my form data:
<form action="layouts.php" method="post">
<input type="text" name="bgcolor">
<input type="submit" value="Submit" align="middle">
</form>
to a php page, "layouts.php", it returns the string, as expected.:
$bgcolor = $_POST['bgcolor'];
echo $bgcolor; //returns "red"
echo gettype($bgcolor); // returns "string"
But when I include "layouts.php" in another page it returns NULL.
<?php
include("php/layouts.php");
echo $bgcolor; //
echo gettype($bgcolor); //returns "NULL"
?>
How do I pass the variable to another page?
You'll have to use a session to have variables float around in between files like that.
It's quite simple to setup. In the beginning of each PHP file, you add this code to begin a session:
session_start();
You can store variables inside of a session like this:
$_SESSION['foo'] = 'bar';
And you can reference them across pages (make sure you run session_start() on all of the pages which will use sessions).
layouts.php
<?php
session_start();
$bgcolor = $_POST['bgcolor'];
$_SESSION['bgcolor'] = $bgcolor;
?>
new.php
<?php
session_start();
echo $_SESSION['bgcolor'];
?>
Give the form two action="" and see what happens. I just tried that on a script of mine and it worked fine.
A more proper way to solve this might exist, but that is an option.
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.