PHP validation help. First and last name, validated as required fields - php

This link leads to where my code is ran.
http://erobi022.pairserver.com/phpvalidate1.php
<!DOC TYPE html>
<html>
<body>
This is a simple form
<form method="post" action="send_phpvalidate1.php">
Please enter your first name: <input type="text" name="First"></p>
Please enter your last name: <input type="text" name="Last"></p>
<button type="submit">Submit</button>
</form>
</body>
</html>
Once the submit button is hit, all data is sent and posted here. I can get first and last name to output fine, but if i leave them blank it will only say that i left my first name field blank.
http://erobi022.pairserver.com/send_phpvalidate1.php
<!DOCTYPE html>
<html>
<body>
Welcome,
</P>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name1 = $_POST["First"];
if (empty($name1)) {
echo "You've entered nothing for first name";
echo "<br>";
echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
die; //if you mess up, youll have to fix it
} else {
echo " Your first name is $name1 ";
}
}
echo "<br>";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name2 = $_POST["Last"];
if (empty($name2)) {
echo "You've entered nothing for last name";
echo "<br>";
echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
die; //if you mess up, youll have to fix it
} else {
echo " Your last name is $name2 ";
}
}
?>
<?php // can have multiple php sections
echo "<a href='phpvalidate1.php'>Return to form</a></p>";
//have to use a simple qoute within html to make it work
?> </p>
Return to home page
</body>
</html>

You can just use that using HTML 5, simple
<!DOC TYPE html>
<html>
<body>
This is a simple form
<form method="post" action="send_phpvalidate1.php">
Please enter your first name: <input required="required" type="text" name="First"></p>
Please enter your last name: <input required="required" type="text" name="Last"></p>
<button type="submit">Submit</button>
</form>
</body>
</html>

No need to use two big ifs, just replace your PHP code with this :
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name1 = $_POST["First"];
$name2 = $_POST["Last"];
if (empty($name1) || empty($name2)) {
echo "Please complete both the fields.";
echo "<br>";
echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
die; //if you mess up, youll have to fix it
} else {
echo " Your name is $name1 $name2";
}
}
?>

First, whenever there is a die() statement,only the codes that appear before that run, the ones which come after don't get to run(in relation to your code.)
you can also trim your codes down this way and it will still work
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name1 = $_POST["First"];
$name2 = $_POST["Last"];
if (empty($name1) || empty($name2)) {
echo "Please complete both the fields.";
echo "<br>";
echo "<a href='phpvalidate1.php?text=hello>Click here to fix</a>";
die; //if you mess up, youll have to fix it
} else {
echo " Your name is $name1 $name2";
}
}
?>

Related

How to ask for user input on PHP

I am trying to get the user input and verify if the answer is correct using an if and statement. How do I prompt the user for input within the same webpage? This is the code I have so far.
<?php
$answer = //user input
if ($answer = "4") {
echo " “Correct!!!! Congratulations!";
} else {
echo "Your answer was blank but the correct answer is 4.";
}
?>
This is the full form view to let you know how to perform the basic form submit and get values and displaying the result
<?php
if(isset($_POST['submit']))
{
$answer=$_POST['answer'];
if ($answer == "4") {
echo " “Correct!!!! Congratulations!";
} else {
echo "Your answer was blank or wrong input but the correct answer is 4.";
}
}
?>
<html>
<body>
<form method="post" action="index.php">
<input type="number" name="answer">
<input type="submit" name="submit" value="Submit">
</form>

PHP form reloads on submit, but resets variables

I've been tasked to create a guessing game. A random number is generated and the user tries to guess it. It tells you if you should try a larger or a smaller number, and eventually the user guesses the correct number.
<?php
session_start();
if(empty($_SESSION['num_to_guess'])) { $_SESSION['num_to_guess'] = mt_rand(1,99); }
if (!isset($_POST['guess'])) {
$message = "Welcome to the Odd Number Guessing Game!";
}
elseif (!is_numeric($_POST['guess'])) { //is not numeric
$message = "I don't understand that response. Please enter a number.";
}
elseif ($_POST['guess'] == $_SESSION['num_to_guess']) { //matches
$message = "Well done! You've found the secret number. Now try to guess another.";
$_SESSION['num_to_guess'] = mt_rand(1,99);
}
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) { //greater
$message = "Try a larger number!";
}
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) { //lesser
$message = "Try a smaller number!";
}
else {
$message = "I'm terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Odd Number Guessing Machine!</title>
</head>
<body>
<h1><?php echo $message; ?>
<?php echo $_SESSION['num_to_guess']; ?>
</h1>
<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">
<p><label for="guess">Try to guess an odd number between 1 and 99:</label> <br/>
<input type="text" id="guess" name="guess" /></p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
My problem is the form reloads every time the user submits the data, thereby changing the random number. I'm sure there is a workaround but I just can't seem to find it.
I want to generate a new number ONLY when the correct number is guessed. I tried adding rand() function on the elseif loop where the number is guessed correctly, but that doesn't work.
Please help. :)
Now browser compatible
<?php
session_start();
$url_of_page = $_SERVER['REQUEST_URI'];
if(!isset($_SESSION['correct_number'])){
// Create random number only when the previous one has been correctly guessed
$number_to_guess = rand(0,9);
$_SESSION['correct_number'] = $number_to_guess;
}
if(isset($_SESSION['correct_number'])){
$num_to_guess = $_SESSION['correct_number'];
}
if(isset($_POST['guess'])){
$guessed_number = trim($_POST['guess']);
$reg_exp = '/^([0-9]+)$/';
$reg_exp_match = preg_match($reg_exp,$guessed_number);
}
if(isset($_POST['submit'])){
if(isset($reg_exp_match)){
if(!$reg_exp_match){
$message = "Enter a number";
}else{
if($guessed_number < $num_to_guess){
// is small
$message = "Try a larger number!";
}elseif($guessed_number > $num_to_guess){
// is large
$message = "Try a smaller number!";
}elseif($guessed_number == $num_to_guess){
//matches
$message = "Well done...You got it";
$new_game = TRUE;
unset($_SESSION['correct_number']);
// A new number can now be created
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Odd Number Guessing Machine!</title>
</head>
<body>
<h3>Welcome to the Guessing Machine!</h3>
<p>
<?php
if(isset($new_game) && ($new_game == TRUE)){ // The correct number
if(isset($message) && isset($url_of_page)){
echo $message . '. Start a new game';
}
}else{ // Not the correct number
if(isset($message)){ echo $message; }
}
?>
</p>
<form action="<?php if(isset($url_of_page)){ echo $url_of_page; } ?>" method="POST">
<p>
<label for="guess">Enter a number, 0 to 9:</label> <br/>
<input type="text" id="guess" name="guess" />
</p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>

Display form validation error message on same page using only PHP?

I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?
<?php
$name = "Fred";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST["name"])) {
if ($_POST["name"] == $name) {
include("welcomeFred.php");
}
else {
$errMsg = "Incorrect name";
}
}
else {
$errMsg = "Name required";
}
}
else { ?>
<html>
...
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" required>
<span><?php echo $errMsg;?></span>
<input type="submit" value="Submit">
</form>
...
</html>
<?php } ?>
You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.
Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.

set value of input field by php variable's value

I have a simple php calculator which code is:
<html>
<head>
<title>PHP calculator</title>
</head>
<body bgcolor="orange">
<h1 align="center">This is PHP Calculator</h1>
<center>
<form method="post" action="phptest.php">
Type Value 1:<br><input type="text" name="value1"><br>
Type value 2:<br><input type="text" name="value2"><br>
Operator:<br><input type="text" name="sign"><br>
Result:<br><input type"text" name="result">
<div align="center">
<input type="submit" name="submit" value="Submit">
</div>
</form>
</center>
<?php
if(isset($_POST['submit'])){
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
if($value1=='') {
echo "<script>alert('Please Enter Value 1')</script>";
exit();
}
if($value2=='') {
echo "<script>alert('Please Enter Value 2')</script>";
exit();
}
if($sign=='+') {
echo "Your answer is: " , $value1+$value2;
exit();
}
if($sign=='-') {
echo "Your answer is: " , $value1-$value2;
exit();
}
if($sign=='*') {
echo "Your answer is: " , $value1*$value2;
exit();
}
if($sign=='/') {
echo "Your answer is: " , $value1/$value2;
exit();
}
}
?>
All I want to do is that answer should be displayed in the result input field instead of echoing them separately. Please help? I Know it's simple but I am new in PHP.
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input> tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
inside the Form, You can use this code. Replace your variable name (i use $variable)
<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">
Try this
<input class="qtytext-box" type="number" value= <?php echo $colll2; ?> >

Using Sessions To Remember User on PHP Form

Intro: I'm trying to learn PHP on $_SESSION. What I was trying to do is call the value assigned through sessions that when you close your tab will keep the value assigned and echoes it on the browser when you open a tab in the browser.
Issue: There's something wrong with my code where for some reason I couldn't echo the value entered in on a form.
The form looks like this:
Name:_____________
Email:_____________ Remember me? __ SUBMIT
I made it so that $_SESSION['name'] = "John" and $_SESSION['email'] = "someemail#email.com" only when user click on "remember me".
If you close a "tab" on the browser but not the browser itself should echo...
John
someemail#email.com
Here's your download link (some link here)...
But of course if you close the browser, session is lost. Cookies can be used but I'm working on sessions to learn more.
Below's code runs but for some reason I couldn't echo values from $_SESSION variables.
<?php
//Start session
session_start();
// session
if (isset($_POST['remember'])) {
$customer_name = $_SESSION['name'];
if (!($customer_name)) {
$customer_name = $_POST['name'];
}
$customer_email = $_SESSION['email'];
if (!($customer_email)) {
$customer_email = $_POST['email'];
}
}
//If form submit validate
if (isset($_POST['Submit'])) {
// Santize fields here but FILTER_VALIDATE_STRING isn't necessary as there is no absolute way
//to validate names absolutely
// Also shows error message if there's error
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid first name.<br/><br/>';
}
} else {
$errors .= 'Please enter your first name.<br/>';
}
// Sanitize and validate email
// Error message shows if any
if ($_POST['email'] != "") {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors .= "$email is NOT a valid email address.<br/><br/>";
}
} else {
$errors .= 'Please enter your email address.<br/>';
}
// If no errors, submitted form is emailed
if (!$errors) {
echo "I did something!<br /><br />"; // might add some message
//downloadLink();
echo "<br /><br />";
}
} else {
echo '<div id="error">' . $errors . '<br /></div>';
}
?>
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Name:
<?php
if (isset($_SESSION['name'])) {
echo $_SESSION['name']."<br />";
}
else {
?>
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="25" /><br />
<?php } ?>
Email:
<?php
if (isset($_SESSION['email'])) {
echo $_SESSION['email']."<br /><br />";
// echo link.. downloadLink();
}
else {
?>
<input type="text" name="email" value="<?php echo $_POST['email']; ?>" size="25"/>
<input type="checkbox" name="remember" /> Remember me
<input type="submit" name="Submit" />
<?php } ?>
</form>
</div>
Put this at the beginning under session_start();
if (!isset($_SESSION['name'])) {
echo "Your session is not good";
} else { echo "Session is set";
}
then replace $customer_name = $_SESSION['name']; with $_SESSION['name']=$_POST['remember']; and you will start getting results.

Categories