php header in if statement not working - php

I am currently working on a login page on wich i want the user to be redirected to another page if a boolean read from the database is set on true.
However, the header() in this if statement never redirects the user properly.
here is a sample of my code:
<?php
session_start();
include_once 'php/dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$gebruikersnaam = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE username = '" . $gebruikersnaam. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
if($row['initialised'] == true)
{
header("Location: dashboard.php");
exit();
}
else{
$_SESSION['usr_name'] = $row['username'];
$_SESSION['usr_company'] = $row['companyname'];
header("Location: starter-page.php");
exit();
}
} else {
$errormsg = "Incorrect Email or Password!";
}
}
?>
If i put the if condition on false. The second header with "location: strater-page.php" will redirect to the correct page.
I do not have any unnecessary whitespace.
Puttin:
error_reporting(E_ALL);
ini_set('display_errors', 1);
In the code doesn't show anything.
I am not outputting anything before the header...
Am i missing something?

try redirect using script
<?php
if($row['initialised'] == true)
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='dashboard.php';
</SCRIPT>");
}
?>

Related

Change text upon redirect from certain page...?

As the title suggests I am trying to use the same .php page and have it display something new upon being redirected from a particular location.
In context...
I have a login which upon successful login redirects to a home page but if unsuccessful, redirects to the index. Is there a way that I can tell my index page to display an "Error logging in" message when it has been redirected from my login page?
Here is my login code...
<?php
session_start();
include('conn.php');
$query = "SELECT * FROM User";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (isset($_POST["submit"])) {
$logEmail = $conn->real_escape_string($_POST['logEmail']);
$logPass = $conn->real_escape_string($_POST['logPass']);
$checkuser = "SELECT * FROM User WHERE Email='$logEmail' AND UserPassword=AES_ENCRYPT('$logPass', 'MyKey')";
$userresult = mysqli_query($conn, $checkuser) or die(mysqli_error($conn));
$loginsucc = (mysqli_num_rows($userresult) > 0);
if (mysqli_num_rows($userresult) > 0) {
while ($row = mysqli_fetch_assoc($userresult)) {
$userPriKey = $row['UserID'];
$userid = $row['Email'];
$accounttype = $row['IsAdmin'];
$firstname = $row['FirstName'];
$surname = $row['LastName'];
$_SESSION['userPriKey'] = $userPriKey;
$_SESSION['name'] = $firstname;
$_SESSION['surname'] = $surname;
$_SESSION['Email'] = $userid;
$_SESSION['IsAdmin'] = $accounttype;
if($accounttype == '1'){
header("Location: home.php");
}else if ($accounttype == '0'||$accounttype == NULL ) {
header("Location: userhome.php");
}
}
} else {
header("Location: index.php");
}
}
?>
Before you call header() set a session variable like so
$_SESSION['msg'] = 'success you are logged in';
header('Location: page.php');
exit;
Then in page.php,
session_start();
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Also FYI, you should be using prepared statements. Your code is not totally safe

acessing a php page only when a different php page directs to it

After submiting username and password in connect.php, user reaches contentselect.php .But if a user enters url like localhost/users/contentselect.php he is still able to see the contentselect.php page,which he should not see because he has not entered username and password in connect.php
//connect.php
<?php
Include ('mysql.php');
session_start();
if (isset($_POST['name'], $_POST['password']))
{
$name = $_POST['name'];
$password = $_POST['password'];
$password = md5($password);
$result = mysql_query("SELECT name,password FROM project WHERE name='" . $name . "' AND password='" . $password . "'");
if (mysql_num_rows($result) > 0)
{
$_SESSION['logged_in'] = true;
$_SESSION["name"] = $name;
header('Location:contentselect.php');
exit();
}
else
{
echo "wrong password or username";
}
}
?>
//this is contentselect.php
<?php
session_start();
echo "Hello ".$_SESSION["name"]."!";
?>
Keeping in mind everything #Fred-ii mentioned, This should work:
<?php
session_start();
if(isset($_SESSION['logged_in']))
{
echo "Hello ".$_SESSION["name"]."!";
}
else{
echo "Sorry Charlie";
}
?>
Or you could use cookies too!
Ofcourse you would have to set the cookies first and then unset it in your signout.php page.
login.php
if($user == $user_db && $pass == $pass_db)
{
$Month = 86400 + time();
setcookie('name', $user, $Month);
exit(header("Location:index.php"));
}
signout.php
if(isset($_COOKIE['name']))
{
unset($_COOKIE['name']);
setcookie('name', '', time() - 3600, 'login.php');
setcookie('name', '', time() - 3600, 'signup.php');
echo "<script type='text/javascript'>alert('YOU HAVE LOGED OUT!')</script>";
}
exit(header("refresh:1; url=welcome.php"));
You need to check that the user is logged in on the contentselect.php page, so you'd need to change that page to something like this:
//this is contentselect.php
<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
header('Location: connect.php');
exit();
}
echo "Hello ".$_SESSION["name"]."!";
?>

PHP script reports wrong credentials

Ok, this is my code for authentication. For now, i have one table and 5 PHP working scripts except this one. After successful login, user should be redirected to his home page, but the problem is, PHP echoes "Cannot login" error message regardless of login details. Heres the script:
session_start();
include_once'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header ("Location: home.php");
}
if (isset($_POST['login'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = mysql_query("SELECT * FROM users WHERE email='".$email."'");
$num = mysql_fetch_assoc($sql);
if ($num['password'] == $pass)) {
$_SESSION['user'] = $num['user_id'];
header ("Location: home.php");
}
else {
echo "Cannot login";
}
}
Any hints ? Thank you
session_start();
include_once'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header ("Location: home.php");
}
if (isset($_POST['login'])) {
$email = mysql_real_escape_string($_POST['email']);
$pass = mysql_real_escape_string($_POST['pass']);
$sql = mysql_query("SELECT * FROM users WHERE email='".$email."'");
$num = mysql_fetch_assoc($sql);
if(count($num)>0){
if ($num['password'] == $pass)) {
$_SESSION['user'] = $num['user_id'];
header ("Location: home.php");
}
else {
echo "Cannot login";
}
}else{
echo "Cannot login, email id not found";
}
}
Make sure you are getting password from the data base.
1.I think Your password encrypted in db.
2.Check it out it may be md5,sha etc.
3.If yes. Change Like this
if ($num['password'] == md5($pass)){
.
.
.
.
}
Hope It Helps..

How to redirect to different page after form is submitted using header()?

I've looked at lots of answers to redirect to a different page after submitting a form, but haven't been able to get it to work thus far, probably because I have no idea where to actually put the code. Can anyone help? The rest of this code is working fine, i just need to know where to place header():
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
//connects to database, checks username & password against database to see is user exists
if($username && $password)
{
include ("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username='$username'");
$numrows = mysql_num_rows($query);
if($numrows !==0)
{
while($row = mysql_fetch_assoc($query))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
//if username and password are correct
if($username==$dbusername&&md5($password)==$dbpassword)
{
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
}
//if password is incorrect
else
echo "Your password is incorrect.";
}
//if username is incorrect
else
die("Username does not exist.");
}
//if no information is submitted
else
die("Please enter your login details.");
//prevents errors from displaying on page
error_reporting(0);
?>
I also need to know where it goes for this page:
<?php
//Check if register button was pressed
$button = $_POST['button'];
//if button was pressed,
if ($button)
{
//get data from form,
$username = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
}
//check if all information has been entered,
if ($username && $password && $retype_password && $first_name && $last_name)
{
//check if password and retype_password are the same
if($password==$retype_password)
{
//check if username already exists
include("connect.php");
$query = mysql_query("SELECT * FROM users WHERE username = '$username'");
$numrows = mysql_num_rows($query);
if($numrows == 0)
{
//encrypt password
$password = md5($password);
//sends data from form to database - creates new user
$register = mysql_query("INSERT INTO users VALUES ('', '$username', '$password', '$first_name', '$last_name')");
echo "You are now registered. <a href='main.php'>Continue to site.</a>";
}
else
echo "Username is unavailable.";
}
else
echo "Password did not match.";
}
//prevents errors from displaying on page
error_reporting(0);
?>
Thanks in advance!
if($username==$dbusername&&md5($password)==$dbpassword)
{
$_SESSION['username'] = $username;
header( 'Location: http://www.yoursite.com/new_page.html' ) ;
}
You should put it once the job is done : that is after
//echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Don't forget the "exit" or what follow will be executed.
That said, you cannot echo something before a doing redirection, that's logical because the echo can't be seen.
So, either you do not echo :
$_SESSION['username'] = $username;
header('Location: your url');
exit;
Or you do a HTML (or javascript) redirection, with a 5 seconds delay:
echo "You are logged in. <a href='main.php'>Continue to site.</a>";
$_SESSION['username'] = $username;
exit;
In which case you have to put it in the < head > section, to do the HTML redirection:
<meta http-equiv="refresh" content="0; url=http://example.com/main.php" />
Also
error_reporting(0);
Should be put at the beginning of the page, unless you want errors for previous lines to be shown.
BUT : error_reporting(0); should NEVER be used on a development site (and always on a production site).
You should turn on display_errors('on') and error_reporting(E_ALL) to see errors - errors are very useful for a developer.

$_SESSION not working correctly

I have made a simple login script here.
There are 3 files, 1 is functions.php(Containing the login function), then there is userdashboard.php, which contains some user functions and then another file users.php which processes the login.
The problem is, whenever I login, the login in successful but it throws the error :- unknow variable username.
It should display the username of the person logged in, what am I doing wrong ?
Here's the code :-
functions.php
<?php
include 'dbconnector.php';
function checklogin($username,$password)
{
include 'dbconnector.php';
$userexists=false;
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
$query="select * from f_users where username = '" . $username . "' and password = '" . $password . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$userexists=true;
}
else
{
$userexists=false;
}
return $userexists;
}
userdashboard.php
<?php
include('dbconnector.php');
session_start();
if(isset($_SESSION['logged']) && $_SESSION['logged']=1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
else
{
header('Location:login.php');
}
echo 'logout';
?>
file where login is processed.
include 'functions.php';
.
.
.
case 'login':
$username=$_POST['username'];
$password=$_POST['password'];
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
if((!empty($username)) && (!empty($password)))
{
if(!checklogin($username,$password))
{
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
}
else
{
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
}
}
else
{
echo "username or password fields cannot be empty, redirecting";
header('refresh:2;URL=login.php');
}
break;
Thanks for the fix Houssni.
I have a weird error here.
Even if I try a valid combination of username and password, it always goes to the else part and throws the error.
What wrong am I doing here ?
$username=mysql_real_escape_string($username);
$password=mysql_real_escape_string($password);
$password=md5($password);
$query="select * from f_users where username = '" . $username . "' and password = '" . $password . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
session_start();
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
exit();
}
else
{
echo mysql_num_rows($result);
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
exit();
}
$username is a parameter so you can only use it in its function scope.
Get the username by $_POST or set the $_SESSION in that function.
Or in userdashboard.php you should assign the variable $username again and give its value.
And in functions.php you have another include inside this function. You are including this file twice if you call this function.
And in the end of where you call you header("Location: ") you should call exit() because else it will keep running the PHP code of that page.
There is another error in your userdashboard.php
change
if(isset($_SESSION['logged']) && $_SESSION['logged']=1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
To
if(isset($_SESSION['logged']) && $_SESSION['logged']==1)
{
$_SESSION['username']=$username;
echo "Hello " . $username;
}
session_start() function need to include in condition section,
if((!empty($username)) && (!empty($password)))
{
if(!checklogin($username,$password))
{
session_start(); // added session start
$_SESSION['logged']=1;
$_SESSION['username']=$username;
header('Location:userdashboard.php');
exit();
}
else
{
echo "Invalid combination of username and password";
echo "redirecting to the login page";
header('refresh:2;URL=login.php');
exit();
}
}

Categories