Ternary Operator on form action - php

I am new to PHP, but what I want is for the page to self-process (contact.php) if there's an error, but go to another PHP page (contactconfirm.php) if it passes validation. Can someone tell me what's wrong with this code?
if(isset($_POST['submit'])){
if(empty($name)) {
$errors ++ ;
echo "<p>You did not enter a name.</p>";
} else {
$errors = 0;
}
if(empty($email)) {
$errors ++ ;
echo "<p>You did not enter an e-mail.</p>";
} else {
$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)){
$errors ++;
echo "<p>Invalid e-mail. Please try again.</p>";
} else {
$errors = 0;
}
}
} //closes isset
?>
<div class="contact-form">
<div class="inputArea">
<form action="<?php echo ($errors > 0) ? 'contact.php' : 'contactconfirm.php' ?>" method="post">

Every time you pass a verification stage, you reset $errors to 0.
e.g.
check if "foo" is correct: nope, increments $errors -> `1`
check if "bar" is correct: yep, reset $errors to 0
if ($errors == 0)
everything is perfect! happy joy joy!
}
but oops, "foo" was wrong, and now you've said everything was ok, because your error counter got reset. Simply remove ALL of the $errors = 0 from inside your verification/validation stages.

See Marc B's answer to point out the first initial problem.
You reset your $errors = 0 in the else of each check. You must remove these statements, otherwise if the later check statements are valid, the $errors variable will be reset.
Also, it would be much better to not print the errors during the checks, but rather to append to an error array, and check the errors variable after all of the error checking has occurred.
e.g.
if($errors>0){
print_r($errorArray);
}
or
if($errors>0){
foreach($errorArray as $error){
echo $error;
}
}
Also, it is unclear without the rest of your code, but it seems like the top half is validation after being redirected to this page, but that will never occur, because you are automatically setting the form action to contactconfirm.php in the first place, since $errors will not have a value on first page load. I may be misinterpreting your code without the full page though.
You should consider removing the turnary operator in your form, and having the action always be contact.php.
Then you can use conditional logic to check if there are no errors, and if not, redirect using header("Location: contactconfirm.php"). See this documentation on header for more info.

Related

PHP Session lost/login not working

I have a question regarding sessions in php. I made a login page, and whenever I tried it, it just gave me a redirect error. So I followed the answer from this question.
So now, instead of getting the redirect error, whenever I press the login button nothing happens, the form is emptied and that is all. What am I doing wrong? This is currently how the code which is giving me issues looks like.
index.php:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$password = $_POST['password'];
$file = file_get_contents("data.txt");
if (strstr($file, "$name||$password")) {
$_SESSION["valid_user"] = $_POST["name"];
$_SESSION["valid_time"] = time();
Header("Location: welcome.php");
} elseif (empty($name) && empty($password)) {
echo "Both fields are empty. Please fill them.";
} elseif (empty($name)) {
echo "No name was entered.";
} elseif (empty($password)) {
echo "No password was entered";
} else {
echo "Wrong credentials, please try again.";
}
}
To be more specific the code which I think is the problem is this part:
<?phpsession_start();
if (isset($_SESSION['valid_user'])) {
Header("Location: index.php");
exit();
}
But whenever I try it I either get the redirect error:
My browser gives me "ERR_TOO_MANY_REDIRECTS" when I try to enter the page.
or the page just empties the form and nothing else happens. And the error messages which are supposed to be displayed when I don't type anything in the form is not displaying either. It's been giving me headaches the whole day today so if anyone could just point me in the right direction that would be great.
Also the form HTML I use in index.php:
<body>
<form method="post" action="index.php" >
<p>Enter name:</p>
<input type="text" name="name" />
<br/>
<br/>
<p>Enter password:</p>
<input type="password" name="password" />
<br/>
<br/>
<input type="submit" value="Login" name="submit"/>
</form>
</body>
I think there are too many errors related to code. There must be spaces between the opening PHP tag and session_start();.
Plus, the conditional statement you've given in if (isset($_SESSION['valid_user'])) is being interpreted as "if it IS set". What you should have used is the ! operator, meaning if it is "NOT" set.
That is why you are getting "too many redirects".
<?php session_start();// try putting space between here
if (!isset($_SESSION['valid_user'])) {
header("Location: login.php"); // Redirect back to your login page
exit();
}
also in } elseif (empty($name) && empty($password)) {
// all elseif should be like else if(condition)
also change file names.
You should also add an exit; after every header, otherwise your code will want to continue to execute.
Problem is here when you have a valid user then you are trying to redirect it on index.php which again check for valid user and again redirect on index.php its like INFINITE loop.
Thanx #Fred-ii-
You've got your answer but here is an explanation about "Too many redirects". You are getting that error on your browser because your code is keep redirecting to another page. Both of your statements are returning true:
if (isset($_SESSION['valid_user'])) {
} //Returning true - Redirect to index
if (strstr($file, "$name||$password")) {
} //Returning true - Redirect to welcome
As there are/were no exits after the redirects, the code carries on executing: redirect here than redirect there...
Also you should check the session validation as follows:
if(!isset($_SESSION['session']) || $_SESSION[''] == "")
This will check if the session is not set OR empty.

php custom error message shown incorrectly

i'm working on a php assignment for log in function using .txt file instead of db, but i'm facing with some sort of problem here. supposedly the "invalid email or password" to be shown after a non exist details key in, but when the page load, the msg showed by default, below is my code
<?php
$lines= file("customers.txt");
$matchFound=false;
$errmsg = 'Invalid email or password';
for($i=0;$i<count($lines);$i++)
{
if ($i!=0)
{
$line=trim($lines[$i]);
$cells=explode("\t",$line);
$_SESSION['email'] = isset($_POST['email'])? $_POST['email'] : null;
$_SESSION['password'] = isset($_POST['password']) ? $_POST['password'] : null;
if ($_SESSION['email']==$cells[2] && $_SESSION['password']==$cells[3])
{
$matchFound=true;
break;
}
}
}
if ($matchFound == true)
{
header('Location: login2.php');
}
else
{
echo $errmsg;
}
?>
This is because you're not checking if the user submitted the form input correctly. The value of $matchFound is FALSE by default, and the error message will always be displayed when the script is ran.
Specify a name attribute for your form submit button, and then add an if block to make sure the form was correctly submitted:
if (isset( $_POST['submitButton'] )) {
# code...
}
That way, the code inside the if block won't be run if the user input wasn't received and you could avoid the error being displayed every time you load the page.
Also, you're missing the session_start() statement at the top of your script. This is required if you want the sessions to work properly.
Try:
if ($matchFound == true)
{
header('Location: login2.php');
}
else if(isset($_POST['email']))
{
echo $errmsg;
}
Also you need session_start to use $_SESSION array

PHP:my session_variables shows when the page refresh

I know this is very simple thing but i am not aware of this. I have php code on same page for a signup form which have some session variables to be shown when any condition matches with the code.
The code structure is like this:
<?php
session_start();
if(isset($_POST['signup'])
{
if(condition)
{
$_SESSION['err1']="string";
}
else
{
$_SESSION['err2']="string";
}
}
?>
//HTML form
<?php if(isset($_SESSION['err1']) {?>
<li><?php echo $_SESSION['err1'];}?></li>
<?php if(isset($_SESSION['err2']) {?>
<li><?php echo $_SESSION['err2'];}?></li>
//rest of the form
I have more block of if-else in my code. Initially, when an condition is matched, the session message is shown. But as soon as the page refresh an another session message is shown along with previous session message.
Is this correct way of coding with forms? Because i want to show error messages inside the html form.
That's maybe because you do not empty your session variable.
Between 2 HTTP request, the session is kept on the server (juste reloading at each request).
So, if you are putting a message on $_SESSION['error1'] for the first call, it will show it. Then, on the second load, if you are putting a message on $_SESSION['error2'], you will also have the message of error1 because the session keep your data.
After showing the form, you should empty all your session messages
Simply unset your session variable after you echo.
<li><?php echo $_SESSION['err1'];} unset($_SESSION['err1']); ?></li>
This is really a bad example that use session to echo errors.
what i do many times at the starting of my php.
$errors = array(); // make a empty array errors before the conditional statements
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Submit'])) {
//handle your POST variable
if(condition1){
$errors[] = "some error";
}
if(condition2) {
$errors[] = "some another error";
}
//more conditions
if (!empty($errors)) {
//process your form data if there is no errro
} else {
//display back your form along with Errors
if(isset($errors) && !empty($errors)) {
foreach($errors as $error) {
echo "<p class = 'error'>" . $error . "</p>";
}
}
<form action = "" method = "POST">
//your form elements
</form>
}
}
in first line of the php page, u can write
you can try any of the three lines between if condition
if(isset($_SESSION))
{
unset($_SESSION);
unregister($_SESSION['variable-name']) // try this also
session_destroy(); //try this also
}

php redirection not working

Ive got this register script that puts the information into a mysql database. now it all works fine and when someone does something wrong its says the error (e.g. "Username not defined")
but when it goes wrong it does not look very good because it just displays the message on an empty page, so i thought i would make it redirect to the form page and display the message there.
here is the working script
$forename = $_POST['forename'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = $_POST['username'];
$errors = array();
if(!$username) {
$errors[] = "Username is not defined";
}
if(!$password) {
$errors[] = "Password is not defined";
}
and it continues.
now i just thought i could do this
$errors = array();
if(!$username) {
$errors[] = header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
}
if(!$password) {
$errors[] = "Password is not defined";
}
but no, all it does is ignore it.
could someone please help me
please feel free to ask for more of the script if you need it
many thanks connor
You cannot wrap a header in a array like that.
You just call the function, then it redirects.
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' ) ;
it does not look very good because it just displays the message on an empty page,
What's the problem?
Why not to show the form again? with fields already filled.
This is going to be a user-friendly interface.
Just include your form in the same page with fields populated.
That's more common way than your redirects to blank form.
This is called POST/Redirect/GET pattern and here goes a short example of it:
the code
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
the template
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
You are placing the return value of the header function in an array, then continuing with your page execution.
If you don't care about anything that would normally happen below that redirection, which I believe is what you're implying, you should just set the header and then immediately exit. Do not try to place the return value of the header function into the errors array like that, as there's no point.
if(!$username) {
header('Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined');
exit;
}
I don't if this is the problem, but it's important to include the status code in header too. Like:
header("Location: /foo.php",TRUE,302);
307 for Temporary Redirect, 302 for permanently moved. Chrome, a while ago, didn't accepted headers redirect without status code (i don't know nowadays).
try this after filling your error array:
if (count($errors) > 0)
{
header( 'Location: http://localhost/muiltabledistractions/#!/page_register_error-Username-is-not-defined' );
exit;
}
Keep in mind there should be no html output before this part!

Verify form field with isset()

Having issues with verifying that my form fields are not empty. I thought I used isset in the past but I am having issues with it below. I know I can do it with =="" but want to figure it out this way.
if(isset($_POST['submit'])){
$error= false;
if (isset($_POST['name'])){$name=$_POST['name'];}else{$error=true; $error_message="enter a name"; echo "no name";};
if(!$error){
//SUBMIT TO DATABASE
}else{ echo $error_message;
}
}
But I keep getting the error that error_message is not set.
Isset() just test if the variable exists. It's almost always the case in a POST form (even if variable is empty). To be sure they're not, use the empty() test.
Here is the code :
if(count($_POST) > 0){
$error = false;
if (!empty($_POST['name']))
$name = $_POST['name'];
else{
$error = true;
$error_message = "enter a name";
echo "no name";
}
if(!$error)
//SUBMIT TO DATABASE
else
echo $error_message;
}
you also had a syntax error with the semicolon after your first else.
Be careful, a variable set to 0 is detected as being empty. Check http://php.net/manual/en/function.empty.php
First, I'd recommend -not- using this method to determine if there was a post. I generally use one of the following:
if($_POST)
OR
if(count($_POST) > 0)
The second isset() call (to check for the name) is fine. Try using full caps to set TRUE or FALSE to the $error variable. You can also use 0 and 1 for TRUE and FALSE respectively; they work fine with if($error) and if(!$error). I believe this is where your problem lies. That is, $error was never set properly, so it is in fact not TRUE, but 'false'. However, because $_POST['name'] wasn't set, and $error_message was not either. Let me know if this works for you. I'll look into it further if it doesn't.
An empty PHP string is not null:
$a = '';
echo isset($a); //true
echo $a == ''; //true
use == instead
You could also use empty($var) function

Categories