else not executing in php - php

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.

Related

PHP -- How to replace string value to user input?

Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>

PHP After submit check if Data input was sent, and if its less than 3 characters give error

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

PHP If / Else statement going directly to the Else without waiting for form input

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.

Is this a safe practice in php?

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

Why is that !isset does not seem to work?

I am new to the world of PHP and have put together a form that multiplies an entered value. However when I attempt to validate if a person has not entered any values to return an error message, it does display the message. My code below. Appreciate if you could also suggest improvements.
<?php
$counter = 0;
if(isset($_POST["submit"])) {
$start = $_POST["start"];
$end = $_POST["end"];
$multiply = $_POST["multiplication"];
// if($_POST["start"] == "" && $_POST["end"] == "" && $_POST["multiplication"] == "") {
// print "Please enter some values";
// }
if(!isset($_POST["start"], $_POST["end"], $_POST["multiplication"])) {
print "Please enter some values";
}
// for($start;$start<$end;$start++) {
// $counter = $counter +1;
// $multiplication = $counter * $multiply;
// print "$counter <br />";
// print "$counter multiplied by $multiply = $multiplication <br />";
// }
}
?>
<html>
<head>
<title>Sample Multiplication</title>
</head>
<body>
<form name="multiply" method="post" action="multiplication_sample.php">
<input type="text" name="start" value="<?php if(isset($_POST["start"])) { print $start; } ?>">
<input type="text" name="end" value="<?php if(isset($_POST["end"])) { print $end; } ?>">
<input type="text" name="multiplication" value="<?php if(isset($_POST["multiplication"])) { print $multiply; } ?>">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
for($start;$start<$end;$start++) {
$counter = $counter + 1;
$multiplication = $counter * $multiply;
print "$counter multiplied by $multiply = $multiplication <br />";
}
}
?>
</body>
</html>
I think that isset will make sure a variable is not NULL, however, "blank" is not the same as null. If you submit a form with blank values, the variable is still being set, it is just empty.
When the form is submitted, the content of the input fields is sent to the server.
If those input fields are empty, the server gets an empty string for each input -- but it gets something ; so, the $_POST["start"], $_POST["end"], $_POST["multiplication"] items are set -- even if they only contain empty strings.
You could check :
If the fields contain an empty string : if ($_POST["start"] === '')
Or if if contains only blank spaces : if (trim($_POST["start"]) === '')
Or if they are empty : if (empty($_POST["start"]))
If the fields aren't defined your code will print your message in the html before the <html> tag appears. Most browsers won't display it or display it in an unexpected place.
You should move the message display somewhere in the html where the user could see it.
And as other pointed out, except on the first call of the page the fields will have an empty value but still exists (and so isset will return TRUE)
I hope, I understand you right. It is
if(!isset($_POST["start"], $_POST["end"], $_POST["multiplication"])) {
print "Please enter some values";
}
that works not as expected? It seems, that you assume an empty string means, that nothing is set, what is not true.
$x = "";
isset($x); // true
Use empty() or just $_POST['start'] == '' instead.

Categories