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!
Related
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.
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
if(isset($_POST['chgPwd']))
{
$oldpwd=$_POST["txtOldPassword"];
$newpwd=$_POST["txtNewPassword"];
$cnewpwd=$_POST["txtConfirmNewPassword"];
//did stuff to get in the text fields
$oldpass = oci_result($new1,"OLDPASS");
if($oldpwd!=$oldpass)
{
$msg = "The old password does not match with the one in the records";
header("Location:ErrorPage.php?abc=".$msg);
}
}
?>
My question here is that when i redirecting my page to the ErrorPage.php, I am able to see the entire page in the URL, which i do not want it to. Is there anyway around this. I am thinking of binding sessions, but i am unable to get it right. Could you please show me the right way if there is any?
You should urlencode($msg) ( string $str ) and perhaps add an exit() after header.
Edit: Well, you only want to see ErrorPage.php in your browsers URL, right? Without any message or attributes? Then you have to work with SESSIONS (or Cookies) to store the message/location for the current user and then to redirect him back to ErrorPage with the individual message.
Get rid of the error page and show your errors oncite.
Here is the sketch of the registration code
<?
include 'config.php';
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';
?>
and a template contains the form and the error mesages
<? 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>
This is the most common way of form processing called POST/Redirect/GET
header("Location:ErrorPage.php?abc=1");
ErrorPage.php
if(isset($_GET['abc'])=="1")
{
Show Some Message
}
You can use sessions to hide that parameters. It's the simplest way.
I have a registration page and I am going to check the values of each field in both javascript and PHP. The problem is I have the registration code behind in a separate file. I put it in a seperate file because I am querying a database and much more so I ruled out posting to self. I then figured that redirecting to an separate error page would be overkill.
So what I would like to do is redirect to the registration page with the error message at the top or something of the sort just like if I was posting the form to self. How can I go about doing this?
It's ok to have registration code in the separate file.
However, this file have to be the registration page itself.
While the form is stored in the another file and just get included.
Here is the sketch of the registration code
<?
include 'config.php';
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';
?>
and a template contains the form and the error mesages
<? 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>
This is the most common way of form processing called POST/Redirect/GET
Why don't you just post to self? All you must do is structure the php so that once verified it inserts the data ect...
if( isset($_POST[ 'submit' ]) ){
//Do checks
// if all checks pass do your thing.
// redirect.... header();
exit;
}
// you could then do if( isset($_POST['name']) ){ echo 'name'; } to repopulate the fields so you don't irritate the user.
If you still insist on doing it this way still use header() to redirect your user. (not a plesent user experience in my opinion...and the user have to refill all the data out again.)
You could post to your authentication page, check if they have a blank field or whatever, then redirect via
header(Location:<your url here>?error=1);
back to the original page and have that page check for the GET variable $_GET['error']. If that variable is 1, display some error.
Is this what you are looking for?
I've a basic login form to which I want to add some validations. I came up with these:
$errors = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(0 === preg_match("/.+#.+\..+/", $_POST['email'])){
$errors['email'] = "Please enter a valid email address";
}
if(0 === preg_match("/.{6,}/", $_POST['password'])){
$errors['password'] = "Please enter you correct password";
}
if(0 === count($errors)){
// SUBMIT THE FORM, <form action='auth.php' method='post'...
}
}
So, how can I accomplish the last IF part, which will submit the form if there's no error? Thanks in advance
I think you're trying to use PHP in a situation where you need JavaScript.
If you're talking about actually submitting a <form> element on an HTML page, then you need JavaScript. PHP only fires, in this case, when the form is submitted.
If, however, your intent isn't to submit the form element and instead perform a task (or series of tasks) based on a validated form, then you would just have to include your logic appropriately.
For example:
if( count($errors) > 0 ){
// THERE IS A PROBLEM, RETURN THE ERRORS
include( 'myHTML.html' );
exit();
}
// If the above didn't fire, then we have no errors
echo( "Wonderful! Now we can add this information to a database, or something." );
I would imagine if this code is in auth.php then you are already submitting the form.
Think of it this way: You submit the form no matter what, but stop the submission if there are errors. You process may look something like the following:
form.php
<?php
if($_GET['error']){ echo '<p>There was a problem with your input</p>'; }
?>
<form method="post" action="auth.php">
<input ... />
<button type="submit">Submit</button>
</form>
auth.php
$errors = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(0 === preg_match("/.+#.+\..+/", $_POST['email'])){
$errors['email'] = "Please enter a valid email address";
}
if(0 === preg_match("/.{6,}/", $_POST['password'])){
$errors['password'] = "Please enter you correct password";
}
}
if(0 === count($errors)){
// do your form action as normal
}
else {
header('Location: form.php?error=1');
exit();
}
I don't see a problem there. The only thing you should do is move the if-part up so it will only be called when the request method is post. Is this solving your problem? If not, please describe your problem in detail.