How do I pass a session variable correctly? - php

I'm really new to PHP, and I'm trying to use the simple captcha mentioned in this question
Numeric Captcha for PHP
What I'm trying to do is pass the $_SESSION['captcha'] to my current page, so it can compare with the input I just entered which is supposed to pass by the "form".
Here's my code:
<?php
if(isset($_POST['captcha'] ,$_SESSION['captcha'])) {
if ($_POST['captcha'] == $_SESSION['captcha'])
echo 'YES, YOU DID IT';
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>captcha test</title>
</head>
<body>
<form name="input" action="index.php" method="POST">
<img src="captcha.php">
Enter the code above: <input type="text" name="captcha">
<input type="submit" value="Submit">
</form>
</body>
</html>
What's the correct way to do this? How can I implement the captcha in my current code?

A few things fixed here:
First you did not use a session_start() to actually retrieve $_SESSION values. Added here.
Next, you should check if the values are not empty by using !empty() in addition to isset(). Added here as well.
Finally, I recommend you use === comparison operator instead of ==. While == will check if values are the same, === will check if they are the same and the same data type.
Here is the cleaned up code:
<?php
session_start();
if (isset($_POST['captcha'], $_SESSION['captcha']) &&
!empty($_POST['captcha']) && !empty($_SESSION['captcha'])) {
if ($_POST['captcha'] === $_SESSION['captcha']) {
echo 'YES, YOU DID IT';
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>captcha test</title>
</head>
<body>
<form name="input" action="index.php" method="POST">
<img src="captcha.php">
Enter the code above: <input type="text" name="captcha">
<input type="submit" value="Submit">
</form>
</body>
</html>
If this still does not work for you, you can dump the values of $_POST and $_SESSION like this to see what you are getting:
echo '<pre>';
print_r($_POST);
echo '</pre>';
echo '<pre>';
print_r($_SESSION);
echo '</pre>';

You didn't add session_start() at the 1st line, thus the $_SESSION is empty.
Side Note:
You mixed up XHTML and HTML. xmlns is not required for HTML.
DOCTYPE is missing

You need to start your session with
session_start();
as a first call before your script has any output.
See documentation: http://php.net/manual/en/function.session-start.php

Related

I am using a Html form with PHP, how do i use $_GET to be assigned to a variable to be used in an IF statement in this specific code

This is my html page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello and welcome to my site</title>
</head>
<body>
<p>are these 2 numbers equal? type yes or no in the box</p>
<p2>one</p2> and eight
<form action="welcome_get.php" method="get">
Answer: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
this is my new php page containing a previous answer and im having new errors
<html>
<body>
<?php
var_dump($_GET['name']);
$answer = $_GET['name'];
$saying = "congratulations";
if ($answer == "yes"){
echo $saying;
}
?>
</body>
</html>
the new errors are referring to my php page which is welcome_get.php
var_dump($_GET['name']);
Additionally, to see all available GET params:
var_dump($_GET)
To assign to a new variable:
if(!empty($_GET['name'])){
$answer = $_GET['name'];
if($answer == 'something'){
// do something
}
}
You can use isset function to check if $_GET['var'] is set
if(isset($_GET['name'])){
$answer = $_GET['name'];
$saying = "congratulations";
if ($answer == "yes"){
echo $saying;
}
}

$_POST read out values in PHP

It is not possible to read out the $_POST variable with this code. Can you please give me a hint where the problem is? The condition block does not work.
When reading out the POST content from the Browser the values seem to be set and transfered.
<!doctype html>
<?php
// select post operation
echo "post=".$_POST["action"];
if ($_POST["action"] == "add"){
// insert and read out values from DB
echo "add-".$_POST["action"];
header("Location:".($_SERVER['PHP_SELF']));
unset($_POST);
} elseif ($_POST["action"] == "delete"){
echo "add-".$_POST["action"];
header("Location:".($_SERVER['PHP_SELF']));
unset($_POST);
}
else{
echo "why else after submit.";
}
$_REQUEST = $_POST = $_GET = NULL;
?>
<html lang="de">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>test</title>
</head>
<body>
<div>
<form action="<? echo ($_SERVER['PHP_SELF']);?>" method="post">
<input type="hidden" name="action" value="add">
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
You never check if a POST was actually performed, so your if() chain ALWAYS executes. When you first hit the page, that loads it as a GET, therefore you get the why else after submit error.
You need something more like this:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... check form submission, echo confirmation/errors, blah blah blah
}
... output html ...
Cause you redirect to an other page with
header("Location:".($_SERVER['PHP_SELF']));
actually you redirect to the same page so a brand new (same) page is served to you with an empty $_POST variable

Passing session variables to more than 3 page and back in php

The first page (inputform1test.php)
<?php require_once('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Input (Test)</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="inputdisplaytest.php">
<p>Name
<input type="text" name="name" id="textfield" />
</p>
<p>Text
<input type="text" name="text" id="textfield2" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
Second page(inputdisplaytest.php)
To test if it's working in 2nd page(inputdisplaytest.php)
<?php include('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['name']= $_POST['name'];
$_SESSION['text']= $_POST['text'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Display Input (Test)</title>
</head>
<body>
<table width="200" border="0">
<tr>
<td><?php echo $_SESSION['name']?></td>
<td><?php echo $_SESSION['text']?></td>
</tr>
</table>
inputdisplaytest_2.php
</body>
</html>
Third page(inputdisplaytest2.php)
This is the part where I got the error
<?php include('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Display Input (Test)</title>
</head>
<body>
<table width="200" border="0">
<tr>
<td><?php echo $_SESSION['name']?></td>
<td><?php echo $_SESSION['text']?></td>
</tr>
</table>
<p>inputdisplaytest.php</p>
</body>
</html>
I clicked to see if it's still working on 2nd page. (Which is not working)
I got the undefinex index problem when I go to the hyperlink and "Document Expired" when I clicked back button via browser.
How do I get the session variables back/not expire?
Any help would be appreciated.
You don't need the
if (!isset($_SESSION)) {
session_start();
}
just use session_start() at the beggining of your script. Even before those includes.
You can't print anything before the session_start. Check your logs for errors.
I believe the reason you're finding this error is because you are POSTing the form data. When you POST the form data, it is sent when you hit Submit. Going back to the form will give you the message to reload the form data. If you change it to GET, your form data should stick.
Remove if statements that you're using to check if session is set, because in your case the session_start() is never being executed, since the $_SESSION array is always set by PHP unless you perform unset($_SESSION) which is deprecated, this will unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal array. So:
if(!isset($_SESSION)){
session_start();
}
becomes:
session_start();
this resolves the problem of undefined index error.
To resolve the browser back button error when navigating back to the page processing your form, you have to put:
session_cache_limiter('private_no_expire');
before session_start() on second.php file, this line of code avoid "Page Has Expired" warnings, you can find more explanation here avoid "Page Has Expired" warnings.
Finally, after session_start() on second.php file, add the following code:
if(isset($_POST['button'])){
$_SESSION['name']= $_POST['name'];
$_SESSION['text']= $_POST['text'];
}
to check if the form was submitted or not, if yes, you can process the data and display the page, else you just display the page using the perviously stored data on your session.
I have had issues with this myself, where the session variables are not passed on, and recently came across the answer. I am sorry that I cannot credit the person who answered this in a previous post because I cannot find the post again. Simply put, sometimes, especially on shared hosting, the sessions are not stored in the right place. You can fix this by forcing the sessions to be saved in a particular spot. My solution was:
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/session'));
My session file is in the domain's root folder.
I then start the session:
session_start();
And then I make sure that the person is signed in:
if(isset($_SESSION["your_variable"])) {
$your_variable = $_SESSION["your_variable"];
//add any other session variables in the same manner
//be sure to rename "your_variable" with the name of your variable
}else{
header('Location: signin.php');
exit;
}
The header redirect at the bottom is where the person is going if they are not signed in or the session variable is not found, so that the session variables are passed to this page. Note the exit, it keeps your code safer. So altogether my first lines of code are:
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . `'/session'));`
session_start();
if(isset($_SESSION["your_variable"])) {
$your_variable = $_SESSION["your_variable"];
}else{
header('Location: signin.php');// or wherever your sign in happens to be
exit;
}
I hope this helps.

Problem with PHP 'PHP_SELF'

I am having a bit of trouble. It does not seem to be a big deal, but I have created a page that the user can edit a MySQL database. Once they click submit it should process the php within the if statement and echo 1 record updated. The problem is that it does not wait to echo the statement. It just seems to ignore the way I wrote my if and display the whole page. Can anyone see where I went wrong.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php require("serverInfo.php"); ?>
<?php
$res = mysql_query("SELECT * FROM cardLists order by cardID") or die(mysql_error());
echo "<select name = 'Cards'>";
while($row=mysql_fetch_assoc($res)) {
echo "<option value=\"$row[cardID]\">$row[cardID]</option>";
}
echo "</select>";
?>
Amount to Add: <input type="text" name="Add" />
<input type="submit" />
</form>
<?php
if(isset($_POST['submit']));
{
require("serverInfo.php");
mysql_query("UPDATE `cardLists` SET `AmountLeft` = `AmountLeft` + ".mysql_real_escape_string($_POST['Add'])." WHERE `cardID` = '".mysql_real_escape_string($_POST['Cards'])."'");
mysql_close($link);
echo "1 record Updated";
}
?>
<br />
<input type="submit" name="main" id="main" value="Return To Main" />
</body>
</html>
if(isset($_POST['submit']));
1) Should not have a semicolon after it.
2) $_POST['submit'] is not set. You have to set a name on your submit button and give it a value. Just setting the type to 'submit' does not return a value for $_POST['submit'] in PHP.
You've got a ; after your if statement.
I noticed that you have two submit buttons and I assume that you are using the first one.
Try giving it a name="submit" and a value too.
Of course it doesnt. PHP runs in the server side, not in browser!
Open your page source. There is no PHP. Nothing to wait.
You need another page to send your form to.
And it is a big deal. It's a cornestone of understanding how the web does work.

PHP if-statement using $_POST variable doesn't seem to work. Why?

On one PHP server I have two files. One file (the name is "first.php") contains this code:
<html>
<head>
<title>First Page</title>
</head>
<body>
Please enter your password and age:
<form action="pass.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
The other file ("pass.php") contains this code:
<html>
<head>
<title>Secon Page</title>
</head>
<body>
<?php
if ($fname=="Jack")
echo "You are Jack!";
else
echo "You are not Jack!";
?>
</body>
</html>
As far as I understand, if a user enters "Jack" in the first page, than the second page should be displayed with "You are Jack!" line, but it doesn't happen. Why is it so?
On your second page, instead of checking for $fname, check for $_POST['fname'] instead. I think that is all you are missing.
You probably don't have register_globals set. This is depreciated and will be removed in 6.x. So for good programming you should instead of $fname try $_POST['fname'] on your second page.
pass.php needs to look like this
<html>
<head>
<title>Secon Page</title>
</head>
<body>
<?php
if ($_POST['fname'] =="Jack")
echo "You are Jack!";
else
echo "You are not Jack!";
?>
</body>
</html>
It might help to set the post values as variables and work with that. Something like this:
foreach($_POST as $key => $value)
{
$$key = $value;
}
Then whatever is posted will be available rather than using $_POST['xxxxx'] in your logic.

Categories