Having a html input as a variable for php - php

This is my first post. So sorry if I get the format wrong :)
Im trying to build a program, that asks for a input using html, sets that input as a php variable, and then calculates that variable. Everything is ready except for the input part, which I find extremely challenging. My code is as follows:
<?php
$x = 1;
$answer = ($x = 1);
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
?>
The variable I'm trying to set is the ($x = 1) part. The codes purpose is to see if a mathematical calculation is true or false. The code has already been tested.
I have already searched the internet for an answer, and sadly I only saw answers for questions that were way different.

There's one small issue with your current code: You're using = to compare a value to another, which will not work, single = is used to assign a variable. You should use == instead.
When you want to use a user's input, you will need something called $_POST, this is a method that you can set in a form using the method="POST" attribute. When the form is submitted it will create an array with the values in the form.
You can then access these values using a certain key, which is equal to the name="" attribute of the input, select or textarea in the form.
Example
Consider this form, with some PHP code:
<form method="post">
<input type="text" name="myName" placeholder="Enter your name!">
<input type="submit" value="Submit">
</form>
<?php
// When the server gets a $_POST request
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set the variable name to whatever the user put in
$name = $_POST['myName']; // equal to the name="" attribute in the form
echo "Hello, " . $name . "!";
}
?>
If I submit the form with my name, it will echo: Hello, rpm192!
For your situation, it would look something like this:
<form method="post">
<input type="number" name="answer" placeholder="Your answer">
<input type="submit" value="Submit answer">
</form>
<?php
// When the server gets a $_POST request
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Set the variable X to whatever the user put in
$x = $_POST['answer'];
$answer = ($x = 1);
// Check if $answer is true or false
if($answer) {
echo "True!";
} else {
echo "False!";
}
}
?>

For that you need to have a form which can submit values to calculation script or same page if script is in same page.
Also in your script you are not comparing anything as the condition is always true as answer is always 1 and condition is always satisfied, so for that you can compare the user input to answer as I did in example.
For example calc.php
<?php
echo"<form method="POST" action="">Your answer:<input type="text" name="val" /><br><input type="submit" /></form>";
#$val=$_POST['val'];
if($val){
$answer = 1;
if($answer==$val) {
echo "The answer is: True";
}
else {
echo "The answer is: False";
}
}
?>

In PHP '=' means assignment operator.
Equal check operator should be '=='.
So, your code should be refactored as:
<?php
$x = 1;
$answer = ($x == 1); // this will return true or false
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
?>
You can also use ternary operator to shorten your code instead of if/else statement like this:
<?php
$x = 1;
$answer = ($x == 1); // this will return true or false
echo $answer ? 'The answer is: true' : 'The answer is: false';
?>

you need to create form to get input from html. there is many different approaches to create form.
I think your are begginer, so simply you can create form on the same page.
you can separate php code from html form write your php code on the top of the page like example below
<?php
if(isset($_POST['submit'])){
$x = $_POST['myinput'];
$answer = $x;
if($answer) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
}
?>
<form method="POST" action="">
<input type="Text" name="myinput" >
<inpu type="submit" name="submit" value="submit button">
</form>
action="" is used for same page. if you want to use separate page for html part you can give action="yourPHPPage.php"

Did u mean this?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
$answer = $_POST['input'];
if($answer == 1) {
echo "The answer is: True";
} else {
echo "The answer is: False";
}
}
?>
<form action="" method="post">
Enter value: <input name="input" type="text" />
<input name="submit" type="submit" />
</form>
</body>
</html>

As the purpose is to check if a mathematic function's value is True or False, I propose a simple CLI script.
<?php
print ((isset($argv[2]) && ($argv[2] === 1)) ? "\nAnswer is True\n\n" : "\nAnswer is false\n\n");
Save this as myfile.php
Open command line navigate to the folder and type in
>php myfile.php 1 // Returns Answer is True
So if you want to change the input you can do that also..
>php myFile.php 4 // Answer is False
Note that if you're passing String "1", this would also return True.

Related

How to fill PHP form with data from URL?

I have a short sample php code above:
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput"><br/>
<br/><input type="submit" name="submit" value="Check"/>
</form>
</body>
<?php
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string))
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
</HTML>
Imagine that the code is saved under file sample.php and located at localhost/sample.php.
I want to fill the form and trigger the submit button through this link:
localhost/sample.php?stringInput=abc&submit=Check
How can I do that? Thanks for help.
I need to use POST method because the actual form has many inputs not just one and I want to know how it will work with POST. And using PHP only if possible. (Javascript, jQuery are not the first choices). Cheers.
This is a good example to demonstrate what I need.
http://image.online-convert.com/convert-to-jpg?external_url=jhjhj&width=333
I tried GET method and the form doesn't display value.
If you want to include the parameters in the URL you cannot use POST
From wikipedia:
the POST request method requests that a web server accept the data enclosed in the body of the request message
Whereas in a GET request (from w3schools):
the query string is sent in the URL of a GET request
Try this:
You can assign your post values to variables & echo them in your input.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>Check for perfect palindrome</title>
</head>
<body>
<?php
$string = "";
if(isset($_POST['stringInput']))
{
$string = $_POST['stringInput'];
if ($string =="")
{
echo "Please fill the form";
} else if ($string == strrev($string) )
{
echo "You entered: <b>'$string'</b> is a perfect palindrome.";
} else
{
echo "You entered: <b>'$string'</b> is NOT a perfect palindrome.";
}
}
?>
<h1>Check for perfect palindrome</h1>
<form method="post">
<label for="stringInput">String:</label><input type="text" id="stringInput" name="stringInput" value="<?php echo $_REQUEST['stringInput'];?>"><br/>
<br/><input type="submit" name="submit" value="Check" />
</form>
</body>
</HTML>
You are using the wrong http method instead of POST you should use GET
"Note that the query string (name/value pairs) is sent in the URL of a
GET request"
Check more about these two methods here: POST vs GET

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>

Show a warning if characters are more then 160 in a string

I want to implement a post update system like twitter where users can update their status in 160 charecters. I want to add some restrictions like If a user entered characters more then 160 ,then the update_post.php file must show him/her a warning and the extra characters(+160) inside HTML del tag. **Bellow is my code that I have tried so far. but it outputs nothing!**Any help is much appriciated! thanks
sample_update.php
<form action="<?php echo $_SERVER['PHP_SELF'];?>"method="post">
<textarea name="msg"></textarea>
<input type="submit"value="Post">
</form>
<?php
if(strlen($txt)>160) {
echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
$txt=$_POST['msg'];
$checking=substr($txt,160);
echo "<del style='color:red;'>$checking</del>";
}
?>
$txt is set inside of your if statement you need to move it outside
$txt=$_POST['msg'];
if(strlen($txt)>160)
{
echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
$checking=substr($txt,160);
echo "<del style='color:red;'>$checking</del>";
}
You should be getting notices about an undefined variable. This being $txt as from what I/we can see, $txt is defined inside your if loop. I have modified your code to be minimal lines but just as effective.
if (isset($_POST['msg'])){
if (strlen($_POST['msg']) > 160){
echo "Your post could not be submitted as it contains more than 160 characters!";
echo "<del style='color:red;'>".substr($_POST['msg'],160)."</del>";
}
}
I have also wrapped your $_POST around an isset statement, which will check if it's set before doing anything else.. If nothing is set, then the code will not execute and trigger some annoying error messages
This should work for you:
($_SERVER['SELF'] doesn't exists only $_SERVER['PHP_SELF'] Also you have to first assign the variable before you can check the length)
<form action="<?= $_SERVER['PHP_SELF'];?>"method="post">
<textarea name="msg"></textarea>
<input type="submit"value="Post">
</form>
<?php
if(!empty($_POST['msg'])) {
$txt = $_POST['msg'];
if(strlen($txt) > 160) {
echo "Your post couldn't be submitted as it contains more then 160 chrecters!";
$checking = substr($txt,160);
echo "<del style='color:red;'>$checking</del>";
}
}
?>
First of all you have to use $_SERVER['PHP_SELF'] instead of $_SERVER['SELF']
You might want to move some of your conditions up, so you can use the check for something else. Furthermore, inserting the user typed text into the textarea is a good practice so the user dosnt have to retype the text again.
<?php
$maxlen = 160;
$txt=(isset($_POST['msg'])) ? $_POST['msg'] : "";
$check = strlen($txt) > $maxlen;
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<textarea name="msg"><?php echo $txt; ?></textarea>
<input type="submit" value="post">
</form>
<?php
if ($check){
echo "Your post couldn't be submitted as it contains more then $maxlen chrecters!";
$checking = substr($txt,$maxlen);
echo "<del style='color:red;'>$checking</del>";
} else {
echo "You are good to go ma man - do something";
}
?>

if(isset($_POST['submit'])) function is not set when working with radio buttons

Okay, first off I apologise if this question has been answered before but because of my lack in php knowledge I do not actually fully know what the problem is.
My $_POST['submit'] does not appear to be set even after the submit button is clicked. I have tried this method before but with text fields, so I'm assuming I am doing something wrong with the configuration of the radio buttons. The way I know its not getting through isset() is because it is not echoing out "in isset" therefore can not reach the rest of my code. Also I have tried replacing $_POST['submit'] with $_POST['onoff'] but both return the same result.
function getRadioState()
{
global $ac;
if (isset($_POST['submit'])) {
echo "in isset";
$selected_radio = $_POST['onoff'];
if ($selected_radio == 'On') {
$ac = 1;
} else if($selected_radio == 'Off') {
$ac = 0;
}
}
}
and here is my html code:
<form>
On: <input type="radio" name="onoff" value="On"><br>
Off: <input type="radio" name="onoff" value="Off"><br>
<input type="submit" name="submit" value="submit">
</form>
Thank you in advance for any responses helping to answer my question :)
That's because form defaults to GET when omitting the method.
Use <form method="post">
Sidenote: Omitting the action defaults to self, should that be the intention.
It's the same as doing action=""
Where you calling this function function getRadioState(){ ???
You have to save the page extension in php
And,
3.form method to POST
<form method="POST" action="test.php">
In test.php
if(isset($_POST['submit'])){
echo "in isset";
$selected_radio = $_POST['onoff'];
if($selected_radio == 'On'){
$ac = 1;
}else if($selected_radio == 'Off'){
$ac = 0;
}
}

How do I check that random value equals entered value to input in php on post

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>

Categories