I am trying to make an online calculater where people can calculate using form in my site, people can POST in form and result is GET by url string. Is it safe ?
html
<form id="form1">
<input type="text" name="user_price" size=2/>
<?php echo form_dropdown('selling', $rates);?>
<input type="submit" value="submit">
</form>
php
<?php
if((int)$_GET['user_price']){
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
}else if((string)$_GET['user_price'] OR (array)$_GET['user_price']){
echo 'enter number not characters';
}else{
echo '';
}
?>
Yes, that's perfectly safe, it just doesn't make sense. (int)$_GET['user_price'] casts a value to an integer, it does not mean "if value is an integer".
You're looking for:
if (isset($_GET['user_price'], $_GET['selling']) &&
is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
...
} else {
echo 'Please enter numbers';
}
You could make it much more concise
if (is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
} else {
echo 'Something went wrong';
}
Here is how I would code that...
$userPrice = isset($_GET['user_price']) ? $_GET['user_price']) : NULL;
$selling = isset($_GET['selling']) ? $_GET['selling'] : NULL;
if (is_numeric($userPrice) AND is_numeric($selling)) {
echo 'Total '. $userPrice * $selling;
} else {
echo 'enter number not characters';
}
Note that a good habit to get into, if echoing user submitted strings back, to wrap them with htmlspecialchars().
Perfectly safe, but when using GET and POST you should always declare a variable before you do anything with the form data
Related
If I leave all the fields blank, the code blow is not showing the else message.
<form action="index.php" method="POST">
<textarea name="input_area" rows="6" cols="20"></textarea><br/><br/>
Search<input type="text" name="find"/><br/><br/>
Replace<input type="text" name="replace" /><br/><br/>
<input type="submit" value="Find and replace"/>
</form>
PHP
if(isset($_POST['input_area'])&&($_POST['find'])&&($_POST['replace']))
{
$text=$_POST['input_area'];
$find=$_POST['find'];
$replace=$_POST['replace'];
if(!empty($text)&&!empty($find)&&!empty($replace))
{
$new_str=str_replace($find,$replace,$text);
echo $new_str;
}
else
{
echo 'FILL ALL THE FIELDS';
}
}
The values will be set in $_POST, but they will be blank. A check like this would work in all situations, even in some cases where someone has modified your html and tried something funny.
<?php
$text = isset($_POST['input_area']) ? $_POST['input_area'] : "";
$find = isset($_POST['find']) ? $_POST['find'] : "";
$replace = isset($_POST['replace']) ? $_POST['find'] : "";
if($text != "" && $find != "" && $replace != ""){
$new_str=str_replace($find,$replace,$text);
echo $new_str;
}else{
echo 'FILL ALL THE FIELDS';
}
?>
This statement is the root of the problem
if(isset($_POST['input_area'])&&($_POST['find'])&&($_POST['replace']))
The correct one is
if(isset($_POST['input_area'])&&isset($_POST['find'])&&isset($_POST['replace']))
Aman has a pretty good answer. You may want to check if a user just entered spaces though. Look up ctype_space($str) for that. You could also adapt strlen for this purpose and trim to knock off whitespaces that may appear at the beginning or end of the input (or all of it)... if you want your code structure to look the same.
if ( strlen(trim($_POST['input_area']))>0 && etc.
My code should provide two random numbers and have the user enter their product (multiplication).
If you enter a wrong answer, it tells you to guess again, but keeps the same random numbers until you answer correctly. Answer correctly, and it starts over with a new pair of numbers.
The below code changes the value of the two random numbers even if I entered the wrong number. I would like to keep the values the same until the correct answer is entered.
<?php
$num1=rand(1, 9);
$num2=rand(1, 9);
$num3=$num1*$num2;
$num_to_guess = $num3;
echo $num1."x".$num2."= <br>";
if ($_POST['guess'] == $num_to_guess)
{ // matches!
$message = "Well done!";
}
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
else
{ // some other condition
$message = "I am terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="answer" value="<?php echo $answer;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<?php echo $expression; ?> <input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
In order to keep the same numbers, you have to store them on the page and then check them when the form is submitted using php. You must also set the random number if the form was never submitted. In your case, you were always changing num1 and num2. I tried to leave as much of your original code intact, but it still needs some work to simplify it.
First I added 2 more hidden field in the html called num1 and num2
Second, I set $num1 and $num2 to the value that was submitted from the form.
After following the rest of the logic, I make sure that $num1 and $num2 are reset if the answer is correct of it the form was never submitted.
You can see the comments in the code below.
Additionally, if you were going to use this in a production environment, you would want to validate the values being passed in from the form so that malicious users don't take advantage of your code. :)
<?php
// Setting $num1 and $num2 to what was posted previously and performing the math on it.
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num_to_guess = $num1*$num2;
// Check for the correct answer
if ($_POST && $_POST['guess'] == $num_to_guess)
{
// matches!
$message = "Well done!";
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
// If the form wasn't submitted i.e. no POST or something else went wrong
else
{
// Only display this message if the form was submitted, but there were no expected values
if ($_POST)
{
// some other condition and only if something was posted
$message = "I am terribly confused.";
}
// set num1 and num2 if there wasn't anything posted
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Show the problem
echo $num1."x".$num2."= <br>";
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="num1" value="<?= $num1 ?>" />
<input type="hidden" name="num2" value="<?= $num2 ?>" />
<input type="hidden" name="answer" value="<?php echo $num3;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
When you load the page for the first time, you have (i.e.) “2*3” as question. $_POST is not defined, so if ($_POST['guess']... will produce a undefined index warning. Then you echo $message, but where you define $message? $_POST['guess'] is undefined, so is evaluated as 0, $num_to_guess is 6 (=2*3), so $message is set to " is too small! Try a larger number.", even if the user has not input anything. The hidden answer is set to $answer, but this variable is not defined so it is set to nothing (or to “Notice: Undefined variable: answer”, if you activate error reporting). Same issue for expression input and for echo $expression.
Try something like this:
$newQuestion = True; // This variable to check if a new multiplication is required
$message = '';
/* $_POST['guess'] check only if form is submitted: */
if( isset( $_POST['guess'] ) )
{
/* Comparison with answer, not with new result: */
if( $_POST['guess'] == $_POST['answer'] )
{
$message = "Well done!";
}
else
{
/* If result if wrong, no new question needed, so we propose same question: */
$newQuestion = False;
$answer = $_POST['answer'];
$expression = $_POST['expression'];
if( $_POST['guess'] > $_POST['answer'] )
{
$message = "{$_POST['guess']} is too big! Try a smaller number.";
}
else
{
$message = "{$_POST['guess']} is too small! Try a larger number.";
}
}
}
/* New question is generated only on first page load or if previous answer is ok: */
if( $newQuestion )
{
$num1 = rand( 1, 9 );
$num2 = rand( 1, 9 );
$answer = $num1*$num2;
$expression = "$num1 x $num2";
if( $message ) $message .= "<br>Try a new one:";
else $message = "Try:";
}
?>
<!DOCTYPE html>
(... Your HTML Here ...)
This might also be fun to learn. This is a session. Lets you store something temporarily. It is a little dirty. But fun to learn from.
http://www.w3schools.com/php/php_sessions.asp
<?php
session_start(); // Starts the Session.
function Save() { // Function to save $num1 and $num2 in a Session.
$_SESSION['num1'] = rand(1, 9);
$_SESSION['num2'] = rand(1, 9);
$_SESSION['num_to_guess'] = $_SESSION['num1']*$_SESSION['num2'];;
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// If there is no session set
if (!isset($_SESSION['num_to_guess'])) {
Save();
$message = "";
}
if (isset($_POST['guess'])) {
// Check for the correct answer
if ($_POST['guess'] == $_SESSION['num_to_guess']) {
$message = "Well done!";
session_destroy(); // Destroys the Session.
Save(); // Set new Sessions.
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too big! Try a smaller number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too small! Try a larger number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// some other condition
else {
$message = "I am terribly confused.";
}
}
?>
<html>
<body>
<h2><?php echo $Som . '<br>'; ?>
<?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
How can i check if this form input was sent to this PHP page and if it's longer than 3 characters? If it's less than 3 characters, I want to print an error.
Form
<form action="index.php" method="post" id="formFlow">
<label for="name" >Name:</label>
<input type="text" name="name" id="name" class="border"/>
</form>
PHP
<?php
$var = $_POST["name"];
if (!empty($var) || strlen($var >= 3)) {
echo "Yes, name is sent";
}else{
echo "Error, name short";
}
?>
First of all you can not use OR operator in your condition becuase it will always true either length of string less than 3 or greater than.
You must need to use && operator.
Second you have an issue in strlen() it must need a string not condition.
Example:
if (!empty($var) && strlen($var) >= 3) {
I think this will solve your problem
<?php
$var = isset($_POST["name"]) ? $_POST["name"] : "";
if (!empty($var) && strlen($var) >= 3) {
echo "Yes, name is sent";
} else {
echo "Error, name short";
}
?>
Ok so I have a form with 1 input and a submit button. Now I am using an if/else statement to make three acceptable answers for that input. Yes, No, or anything else. This if/else is working the thing is the code is kicking out the else function as soon as the page is loaded. I would like there to be nothing there until the user inputs then it would show one of three answers.
Welcome to your Adventure! You awake to the sound of rats scurrying around your dank, dark cell. It takes a minute for your eyes to adjust to your surroundings. In the corner of the room you see what looks like a rusty key.
<br/>
Do you want to pick up the key?<br/>
<?php
//These are the project's variables.
$text2 = 'You take the key and the crumby loaf of bread.<br/>';
$text3 = 'You decide to waste away in misery!<br/>';
$text4 = 'I didnt understand your answer. Please try again.<br/>';
$a = 'yes';
$b = 'no';
// If / Else operators.
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
}
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
?>
<form action="phpgametest.php" method="post">
<input type="text" name="name" /><br>
<input type="submit" name="senddata" /><br>
</form>
You just need to call the code only when the POST value is set. This way it will only execute the code when the form was submitted (aka $_POST['senddata'] is set):
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a){
echo ($text2);
}
elseif ($usertypes == $b){
echo ($text3);
}
else {
echo ($text4);
}
}
Just put the validation in the first if statement like this:
if(isset($_POST['senddata'])) {
$usertypes = $_POST['name'];
if ($usertypes == $a) {
echo ($text2);
} elseif ($usertypes == $b) {
echo ($text3);
} else {
echo ($text4);
}
}
When you load your page the browser is making a GET request, when you submit your form the browser is making a POST request. You can check what request is made using:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your form was submitted
}
Put this around your form processing code in order to keep it from being executed on GET request.
This question already has answers here:
Check for whitespace at beginning of string
(4 answers)
Closed 8 years ago.
Is there any way to check the white space at the begin of a string ? I have tried strpos but look like it doesn't work. I use $_POST['text']=" hi" and it output ok in my code. It suppose to be an error.
<form action="#" method="POST">
text <input type='text' name='text'/><br/>
<input type='submit' value='submit'/>
</form>
<?php
if(isset($_POST['text']) && !empty($_POST['text']))
{
if(strpos($_POST['text'],' '))
{
echo 'found white space';
}
else
{
echo 'not found';
}
}
else
{
echo 'none';
}
strpos() will search through the whole string. At the end and in the middle.
Also, you should always use !== false resp. === false when using with strpos().
You can use this for your problem:
if (ctype_space($_POST['text'][0])) {
}
ctype_space() is better than $_POST['text'][0] == ' ', since it also checks for tabs or null characters etc.
PS: If you simply want to remove whitespaces, use trim() . If you just want to remove at the left, you can use ltrim() .
With strpos you find all spaces in your string (or better, first space in your string, not directly first character). Use substr for testing first character.
if (!empty($_POST['text'])) {
if (substr($_POST['text'], 0, 1) == ' ') {
echo 'First char is space';
} else {
echo 'First char isn\'t space';
}
} else {
echo 'String is empty.';
}
if(ltrim($str) == $str)
{
echo 'No Space';
}
else
{
echo 'There are space';
}
This code will check if there are space at the begin of a string.
I got the answer for you. The answer is quite simple you have to just use false and true statement to check weather it has space or not. I have edited your answer please check it.
<form action="#" method="POST">
text <input type='text' name='text'/><br/>
<input type='submit' value='submit'/>
</form>
<?php
if(isset($_POST['text']) && !empty($_POST['text']))
{
$sx=strpos($_POST['text'],' ');
if($sx==true)
{
echo 'found white space';
}
else
{
echo 'not found';
}
}
else
{
echo 'none';
}
Tell if it works