Question

I'm creating a website that requires the user to enter a username and password to access the site. Everything works perfectly. If right password and username are entered, access is granted. If not, it redirects the user to the same login form page. However, the problem i'm facing is in the following code in php:

 if (!$_POST['username'] | !$_POST['pw'] ) {

        die("At least one box was left empty");

    }

This piece of code checks if the user left any of the 2 input boxes empty. It kills the site and outputs the wanted sentence. However, what i would like to do is redirect the user into the Login form page. Any help with that? Thanks folks

No correct solution

OTHER TIPS

You haven't even tried to redirect.

Use header("Location: login.php"); (with whatever the location of your login page is, if it's not login.php), then exit.

WRONG:

   if (!$_POST['username'] | !$_POST['pw'] ) {

Wrong syntax in your example, you need to add one sign to make it correct:

CORRECT:

   if (!$_POST['username'] || !$_POST['pw'] ) {
                            ^

There are two possibilities:

  • Use the header()-function: header('Location: login.php');
  • Echo/ Print a java-script tag: echo "<script language="javascript">window.location.href='login.php';</script>

The header()-function can only be used, if you do not output some text before you call it.

First, you have to use double | to compare, the correct way is: value || value

Redirect to the login using header('Location: login.php');

If you prefer to show an extra message in the login form with the error, you can do something like this: header('Location: login.php?error=1');

Then, in the login.php you can check for $_GET['error'], doing the following:

if($_GET['error'] == 1){
     echo "You have to fill username and password in order to continue.";
}

You can use the empty and header functions !

<?php
if(empty($_POST['username']) OR empty($_POST['pw']))
{
    header('Location: pathtoyourloginpage.php');
}

else
{
    echo "OK";
}
?>

empty check if $_POST['username'] and $_POST['pw'] are empty. If it so they return TRUE else FALSE.

OR is a logical operator, you'll found more infos here : http://www.php.net/manual/en/language.operators.logical.php

More informations about empty(); and header();

http://php.net/manual/fr/function.empty.php

http://fr2.php.net/manual/fr/function.header.php

This is the best way to solve your problem:

You need to declare this variable first, in your core.php file, for example and use it in all your php files, or just declare it in the file you are working on:

$current_file = $_SERVER['SCRIPT_NAME'];

Then simply use it in the header() function:

header('Location: '.$current_file);

The opportunity in this method is that you use a universal variable to specify the url in the header function or in any other function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top