Question

I have created a HTML login form which checks for email and password authentication and then redirects to the user account.

My PHP code is as below:

 <?php  

 require('connect.php');//for connection to the database.


$email = $_POST['email'];
$password = $_POST['password'];

$query = "SELECT * FROM `account` WHERE pemail='$email' and password='$password'";

$result1 = mysql_query($query) or die(mysql_error());
$usercount = mysql_num_rows($result1);




if ($usercount == 1){
include 'myaccount.php';
}


else{

echo "Invalid Details.";
echo "<a href='login.php'>Back to Login</a>";
}

Here, I have tried include to redirect to the user account...and it works fine.

Though my instructor says me that it is wrong to use include and you should implement it in another ways.

Why it is wrong to use include to redirect to the user account? I searched for it but I didn't found the answer.

plz do not discourage...thanks in advance.

Was it helpful?

Solution

Yes, your instructor is correct. include() is for including PHP code, not for redirecting. header() function does that, so use it. Using include() works, but that doesn't mean you should use it.

Why shouldn't you use include?

  • include() is a function for "including" code from a different file. It loads and executes the code from the file and is not exclusively built for redirecting. On the other hand, the sole purpose of header() is to send raw HTTP headers, i.e. perform redirects and the like. Use that instead.

  • If you have multiple lines of code in the file you're using for the redirect, include() will execute it completely, every time you perform a redirect. If your application uses redirects heavily, this would mean a performance loss and would result in a laggy application. Moreover, you'll be needlessly executing several lines of code if you're using include(). If you were to use header(), you could avoid this problem. (By calling exit() right after header().)

More problems in your code:

  • You're using mysql_* functions. The ext/mysql extension is deprecated and shouldn't be used. Use MySQLi or PDO instead.

  • You're blindly injecting user input into your database query, thereby making it vulnerable to SQL injection. A user with malicious intent could technically cause troubles, or even delete your database entirely. Use PDO / MySQLi with prepared statements to prevent this from happening. See this question for more details on how.

OTHER TIPS

Try this

    if ($usercount == 1) {
        $redirect_url = "";//here goes your url where you want to redirect the user to
        header("Location: " . $redirect);
        exit();
    }

You should also look into MySqli or PDO

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