This if statement is not working. I am trying to make it so that all the things must contain a value for the first statement to be shown, but it works when only one value is selected.
<?php
if ((isset($_POST["FirstName"]))&&(isset($_POST['SecondName']))
&&(isset($_POST['email']))&&(isset($_POST["submit"]))) {
echo "You've given all your details";
}
else {
echo "Please enter all your details";
}
?>
Even if the input is not filled it will be set. you need to check if it is set and if it contains input.
Try making a function to do just that:
function issetWithInput(&$va){
return (isset($va) && !empty($va));
//checks that it is set and contains input.
}
Then you can do something like:
if(issetWithInput($_POST["FirstName"])&&issetWithInput($_POST['SecondName'])..) {
Try this
<?php
if (isset($_POST['FirstName']) &&
isset($_POST['SecondName']) &&
isset($_POST['email']) &&
isset($_POST['submit']) &&
!empty($_POST['SecondName']) &&
!empty($_POST['FirstName']) &&
!empty($_POST['email'])) {
echo "You've given all your details";
}
else {
echo "Please enter all your details";
}
?>
this is what i do when checking my form
<?php
$firstname= $_POST['FirstName'];
$secondname = $_POST['SecondName'];
$email = $_POST['email'];
$submit = $_POST['submit'];
if ($submit)
{
if ($firstname&&$secondname&&$email)
{
echo "You've given all your details";
}
else
echo "Please enter all your details";
}
?>
but i may have miss understood what you are tying to do :), please do ignore this if this makes no sense at all (im still rather new to php)
Related
I'm looking to create a sign-up page for a large-scale website which means I'm using a lot more layers of validation then I would normally do, given this should be common practice but in this particular case more than any other situation it is imperative.
I've already written most of the code required and formatted it in an order which I believed wouldn't lead to any undefined variable errors, however, upon form submission it doesn't create a new SQL row and doesn't return any errors under the error handling areas of the form validation. In all fairness, the error handling is quite simple at this point and is not a final version, just what I put in place to help me debug and troubleshoot any issues which should arise.
Here's the PHP code, and the snippet of the piss-poor error handling that is supposed to output an error message if an error occurs, to re-state, this error handling isn't final.
$conn = mysqli_connect('localhost', 'root2', '123', 'db');
$signupConditionsMet = "0";
if (isset($_POST["email"]) && isset($_POST["username"]) && isset($_POST["password"]) && isset($_POST["passwordCheck"]) && isset($_POST["birthdate"])) {
$signupConditionsMet = "1";
$birthGood = true;
$passGood = false;
$nameGood = false;
$emailGood = false;
}
$usernameSearch = $conn->prepare("SELECT * FROM users WHERE username = ?");
$userInsertion = $conn->prepare("INSERT INTO users (username, passwd, birthdate, email) VALUES (?,?,?,?)");
$nameErr = $emailErr = $passErr = $birthErr = "";
$name = $email = $pass = $birth = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
$email = $_POST["email"];
$pass = $_POST["password"];
$birthdate = $_POST["birthdate"];
$passCheck = $_POST["passwordCheck"];
}
if ($signupConditionsMet === "1"){
function test_input($name) {
if (!preg_match("/^[a-z\d_]{2,15}$/i",$name)) {
$nameErr = "Only letters and white space allowed";
} else {
$nameGood = true;
return $name;
echo "did name ez";
}
}
function test_input2($email){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
} else {
$emailGood = true;
return $email;
echo "did email ez";
}
}
function test_input3($password){
if (!preg_match("/^[a-z\d_]{2,15}$/",$pass)) {
$passErr = "Invalid password format";
} else if (!preg_match("/^[a-z\d_]{2,15}$/",$passCheck)){
$passErr = "Invalid password check format";
} else if ($_POST["password"] !== $_POST["passwordCheck"]){
$passErr = "Passwords do not match";
} else {
$passwd2 = AES_ENCRYPT($_POST["password"], 'mysecretstring');
$passwdGood = true;
return $passwd2;
echo "did pass ez";
}
}
}
if (($signupConditionsMet === "1") && ($birthGood === true) && ($nameGood === true) && ($passwdGood === true) && ($emailGood === true)) {
if ($usernameSearch->execute(array($_POST['username']))) {
while ($row = $usernameSearch->fetch()) {
if (!empty($row['id'])) {
$creationError = "This username is already taken";
} else {
$userInsertion->bindParam(1, $name);
$userInsertion->bindParam(2, $passwd2);
$userInsertion->bindParam(3, $birthdate);
$userInsertion->bindParam(4, $email);
$userInsertion->execute();
header('Location: userlanding.php');
}
}
}
}
/* PHP inside the HTML to output errors */
<?php if ($signupConditionsMet === "1") { echo "all inputs received"; echo $_SERVER["REQUEST_METHOD"];} else { echo "drats, they weren't all there"; echo $name; echo $email; echo $birthdate; echo $pass; echo $passCheck;}?>
<?php if ($passErr) { echo $passErr;} else if ($nameErr) { echo $nameErr;} else if ($emailErr) { echo $emailErr;} else if ($birthErr) { echo $birthErr;} ?>
Disregarding the previously admitted terrible error handling, I can't seem to wrap my head around why it doesn't work in its current form. It returns (from the client-side reporting) that all inputs were received and there isn't any fatal errors thrown from running the PHP code. In addition, the second client-side code which prints any errors doesn't print anything either, implying that all functions operated correctly, however, the echos at the bottom of the input tests don't echo the strings they've been assigned, implying those didn't work, but there was no errors. Hmm. Perhaps I'm missing something blatantly obvious regarding my syntax but I don't see why it wouldn't work. Any help would be appreciated.
I am new to php and I wrote this code:
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
if ((isset($_POST['username']) == $usernametest ) && (isset($_POST['password']) == $passwordtest ))
{ include ('templates/main.php');
}
else
{
echo "please enter the correct username and password combination";
}
exit();
}
?>
I made 2 text boxes and a submit button, I want the user to be directed to another page if the username equals Testing and the password equals TestingPass, and if the user doesnt type in the right combination I want the site to say the username and pass are incorrect. Also, where am I supposed to paste this code exactly? above the text boxes codes ?
You have error in condition checking and redirecting:
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
if ((isset($_POST['username']) && $_POST['username'] == $usernametest ) && (isset($_POST['password']) && $_POST['password'] == $passwordtest ))
{
header('location: templates/main.php');
}
else
{
echo "please enter the correct username and password combination";
}
exit();
}
?>
You want to use header(). You should therefore not have an include in that condition, as headers will already be sent.
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
if ($_POST['username'] == $usernametest && $_POST['password'] == $passwordtest)
{
header("Location: MY_PAGE.php");
}
else
{
echo "please enter the correct username and password combination";
}
exit();
}
?>
Isset() function checks if variable exists and returns boolean. You must check equality like this:
if ($_POST['username'] == $usernametest && $_POST['password'] == $passwordtest)
Always store values in variable to make code more understandable
<?php
$usernametest="Testing";
$passwordtest="TestingPass";
if (isset($_POST['submit']))
{
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == $usernametest && $password == $passwordtest ))
{ header("location:templates/main.php");
}
else
{
echo "please enter the correct username and password combination"; exit();
}
}
?>
I am trying to validate my form using php. Upon validation it will give a welcome message.Or else it will redirect to the index page. I have used session to save the variable. But the problem is nothing happen's when I submit the form, Here's my script
<?php session_start();
$_SESSION['reg'] = array();
$name = $_POST['name'];
$email = $_POST['email'];
$passwd = $_POST['passwd'];
$repasswd = $_POST['repasswd'];
if(empty($_POST)){
header("location:register.php");
}
else
{
if(empty($name)){
$_SESSION['reg']['name'] = "Please enter name";
}
if(empty($email)){
$_SESSION['reg']['email'] = "Please enter email";
}
if (empty($passwd)) {
$_SESSION['reg']['passwd'] = "please enter a password";
}
elseif (strlen(passwd)>16) {
$_SESSION['reg']['passwd'] = "At most 16 chars";
# code...
}
if ($passwd != $repasswd) {
$_SESSION['reg']['repasswd'] = "Passwords don't match";
}
if (empty($_SESSION['reg'])) {
header("location:welcome.php");
}
else
{
$_SESSION['data'] = array();
foreach($_POST as $id=>$val)
{
$_SESSION['data'][$id] = $val;
}
header("location:register.php");
}
?>
when I submit the form, It shows a blank page.
The problem is that you are not storing your post variables into the session if they are NOT empty prior to checking
if (empty($_SESSION['reg'])) {
I would highly suggest doing some sql injection prevention prior to putting post variables into the session scope.
UPDATE: So if you want the variable in the session scope, instead of checking if(empty($name)){ and setting an error message in the session, I would do this:
if( !empty($name) ){
$_SESSION['reg']['name'] = $name;
} else {
// error handling
}
this will set the session variable if the posted value is NOT empty. Now when you check your session variable later on, it will have the name value in it and won't be empty.
I have been using the code below to validate my user input by $_POST:
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
This code checks whether 'name' was actually set, which is obvious and clear and needed.
Secondly, it checks whether user typed something in textfield to give a value for name.
However, if user gives SPACE " " as input it accepts it because it is not empty it has SPACE.
I found one way of doing it right:
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
if(empty($n)) {
$errors[] = "Please give a name";
}
}
else {
$errors[] = "Please give a name";
}
But here I am repeating same error message twice, so how can it be optimized?
if(isset($_POST['name']) && trim($_POST['name']) !== "") {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Remove the empty, and just do the trim.
To be honest, you don't even need the isset unless you have notices turned on:
if(trim($_POST['name']) !== "") {
If you don't need the trimmed string, you can move the trim itself to the if-clause:
if(isset($_POST['name']) && (trim($_POST['name']) != '') ) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
If you further need it, you could modify the input before checking:
$_POST['name'] = trim( $_POST['name'] );
if(isset($_POST['name']) && !empty($_POST['name'])) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Try like this
if(trim(isset($_POST['name']))) {
$n = trim($_POST['name']);
}
else {
$errors[] = "Please give a name";
}
try
if(isset($_POST['name'])) {
$n = trim($_POST['name']);
}
if(empty($n) or !isset($_POST['name'])) {
$errors[] = "Please give a name";
}
Just change your above code to this
if(trim(isset($_POST['name'])))
{
$n = trim($_POST['name']);
}
else
{
$errors[] = "Please give a name";
}
Try using this
if(isset($_POST['name']) && trim($_POST['name']) != false) {
$n=$_POST['name'];
}
else {
$errors[] = "Please give a name";
}
Finally I came to use the following code. It is better because here I can even control minimum number of characters.
if(isset($_POST['name']) && strlen(trim($_POST['name'])) > 1) {
$block->name = trim($_POST['name']);
}
else {
$errors[] = "Please give a name. It should be at least two characters";
}
$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';
$yourname='';
$email='';
$email2='';
$password='';
$password2='';
$country='';
if (isset($_POST['Registerme']))
{
$_POST['yourname']=$yourname;
$_POST['email']=$email;
$_POST['email2']=$email2;
$_POST['password']=$password;
$_POST['password2']=$password2;
$_POST['country']=$country;
if($yourname==''){
$error1='name required';
}
if($email==''){
$error2='email required';
}
if($email2==''){
$error3='required field';
}
if($password==''){
$error4='password required';
}
if($password2==''){
$error5='required field';
}
if($country==''){
$error6='country required';
}
if(empty($error1) && empty($error2) && empty($error3) && empty($error4) && empty($error5) && empty($error6))
{echo 'mysql query goes here and add the user to database';}
}///main one
else {$error1='';
$error2='';
$error3='';
$error4='';
$error5='';
$error6='';}
this is a registration validation script. in my registration form there are two email and password filelds.second fields are for confirmation.i want to check weather user typed same information in that both field.if i want to do that in this script should i use another if statement? or i should use else if? i am confused about that step...
Some comments:
You MUST sanitize input! Take a look at best method for sanitizing user input with php.
Your assignments: Instead of "$_POST['yourname']=$yourname;" it should be "$yourname=$_POST['yourname'];".
You're using a lot of variables for error control, and after that if all went well you simply forget the error messages in the last else block. Use some kind of array for error strings, and use it!
Are you sure you aren't validating usernames/passwords to not contain spaces or weird characters, or emails to be valid?
Some sample code...:
// Simple sanitize function, complete it
function sanitize_input ($inputstr) {
return trim(mysql_real_escape_string($inputstr));
}
if (isset ($_POST['Registerme']) {
// array of error messages to report
$error_messages = array();
$isvalid = true;
// Assignment
$yourname = sanitize_input ($_POST['yourname']);
$email = sanitize_input ($_POST['email']);
$email2 = sanitize_input ($_POST['email2']);
$password = sanitize_input ($_POST['password']);
$password2 = sanitize_input ($_POST['password2']);
$country = sanitize_input ($_POST['country']);
// Validation
if (empty ($yourname)) {
$error_messages[] = "You must provide an username";
}
if (empty ($password)) {
$error_messages[] = "You must provide a password.";
}
elseif ($password !== $password2) {
$error_messages[] = "Passwords do not match.";
}
// Same for email, you caught the idea
// Finally, execute mysql code if all ok
if (empty($error_messages)) {
// Execute mysql code
isvalid = true;
}
}
// After form processing, use isvalid which is false if there are errors
// and the error_messages array to report errors
add additional conditions to your second if statement.
e.g.
if($email=='' || $email != $email2){
...
Just add simple checks. I wouldn't combine the check with the general password check - as I can imagine you would like to tell the user what went wrong exactly.
if ($password1 !== $password2) {
// Add an specific error saying the passwords do not match.
}
I would replace the user of loose errors to an array like:
$aErrors = array();
if ($password1 !== $password2) {
$aErrors[] = 'Another specific error!';
}
if (empty($password1) || empty($password2)) {
$aErrors[] = 'Another specific error';
}
if (empty($aErrors)) {
// Process the form!
}
There are lots of issues with your code.
1. You are assinging $_POST['key'] = $somevalue, while I think you mean $somevar = $_POST['key']
2. Use an array for all error messages as it'll make your life a bit easier ..
3. To compare password use something like
if ($password1 !== $password2) {
}
so .....
$errors = array();
so you'd check something like ..
if ($password1 !== $password2) {
$errors[] = 'Password dont match';
}
if(count($errors) > 0) { //if there are errors
foreach($errors as $err) {
echo $err.' <br />';
}
} else {
// whatever you want to do if no error
}
I'll also suggest to sanitise the $_POST values before you use them in your queries.
I hope it helps.
I think you mean to do this:
$yourname = $_POST['yourname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
$country = $_POST['country'];
Second this make use of an errors array:
$errors = array();
Third use nested ifs(just a suggestion)
if (!empty($_POST['password1'])) {
if ($_POST['password1'] != $_POST['password2']) {
$errors[] = '<font color="red">The 2 passwords you have entered do not match.</font>';
} else {
$password = $_POST['password1'];
}
} else {
$errors[] = '<font color="red">Please provide a password.</font>';
}