$_POST read out values in PHP - 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

Related

Why does starting a session cause my function-generated form value to change when submitted?

I have a simple form, and use PHP to set the value of one of its fields by creating and echoing a hash. I'm not sure why, but when I submit the form without calling session_start() my $_POST variable shows the correct hash that was embedded in my HTML when the page first loaded. Starting a session causes the hash to change when the form is submitted, almost as if the hash function is being called again.
This sort of makes sense to me, but this was not always happening; I haven't changed my code, and previously tested this functionality.
I'm using XAMPP to test my program on my local server, and compare the echoed hash with the "view page source" command in my browser, looking at the hash that was generated before clicking the submit button.
<?php
// Toggle this to see different results
// session_start();
function generateRandomToken() {
return md5(uniqid());
}
if (isset($_POST['token'])) {
echo $_POST['token'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
<input type="hidden" name="token" value="<?php echo generateRandomToken(); ?>">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
When you submit the form, page get refreshed, and new token generated. If you want to use same token even after page refresh save a token value in session if it's previously not set.
function generateRandomToken() {
if(isset($_SESSION['token']) && !empty($_SESSION['token'])
$token = $_SESSION['token'];
else{
$token = md5(uniqid());
$_SESSION['token'] = $token;
}
return $token;
}
Once form processed successfully unset session variable. I hope this will help.
unset($_SESSION['token']);

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;
}
}

How to keep value after post request?

I want to learn how to keep value after a post request.
In my code, I have these variables:
myvar
myans
result
myvar is a random val between 0-5. I will get myans from my input if myans == myvar, then result will be true (else it will be false).
I see myvar before I submit my ans just for trying, but although I see the var when I send it, what I see it is sometimes false and sometimes true. What am I missing?
example.php:
<?php
session_start();
if (!isset($_COOKIE['result'])) {
setcookie("result","EMPTY");
}
setcookie("myvar",rand(0,5));
if (!empty($_POST)) {
if ($_POST['myans'] == $_COOKIE['myvar']) {
setcookie("result","TRUE");
}
else {
setcookie("result","FALSE");
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo $_COOKIE['myvar'] ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo $_COOKIE['result'] ?>
</form>
</body>
</html>
The problem you were having was caused by your random number generator making creating a new number before comparing to the original. I made some changes to only set "myvar" if it's empty. this will only set it once, but at least you can see your code working as intended. I recommend you plan out what exactly what functionality you want before adding to it.
I also switched you out from the "$_COOKIE" var to "$_SESSION" vars. They are hidden from the client, and by php default last about 24 minutes if not refreshed. I don't know what you plan on using this for, but using cookies allows the end user to manipulate that info. If this is not a concern for you, by all means just uncomment the "setcookie()" lines.
<?php
session_start();
if (!isset($_SESSION['result'])) {
//setcookie("result","EMPTY");
$_SESSION["result"] = "EMPTY";
}
//setcookie("myvar",rand(0,5));
if(empty($_SESSION["myvar"])){
$_SESSION["myvar"] = rand(0,5);
}
//
if (!empty($_POST)) {
if ($_POST['myans'] == $_SESSION['myvar']) {
//setcookie("result","TRUE");
$_SESSION["result"] = "TRUE";
} else {
//setcookie("result","FALSE");
$_SESSION["result"] = "FALSE";
}
}
?>
<html>
<head>
<title>Example</title>
</head>
<body>
<form method="post" action="">
<?php echo isset($_SESSION['myvar']) ? $_SESSION['myvar'] : ""; ?>
<input type="text" name="myans">
<input type="submit" value="Send">
<?php echo isset($_SESSION['result']) ? $_SESSION['result'] : ""; ?>
</form>
</body>
</html>

PHP Keep the variable scope even after the page reload

The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}

How do I pass a session variable correctly?

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

Categories