This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 19 days ago.
I'm trying to make a concept sign up page in PHP, and I need to require the user to enter in text for ALL inputs. If not, it would say for example, "You need a valid email address!" or something like that.
My problem is getting the text to actually show. When I submit, it doesn't show the error, it rather just stays with a star.
My code:
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Test</title>
</head>
<body>
<?php
$emailErr = $usernameErr = $passwordErr = "";
$email = $username = $password = "";
if ($_SERVER["REQUIRED_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "You must enter a valid email address!";
} else {
$email = testData($_POST["email"]);
}
if (empty($_POST["username"])) {
$usernameErr = "You must create a username!";
} else {
$username = testData($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "You must create a password!";
} else {
$password = testData($_POST["password"]);
}
}
function testData($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* Required Field(s)</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="email">Email Address:</label>
<span class="error">* <?php echo $emailErr;?></span>
<br>
<input type="email" name="email" placeholder="someone#organization.com" />
<br><br>
<label for="username">Username:</label>
<span class="error">* <?php echo $usernameErr;?></span>
<br>
<input type="text" name="username" />
<br><br>
<label for="password">Password:</label>
<span class="error">* <?php echo $passwordErr;?></span>
<br>
<input type="password" name="password" />
<br><br>
<input type="submit" value="Create Account!">
</form>
</body>
</html>
Can anyone please help me find out a solution to my situation?
It is not $_SERVER["REQUIRED_METHOD"] it should be $_SERVER["REQUEST_METHOD"]
So your if conditional block will be
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "You must enter a valid email address!";
} else {
$email = testData($_POST["email"]);
}
if (empty($_POST["username"])) {
$usernameErr = "You must create a username!";
} else {
$username = testData($_POST["username"]);
}
if (empty($_POST["password"])) {
$passwordErr = "You must create a password!";
} else {
$password = testData($_POST["password"]);
}
}
Also, another quick and easy way of debugging is using var_dump() and see if the code block is being executed and has desired data in the variables is set.
You could have done var_dump($_SERVER); too to quick check what data this super global variable has or inside the if block so you will be sure that truth condition did passed or not.
Change index of $_SERVER["REQUIRED_METHOD"] to REQUEST_METHOD.
For more details go to https://www.php.net/manual/en/reserved.variables.server.php
$_SERVER["REQUIRED_METHOD"] == "POST" will raise an error.
$_SERVER["REQUEST_METHOD"] == "POST" will be right answer for your question.
if ($_SERVER['REQUEST_METHOD'] === 'POST')
Related
This is my first php script ever and I have googled a lot to try to get the script to work.
I am working on this tutorial: https://learn.microsoft.com/en-us/gaming/playfab/features/engagement/emails/using-email-templates-to-send-an-account-recovery-email
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$emailErr = $pw1Err = $pw2Err = "";
$email = $pw1 = $pw2 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["pw1"]))
{
$pw1Err = "Password is required";
}
if (empty($_POST["pw2"])) {
$pw2Err = "Confirm Password is required";
}
//$str1 = "Hello";
//$str2 = "Hello World";
//echo strcasecmp($pw11, $pw2); // Outputs: -6
//$check = strcasecmp($pw11, $pw2)
$check = strcasecmp($pw1, $pw2); // Outputs: -6
/*
if ($check == 0)
{
<br><br>
echo Passwords are the same!;
<br><br>
}
else
{
<br><br>
echo Passwords are NOT the same!;
<br><br>
}
*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Password Recovery</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
New Password: <input type="test_input" name=pw1 valur="<?php echo $pw1;?>">
<span class="error">* <?php echo $pw1Err;?></span>
<br><br>
Confirm Password: <input type="test_input" name=pw2 valur="<? php echo $pw2;?>">
<span class="error">* <?php echo $pw2Err;?></span>
<br><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<br>";
echo "<h3>Your Input:</h3>";
echo $email;
echo "<br>";
echo $check;
?>
</body>
</html>
What I am trying to accomplish is the callback URL. I first tried to create it in WordPress, which was also a first, and now try with php code.
Here is what I try to accomplish:
A form with the following fields:
email
New pasword (currently a text_input during test but will be real pw)
Confirm password (currently a text_input during test but will be real pw)
Submit button
Currently I am focus on trying to echo the result but I just can't get this to work.
The ultimate target is to send back a confirmation with this API including the new checked password and the token.
https://learn.microsoft.com/en-us/rest/api/playfab/admin/account-management/reset-password?view=playfab-rest
I have been trying for quite a long time now so I reach out for help.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #eb0800;}
</style>
</head>
<body>
<?php
$firstname = ["firstname"];
$surname = ["surname"];
$username= ["username"];
$password = ["password"];
$firstnameerror = $surnameerror = $usernameerror = $passworderror = "";
$firstnameerror = "Please enter your First Name";
$surnameerror = "Please enter your Surname";
$usernameerror= "Please enter your Username";
$passworderror= "Please enter your Password";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$firstnameerror = "First name is required";
} else {
$firstname = ($_POST["firstname"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$firstname)) {
}else{
$firstnameerror = "You have entered the First Name correctly";
}
}
}
if(empty($_POST["surname"])){
$surnameerror = " Surname must be entered";
} else{
$surname = ($_POST["surname"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$surname)) {
}else{
$surnameerror = "You have entered the Surname correctly" ;
}
}
if(empty($_POST["username"])){
$usernameerror = "Username must be entered";
}else{
$username = ($_POST["username"]);
if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {
$usernameerror = "Invalid Username try Again";
}else{
$usernameerror = "You have entered the email correctly";
}
}
if(empty($_POST["password"])){
$passworderror = "Password must be entered";
}else{
$password = ($_POST["password"]);
}
function ($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="firstname">
<span class="error">* <?php echo $firstnameerror;?></span>
<br> <br>
Surname: <input type="text" name="surname">
<span class="error">* <?php echo $surnameerror;?></span>
<br><br>
Username: <input type="text" name="username">
<span class="error">* <?php echo $usernameerror;?></span>
<br><br>
Password:
<input type="password" minlength="5" required>
<span class="error">* <?php echo $passworderror;?></span>
<br> <br>
<input type="submit" name="register" value="submit">
</form>
</body>
</html>
when I run this code it works fine however I would like the input fields to say please enter your first name for the rest below and not the first name is required as I want that to happen after there are no fields in and they click submit I'm very new to this so sorry.Also I do not see the error and am having lots of trouble with this can someone explain to me why.
Add placeholder="Please enter your first name" to have grayed out text that disappears when the user types in something.
Also, you can add required="required" to the input to prevent the user from submitting the form if a field is empty (if I understood the question right it's what you also wanted?)
Your input for first name will then look like this:
<input type="text" name="firstname" required="required" placeholder="Please enter your first name">
I am doing this to learn, got it from examples here and there and, following an online tutorial. What I have not been able to do so far is to prevent it to go to the confirmation.php page if one of the entry is either empty, has numbers (name and lastname) or the email adress is invalid.
If i use action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" I see when thre is an error in the fields but, when action is set to confirmation.php, even if there is an error, it will go with the entered data.
Just for info of my next step, confirmation.php would be a page displaying the info entered with a submit button (to a DB) or an update button if the user made a mistake so he can fix it before sending to db.
Just so you know, I am just starting paying with php so, please, I would appreciate if your answer was not to generic :-)
Thank you
<?php
// define variables and set to empty values
$nameErr = $lastNameErr = $emailErr = "";
$name = $lastName = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])||(ctype_space($_POST["name"]))) {
$nameErr = "Prénom Requis";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Lettre seulement";
}
}
if (empty($_POST["lastName"])||(ctype_space($_POST["lastName"]))) {
$lastNameErr = "Nom Requis";
} else {
$lastName = test_input($_POST["lastName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
$lastNameErr = "Lettre seulement";
}
}
if (empty($_POST["email"])||(ctype_space($_POST["email"]))) {
$emailErr = "Adresse courriel requise";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Adresse courriel non valide";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Inscription du participant</h2>
<p><span class="error">* Champ requis.</span></p>
<form method="post" "confirmation.php">
Prénom: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Nom: <input type="text" name="lastName" value="<?php echo $lastName;?>">
<span class="error">* <?php echo $lastNameErr;?></span>
<br><br>
Courriel: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can easily achieve what you want just by adding the "required" attribute to your input field html element.
Have a look here: https://www.w3schools.com/tags/att_input_required.asp
By adding "required" the browser itself will prevent the form to be sent.
Furthermore, for the "email" input, try to change its type to email (type="email" which will also add the default browser validation for an email address.
Have a look here for more default validation in form input fields: https://www.w3schools.com/htmL/html_form_input_types.asp
You are missing action= inside your <form>. It just says confirmation.php
I made a website using css, html, javascript and a little php. I have it hosted on a hosting site with a domain name, but I'm having issue with the server side validation for the form.
It's just a simple contact form:
First Name
Last Name
Email
Message (textarea)
Submit button
I have javascript validation and it works fine. The form won't submit at all unless the correct amount of characters are input, but obviously that's useless if the user has js disabled. I've also finally gotten the form to email to my personal email using php... But obviously I need server side validation as well.
Today was my first day really getting into php and I was hoping to have the php validation done by today, but of all the videos I watched, I just came away more confused. All I want to do is just make it so that if the user has javascript disabled for whatever reason, or if he leaves the fields blank, the form won't submit...
Anyeay, I was working on this all day today with the intention of getting the form to send to my email, I finally accomplished that. Then realized I had no server side validation. I spent a few hours researching it and attempting it to no avail. Can anyone here just give me the php validation code for the kind of form I described above? It's for my business website so the sooner I can have a working contact form on it, the better...
Here is the html contact form I made.
<form action="message_sent.php" method="POST" onSubmit="return validateTextbox();">
<p class="message">
<div class="row">
<label for="firstname"><!--First Name (Required):--> </label>
<input type="text" id="firstname" name="first_name" size="40" placeholder="First Name (Required)"></br> </br> </div>
<div class="row">
<label for="lastname"><!--Last Name (Required):--> </label>
<input type="text" id="lastname" name="last_name" size="40" placeholder="Last Name (Required)"/> </br> </br></div>
<div class="row">
<label for="email"><!--Your Email (Required):--></label>
<input type="email" id="email" name="email" size="40" placeholder="Email (Required)"/> </br> </br></div>
<!--<p class="yourMessage">Your Message (10 Character Minimum):</p>-->
<textarea id="theform" rows="30" cols="80" name="message" placeholder="Your Message (10 Character Minimum):"></textarea></br>
</p>
<input type="submit" name="submit" onclick="return val();" value="SUBMIT">
</form>
</body>
</html>
Here is the javascript validation:
/*============================ CONTACT US PAGE ==========================*/
function validateTextbox() {
var box = document.getElementById("firstname");
var box2 = document.getElementById("lastname");
var box3 = document.getElementById("email");
var box4 = document.getElementById("theForm");
if (box.value.length < 1 || box2.value.length < 1 || box3.value.length < 5){
alert("You must enter a value");
box.focus();
box.style.border = "solid 3px red";
box2.focus();
box2.style.border = "solid 3px red";
box3.focus();
box3.style.border = "solid 3px red";
return false;
}
}
function val(){
if(document.getElementById("theform").value.length < 10
&& document.getElementById("theform").value.length > 0){
alert("You must enter at least 50 characters. Tell us what you need so we can better assist you.");
return false;
}
else if(document.getElementById("theform").value.length === 0){
alert("You cannot submit an empty form.");
theform.focus();
theform.style.border = "solid 3px red";
return false;
}
}
/*function val(){
if(document.getElementById("theform").value==null || document.getElementById("theform").value==""){
alert("The Message field cannot be blank.");
return false;
}
*/
/*
*/
/*=======================|| box4.value.length < 70) ================================================ */
/*========= CONTACT PAGE========================================*/
/*
function contactPage(){
alert("This Contact Form is NOT OPERATIONAL.");
Here is the php submission success page... the code I used to have the form send to my email:
<?php
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];
$to="default#email.com";
$subject="A visitor has sent you a new message";
$body="You have received a message from: \n\n
First Name: $first_name\n
Last Name: $last_name\n
Email: $email\n\n
MESSAGE: $message";
mail($to, $subject, $body);
print "<p>Message Sent! <a href='index.html'>Click. here</a> to return to the homepage</p>"
?>
Simple and complete example:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//Define variable as empty to avoid "undefined variable error".
$FnameErr = $LnameErr = $emailErr = ""; //Each variable contain error string of specific field.
$fname = $lname = $email = $message = ""; //Main inputed data of specific field
if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if request is posted.
//First name check
if (empty($_POST["fname"])) { // check if empty then assign a error string in spacific variable
$FnameErr = "First Name is required";
}else{ // if not empty then store as right data
$fname = filter_data($_POST["fname"]); //filter with unexpected special char and trim.
}
//Last name
if (empty($_POST["lname"])) { // check if empty then assign a error string in spacific variable
$LnameErr = "Last Name is required";
}else{ // if not empty then store as right data
$lname = filter_data($_POST["lname"]); //filter with unexpected special char and trim.
}
//email
if (empty($_POST["email"])) { // check if empty then assign a error string in spacific variable
$emailErr = "Email is required";
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // validate email with php build-in fucntion.
$emailErr = "Invalid email format";
}else{ // if not empty and valide email then store as right data
$email = filter_data($_POST["email"]); //filter with unexpected special char and trim.
}
}
//message with no validation
if (empty($_POST["message"])) {
$message = "";
} else {
$message = filter_data($_POST["message"]);
}
//Database query
if($FnameErr =="" && $LnameErr =="" && $emailErr==""){
//MYSQL insert statement that you know
// $sql = "INSERT INTO tablename .................."; values = $fname; $lname; $email; $message;
}
}
// A function to trim data and remove special charecter
function filter_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fname" value="">
<span class="error">* <?php echo $FnameErr;?></span><br><br>
Last Name: <input type="text" name="lname" value="">
<span class="error">* <?php echo $LnameErr;?></span><br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Message: <textarea name="message" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $email;
echo "<br>";
echo $message;
?>
</body>
</html>
This is just a basic empty check validation.
Validations in PHP are not very difficult.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(trim($_POST['firstname']) === ''){
echo 'Please enter firstname';
}
}
You can also learn some validations here
http://www.w3schools.com/php/php_form_validation.asp
I am new to php. I have tried the following code to redirect the page when sign In button is clicked, but it is not happening. please help me editing the code. probably, there is an error in header() function. Have I used the header() function correctly?
<body>
<?php
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "*Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"])) {
$passwordErr = "*Password is required";
} else {
$password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
}
?>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
Add #ob_start(); top of the page,
if (isset($_POST["sign"])) {
header('Location:signInform.php');
}
Just remove following line.
include("signInform.php");
and put header function like below.
header('location:signInform.php');
your issue is header already send.You can avoid this issue by using ob_start().Try like this:
<?php
ob_start();
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{
$emailErr = "*Email is required";}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"]))
{$passwordErr = "*Password is required";}
else
{$password = test_input($_POST["password"]);}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
exit();
}
?>
<body>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
use--- echo '<script> location.href="signInform.php";</script>';
instead of header('Location:signInform.php');
replace if($_POST["sign"])
{
header('Location:signInform.php');
}
to
if($_POST["sign"])
{
echo '<script> location.href="signInform.php";</script>';
}
and why did you include include("signInform.php"); this line that's why showing error already sent.