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>
Related
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'[;
}
I don't know how to deal with the error. i just want to pass the value to another page. i use "GET" method , it is okay. However, it is not working with "POST" method.
The error :
Undefined index: data in C:\Users\x\x\x\x\x on line 18
Testing.html:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<form method="POST" action="testing.php">
<input name="data" type="text">
<input type ="submit" value="send">
</form>
</body>
</html>
testing.php
<?php
$data = $_REQUEST["data"];
if (isset($data)) {
echo $data;
}
else
{
echo "No data ";
}
?>
This example does work - irrelevant of the send method (GET / POST).These cases are handled (and you possibly should too):
Variable "data" NOT TRANSMITTED.
Variable "data" transmitted BUT EMPTY
Variable "data" transmitted and HAS CONTENTS
HTML code
<!DOCTYPE html>
<head>
</head>
<body>
<form method="POST" action="testing.php">
<input name="data" type="text">
<input type ="submit" value="send">
</form>
</body>
</html>
PHP script
<?php
if (isset($_REQUEST["data"])) {
$data = trim($_REQUEST["data"]);
if (strlen($data) > 0) {
echo "Data sent: $data";
} else {
echo "Data sent but EMPTY";
}
} else {
echo "NO DATA sent";
}
?>
Result
Either one of...
NO DATA sent
Data sent: myData
Data sent but EMPTY
IMHO you should check if data is actually being passed or not. change your php as below:
<?php
$data = (isset($_REQUEST["data"]) && $_REQUEST["data"] != "") ? $_REQUEST["data"]: "no data" ;
echo $data;
//this should print value of data (or "no data" if no value passed)
?>
You can't assign it to a local variable before checking if it is present. You need to call isset on the actual thing you care about:
if (isset($_POST["data"])) {
$data = $_POST["data"];
Try this:
<?php
$data=trim($_POST['data']);
if(empty($data){
echo "no data";
} else {
echo $data;
}
?>
I am just started with Php and have some doubts.
I created 2 pages one.php and two.php
ONE.php
<body>
<form method="post" action="TWO.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
</body>
TWO.php
<body>
<?php
$sum=$_POST["txt1"] + $_POST["txt2"];
echo $sum;
?>
</body>
I POST values form one.php to two.php. Two.php calculates the sum and echo's the result.
My query is would I be able to get the sum echoed on one.php using just php and its important to post the data on another page and get the response from there.
Yes you are. Simply, handle the form submission (the POST request) in one.php. When the request for one.php is not POST just show the form.
The typical way is:
// ONE.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$content = "Sum is " . $_POST["txt1"] + $_POST["txt2"];
}
else {
$content = <<<EOC
<form method="post" action="ONE.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
EOC;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ONE</title>
<meta charset="utf-8"> <!-- or whatever charset you are using -->
</head>
<body>
<?php echo $content ?>
</body>
</html>
Edited, the OP needs the two files but print the result on one.php
In order to pass data between two files you can:
Set the data in the first file (two.php) and require the second (one.php, where you would print the value)
Use PHP sessions.
With the latter you need to do a (well you don't need to but it's mean to work with a) page redirect, so my recommended approach for this case is use the former. The code could be something like:
// TWO.php
<?php
// you should probably check if $_POST['txt1'] and $_POST['txt2'] does really exists and throw and error if not...
$sum = $_POST["txt1"] + $_POST["txt2"];
require "ONE.php" // careful if you're on a *nix file system the NameCase is extremely important!
// ONE.php
<?php
if (isset($sum)) {
$content = "Sum is " . $sum;
}
else {
$content = <<<EOC
<form method="post" action="TWO.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
EOC;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>ONE</title>
<meta charset="utf-8"> <!-- or whatever charset you are using -->
</head>
<body>
<?php echo $content ?>
</body>
</html>
Try this code:
<body>
<?php
if($_POST){
$sum = $_POST["txt1"] + $_POST["txt2"];
echo $sum;
}else{
?>
<form method="post" action="">
First Number<input type="text" name="txt1"><br />
Second Number<input type="text" name="txt2"><br />
<input type="submit">
</form>
<?php } ?>
</body>
You can try with this, in only one page:
ONE.php
<html>
<head></head>
<body>
<form method="post" action="ONE.php">
First Number<input type="text" name="txt1"><br>
Second Number<input type="text" name="txt2"><br>
<input type="submit">
</form>
<?php
// Verify if $_POST["txt1"] and $_POST["txt1"] are defined
// (when form is submit $_POST, $_GET and other $_ PHP vars
// are set). If form isn't submitted, set 0 on each variable
// to perform sum. Is necessary check values to avoid PHP
// Warnings/Errors (In this case with isset function. There
// are many different ways to perform it)
$txt1 = isset($_POST["txt1"]) ? $_POST["txt1"] : 0;
$txt2 = isset($_POST["txt2"]) ? $_POST["txt2"] : 0;
$sum = $txt1 + $txt2;
//Print sum result
echo 'Sum is: '.$sum;
?>
</body>
</html>
For comparations I'm using ternary operators, that simplify/minimize code of traditional if/else. Also you can use traditional if/else (simple compare) or switch(multiple compare)
I'am new to php and I have no idea why my code in php is always echoing FALSE.
I do not want to use another hidden input like:
<input type="hidden" name="storeRandVal" value="<?php echo $randomValue; ?>
to store my generated random value, and then checking if the entered value in input is equal with value that was generated and entered to hidden input. Is there any way around to do it in php also without involving cookies?
Here is my code:
<?php
$buttonPost = $_POST['button_post'];
$enteredValue = htmlspecialchars(trim($_POST['test_input_p']));
$randomValue = rand(1,100);
if(isset($buttonPost))
{
if($randomValue == $enteredValue)
{
echo "TRUE";
}
elseif($randomValue != $enteredValue)
{
echo "FALSE";
}
else
{
echo "Er__!";
}
}
?>
<html>
<head>
<meta></meta>
</head>
<body>
<form action="" method="post">
<fieldset>
<label for="test_input" id="label_input">Enter value: <?php echo $randomValue; ?></label>
<input id="test_input" name="test_input_p">
<input type="submit" id="ibutton_send" name="button_post" value="Send">
</fieldset>
</form>
</body>
</html>
Why not store the random value in a session? Re-set the session only when a form is not submitted (eg; when a user comes to this page from a different page)
As #Fred commented, you have to include the hidden input. By its nature, PHP's rand() function gives you a different answer every time you load the page.
You'll need to compare the $_POST['test_input_p'] and $_POST['storeRandVal'] values in order to confirm that the user entered the correct values.
Here's what you can do:
Store the hidden value in a variable then compare it with that value.
(Unless you will be using this for more than 2 pages, sessions are not needed, not for this since you're using your entire code inside the same page.)
<?php
$buttonPost = $_POST['button_post'];
$enteredValue = htmlspecialchars(trim($_POST['test_input_p']));
$hidden = $_POST['storeRandVal'];
$randomValue = rand(1,100);
if(isset($buttonPost))
{
if($enteredValue == $hidden)
{
echo "TRUE";
}
elseif($randomValue != $hidden)
{
echo "FALSE";
}
else
{
echo "Er__!";
}
}
?>
<html>
<head>
<meta></meta>
</head>
<body>
<form action="" method="post">
<input type="hidden" name="storeRandVal" value="<?php echo $randomValue; ?>">
<fieldset>
<label for="test_input" id="label_input">Enter value: <?php echo $randomValue; ?></label>
<input id="test_input" name="test_input_p">
<input type="submit" id="ibutton_send" name="button_post" value="Send"></input>
</fieldset>
</form>
</body>
</html>
I have done a conditional redirect with javascript (depending of referer). However now I need to detect if user got redirected and then he clicked back button and got again to the page he has been redirected from. In this case I need no to redirect him again.
I have found a solution here - but I am failed to combine php and javascript properly, so there is always an error - How do I detect if a user has got to a page using the back button?
Code:
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
<script language="javascript" type="text/javascript">
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') {
document.write("<p>Do Not Redirect</p>");
}
else {
<?php if((stristr($_SERVER['HTTP_REFERER'],"thoughts") != FALSE) { ?>
<?php $setupform = '<form id="form1" method="post" action="http://yahoo.com">'; ?>
<?php $submitform = 'document.getElementById(\'form1\').submit(); </form>'; ?>
<?php echo $setupform; ?>
<?php echo $submitform; ?>
<?php } ?>
}
function mark_page_dirty() {
dirty_bit.value = '1';
}
</script>
What is wrong here?
The error is that it simply doesn't redirect - it gives a blank page with code on it:
<form name="ignore_me">
<input type="hidden" id="page_is_dirty" name="page_is_dirty" value="0" />
</form>
<script language="javascript" type="text/javascript">
var dirty_bit = document.getElementById('page_is_dirty');
if (dirty_bit.value == '1') {
document.write("<p>My First JavaScript</p>");
}
else {
<form id="form1" method="post" action="http://yahoo.com">document.getElementById('form1').submit(); </form>
}
function mark_page_dirty() {
dirty_bit.value = '1';
}
I took a look at your code and here are some points:
When mixing PHP and JS, remember, that PHP code will be executed first, it will not read any of JS statements
You put a block of PHP code into if statement of JS.
Here is a possible solution for you:
PHP logic first:
$redir = false ;
if((stristr($_SERVER['HTTP_REFERER'],"thoughts"))) {
$redir = true ;
}
HTML form:
<form id="check" action="a.php" method="post">
<input type="hidden" name="durty_bit" value="1" />
</form>
JS check:
var check = getElementById("check") ;
if (check && check.durty_bit == 1){
document.write("<p>Do Not Redirect</p>");
} else {
<?php if ($redir){ ?>
document.write('<form id="form1" method="post" action="http://yahoo.com"> </form>');
document.getElementById("form1").submit() ;
<?php } ?>
}