Hi friends am trying to redirect a page once user logged in by using heade location but its not working unable to understand why..
Here is code..
<?php include "config.php"; ?>
<?php session_start();
error_reporting(0);
ini_set('display_errors', 0);
if(isset($_SESSION['username'])){
header("Location: user_details.php");
}
?>
Here is my html login with php
<html>
<head>
</head>
<body>
<div id="form">
<form action="" method="POST">
<div class="login-block">
<h1>Login</h1>
<input type="text" value="" placeholder="Username" id="username" name="user"/>
<input type="password" value="" placeholder="Password" id="password" name="pass"/>
<button type="submit" id="btn" value="Login" name="login">Submit</button>
<?php
if(isset($_POST['login']))
{
$username=$_POST['user'];
$password=$_POST['pass'];
$username=mysqli_real_escape_string($conn,$username);
$password=mysqli_real_escape_string($conn,$password);
$password=md5(mysqli_real_escape_string($conn,$password));
$query="SELECT * FROM user WHERE username = '{$username}' and password='{$password}'";
$select_user_query=mysqli_query($conn,$query);
if(!$select_user_query)
{
die("Connection failed".mysqli_error($conn));
}
while($row=mysqli_fetch_array($select_user_query))
{
$db_user_id=$row['id'];
$_SESSION['username']=$row['username'];
$db_user_email=$row['email'];
$db_user_password=$row['password'];
}
if($username === $_SESSION['username'] && $password ===$db_user_password)
{
header("location: titles.php");
}
else
{
echo "<p style='color:#FF7B81'> enter correct username and password <p>";
}
}
?>
</div>
</form>
</div>
Can anyone help me how can I redirect. I have used the echo statement after the heade location only I have tried both 'L' and 'l' in Location
This line will never work:
header("location: titles.php");
as headers must be sent before any form of output. It's usually common practice to place the isset($_POST['submit']) above the HTML block, and assign vars you might want to put into the HTML for later use.
Try reformatting your code as such:
<?php
if(isset($_POST['login']))
{
$username=$_POST['user'];
$password=$_POST['pass'];
$username=mysqli_real_escape_string($conn,$username);
$password=mysqli_real_escape_string($conn,$password);
$password=md5(mysqli_real_escape_string($conn,$password));
$query="SELECT * FROM user WHERE username = '{$username}' and password='{$password}'";
$select_user_query=mysqli_query($conn,$query);
if(!$select_user_query)
{
die("Connection failed".mysqli_error($conn));
}
while($row=mysqli_fetch_array($select_user_query))
{
$db_user_id=$row['id'];
$_SESSION['username']=$row['username'];
$db_user_email=$row['email'];
$db_user_password=$row['password'];
}
if($username === $_SESSION['username'] && $password ===$db_user_password)
{
header("location: titles.php");
}
else
{
$error = "<p style='color:#FF7B81'> enter correct username and password <p>";
}
}
?>
<html>
<head>
</head>
<body>
<div id="form">
<form action="" method="POST">
<div class="login-block">
<h1>Login</h1>
<input type="text" value="" placeholder="Username" id="username" name="user"/>
<input type="password" value="" placeholder="Password" id="password" name="pass"/>
<button type="submit" id="btn" value="Login" name="login">Submit</button>
<?PHP if(isset($error)){ echo $error; } ?>
</div>
You also need to call:
session_start()
before you can assign any session vars.
<html>
<head>
</head>
<body>
<div id="form">
<form action="" method="POST">
<div class="login-block">
<h1>Login</h1>
<input type="text" value="" placeholder="Username" id="username" name="user"/>
<input type="password" value="" placeholder="Password" id="password" name="pass"/>
<button type="submit" id="btn" value="Login" name="login">Submit</button>
<?php
if(isset($_POST['login']))
{
$username=$_POST['user'];
$password=$_POST['pass'];
$username=mysqli_real_escape_string($conn,$username);
$password=mysqli_real_escape_string($conn,$password);
$password=md5(mysqli_real_escape_string($conn,$password));
$query="SELECT * FROM user WHERE username = '{$username}' and password='{$password}'";
$select_user_query=mysqli_query($conn,$query);
if(!$select_user_query)
{
die("Connection failed".mysqli_error($conn));
}
while($row=mysqli_fetch_array($select_user_query))
{
$db_user_id=$row['id'];
$_SESSION['username']=$row['username'];
$db_user_email=$row['email'];
$db_user_password=$row['password'];
}
if($username === $_SESSION['username'] && $password ===$db_user_password)
{
//header("location: titles.php");
echo "<script>window.location.href='titles.php'</script>";
}
else
{
echo "<p style='color:#FF7B81'> enter correct username and password <p>";
}
}
?>
</div>
</form>
</div>
Try This
You have to start object.
// Add this start of file after <?php
ob_start();
Related
I am working on a web project where I want to move from one PHP page to another Php page if condition true...
In below login PHP page, I am getting username and password using $_POST[]. if both username and password got matched in (if statement) of current PHP login page then, I want to jump to another PHP page(choice.php) specified in header function below after if.
<html>
<body>
<head>
</head>
<form method="post" action="login.php">
<div id="div1">
<h1>welcome to bizdiary</h1>
<div id="div2">
<label >Username</label>
<input id="name" type="text" name="username" value=""
placeholder="username" />
<label >Password</label><input type="text" name="password" value=""
placeholder="password"/>
<input type='submit' name="login" value="login" >
</form>
<?php
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
if($username=='root' && $password=='tiger'){
header( "Location:http://localhost/bizdiary/choice.php" ); die;
}
}
?>
This code should work:
The HTML in top of the file.
Remove the action in your form.
<?php
if(isset($_POST['submit'])){
$username=$_POST['username'];
$password=$_POST['password'];
$host = $_SERVER['HTTP_HOST'];
// Put in here the conditional that the request need to accomplish to redirect.
if($username=='root' && $password=='tiger'){
header("Location: http://{$host}/choice.php");
}
}
?>
<html>
<body>
<head>
</head>
<body>
<form method="post">
<div id="div1">
<h1>welcome to bizdiary</h1>
<div id="div2">
<label >Username</label>
<input id="name" type="text" name="username" value="" placeholder="username" />
<label >Password</label>
<input type="text" name="password" value="" placeholder="password"/>
<input type='submit' name="login" value="login" >
</form>
</body>
</html>
You should mysql control. Example
if ($_POST){
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
if (empty($username) or empty($password)){
echo 'Don't leave blank.';
}else {
$user = mysql_query('SELECT * FROM user WHERE username = "'.$username.'" AND password = "'.$password.'"');
if (mysql_num_rows($user)){
header('Location: asd.php');
}else {
echo 'Didn't find user.';
}
}
}
I'm pretty new to php and have been trying to create a site using it. I have created a login page and am trying to provide the option to create a new user by inserting a username & pass into the DB. I feel like this is something simple that I'm missing but i'm not sure so hopefully someone can help :)
php ~
<?php
session_start();
unset($_SESSION["currentUser"]);
unset($_SESSION["currentUserID"]);
if (isset($_POST["action"]) && $_POST["action"]=="create") {
$formUserC=$_POST["name"];
$formPassC=$_POST["pword"];
include("dbConnect.php");
$dbQuery=$db->prepare("select * from users");
$newAcc = "INSERT INTO users (username, password) VALUES ('$formUserC', '$formPassC')";
if($newAcc){
echo "<p>Your account was successfully created.";
}
else{
echo "<p>Error</p>";
}
}
if (isset($_POST["action"]) && $_POST["action"]=="login") {
$formUser=$_POST["username"];
$formPass=$_POST["password"];
include("dbConnect.php");
$dbQuery=$db->prepare("select * from users where username=:formUser");
$dbParams = array('formUser'=>$formUser);
$dbQuery->execute($dbParams);
$dbRow=$dbQuery->fetch(PDO::FETCH_ASSOC);
if ($dbRow["username"]==$formUser) {
if ($dbRow["password"]==$formPass) {
$_SESSION["currentUser"]=$formUser;
$_SESSION["currentUserID"]=$dbRow["id"];
if (isset($_SESSION["homePage"]))
header("Location: addToBasket.php");
else header("Location: homePage.html");
}
else {
header("Location: login.php?failCode=2");
}
} else {
header("Location: login.php?failCode=1");
}
} else {
?>
html (mostly) ~
<html >
<head>
<meta charset="UTF-8">
<title>Flat HTML5/CSS3 Login Form</title>
<link rel="stylesheet" href="css/loginstyle.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" name="create" method="post" action="login.php">
<input type="text" name="name" placeholder="name"/>
<input type="password" name="pword" placeholder="pword"/>
<input type="hidden" name="action" value="create">
<input type="submit" value="create"/>
<p class="message">Already registered? Sign In</p>
</form>
<form name="login" method="post" action="login.php">
<input type="text" name="username" placeholder="username"/>
<input type="password" name="password" placeholder="password"/>
<input type="hidden" name="action" value="login">
<input type="submit" value="login"/>
<p class="message">Not registered? Create an account</p>
</form>
<?php
if (isset($_GET["failCode"])) {
if ($_GET["failCode"]==1)
echo "<h3 style='color:red;'>Invalid username entered</h3>";
if ($_GET["failCode"]==2)
echo "<h3 style='color:red;'>Invalid password entered</h3>";
}
?>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/loginindex.js"></script>
</body>
</html>
<?php
}
?>
P.S. some of it's code I nabbed from others. Thanks in advance.
Normally I would just use basic PHP and MySQL and some simple CSS to style. However I like the look and feel of the Bootstrap framework and would like to incorporate it into my PHP, but am a relative newbie of where to begin. I would like to start with a simple hands-on example.
Using the code below, which is a simple login script using PHP and MySQL, which changes would I need to make in order to use Bootstrap.?
I have already downloaded the Bootstrap files..
<?php
$connect = mysqli_connect("db location","username","password", "forks") or die(mysql_error());
if(isset($_COOKIE['ID_your_site'])){ //if there is, it logs you in and directes you to the members page
$username = $_COOKIE['ID_site'];
$pass = $_COOKIE['Key_site'];
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysqli_fetch_array( $check )){
if ($pass != $info['password']){}
else{
header("Location: login.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) {
// makes sure they filled it in
if(!$_POST['username']){
die('You did not fill in a username.');
}
if(!$_POST['pass']){
die('You did not fill in a password.');
}
// checks it against the database
if (!get_magic_quotes_gpc()){
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysqli_query($conect, "SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysqli_num_rows($check);
if ($check2 == 0){
die('That user does not exist in our database.<br /><br />If you think this is wrong try again.');
}
while($info = mysqli_fetch_array( $check )){
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);
//gives error if the password is wrong
if ($_POST['pass'] != $info['password']){
die('Incorrect password, please try again.');
}
else{ // if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie(ID_your_site, $_POST['username'], $hour);
setcookie(Key_your_site, $_POST['pass'], $hour);
//then redirect them to the members area
header("Location: members.php");
}
}
}
else{
// if they are not logged in
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="pass" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
<?php
}
?>
Any help would be appreciated.
Appart from the security problems inside your script you can check out: https://getbootstrap.com/examples/signin/
if you take a look at the source you'll see the familiar < form >
source:
<!-- here your php code -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Signin Template for Bootstrap</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin" action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" name="username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="pass" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</body>
</html>
I'm using PHP and HTML for a user login, it works fine, it sends me error message when there are empty fields or when I enter a wrong password, but it fails when i want to re-direct me to the file if the 'username' and 'password' are properly admitted. Any ideas?
my PHP:
<?php
session_start();
?>
<?php require_once("../includes/connection.php"); ?>
<?php include("../includes/header.php"); ?>
<?php
if(isset($_SESSION["session_username"])){
// echo "Session is set"; // for testing purposes
header("Location:intropage.php");
}
if(isset($_POST["login"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$query =mysql_query("SELECT * FROM admin_list WHERE username='".$username."' AND password='".$password."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($username == $dbusername && $password == $dbpassword)
{
$_SESSION['session_username']=$username;
/* Redirect browser */
header("Location:intropage.php");
}
} else {
$message = "Nombre de usuario ó contraseña invalida!";
}
} else {
$message = "Todos los campos son requeridos!";
}
}
?>
HTML
<div class="container mlogin">
<div id="login">
<h1>Logueo</h1>
<form name="loginform" id="loginform" action="" method="POST">
<p>
<label for="user_login">Nombre De Usuario<br />
<input type="text" name="username" id="username" class="input" value="" size="20" /></label>
</p>
<p>
<label for="user_pass">Contraseña<br />
<input type="password" name="password" id="password" class="input" value="" size="20" /></label>
</p>
<p class="submit">
<input type="submit" name="login" class="button" value="Entrar" />
</p>
<p class="regtext">No estas registrado? <a href="register.php" >Registrate Aquí</a>!</p>
</form>
</div>
</div>
PHP empty field Error Message
<?php if (!empty($message)) {echo "<p class=\"error\">" . "MESSAGE: ". $message . "</p>";} ?>
I think it may be a string literals issue which is causing the mysql query to fail.
Try changing:
$query =mysql_query("SELECT * FROM admin_list WHERE username='".$username."' AND password='".$password."'");
To this instead:
$query =mysql_query("SELECT * FROM admin_list WHERE username='$username' AND password='$password'");
Ok I am trying to create a simple login here but my login code as well as the intropage wont work properly. Tried to tweak the code for SESSION but find no luck.
Here's the code for my login.php:
<?php require_once("includes/connection.php"); ?>
<?php include("includes/header.php"); ?>
<?php
if(isset($_POST["login"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$query=mysql_query("SELECT * FROM usertbl WHERE username='".$username."' AND password='".$password."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($username == $dbusername && $password == $dbpassword)
{
session_start();
$_SESSION['session_username']=$username;
/* Redirect browser */
header("Location: intropage.php");
}
} else {
$message = "Invalid username or password!";
}
} else {
$message = "All fields are required!";
}
}
?>
<div class="container mlogin">
<div id="login">
<h1>LOGIN</h1>
<form name="loginform" id="loginform" action="" method="POST">
<p>
<label for="user_login">Username<br />
<input type="text" name="username" id="username" class="input" value="" size="20" /></label>
</p>
<p>
<label for="user_pass">Password<br />
<input type="password" name="password" id="password" class="input" value="" size="20" /></label>
</p>
<p class="submit">
<input type="submit" name="login" class="button" value="Log In" />
</p>
<p class="regtext">No account yet? <a href="register.php" >Register Here</a>!</p>
</form>
</div>
</div>
<?php include("includes/footer.php"); ?>
<?php if (!empty($message)) {echo "<p class=\"error\">" . "MESSAGE: ". $message . "</p>";} ?>
Then for here's the code for my intropage.php where in I redirect the page.
<?php
session_start();
if(!isset($_SESSION["session_username"])){
header("location:login.php");
} else {
?>
<?php include("includes/header.php"); ?>
<h2>Welcome, <?php echo $_SESSION['session_username'];?>! </h2>
<p>Logout Here!</p>
<?php
}
?>
Any help please? Just wanna make this work or if anything you can tweak so that I can find where I made a mistake. A big thanks!
You need to check if the session name is set inside all pages using if(isset($_SESSION["session_username"]))
login.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
?>
<?php require_once("includes/connection.php"); ?>
<?php include("includes/header.php"); ?>
<?php
if(isset($_SESSION["session_username"])){
// echo "Session is set"; // for testing purposes
header("Location: intropage.php");
}
else{
echo "You are not logged in.";
}
if(isset($_POST["login"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$query =mysql_query("SELECT * FROM usertbl WHERE username='".$username."' AND password='".$password."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($username == $dbusername && $password == $dbpassword)
{
// old placement
// session_start();
$_SESSION['session_username']=$username;
/* Redirect browser */
header("Location: intropage.php");
}
} else {
// $message = "Invalid username or password!";
echo "Invalid username or password!";
}
} else {
$message = "All fields are required!";
}
}
?>
<div class="container mlogin">
<div id="login">
<h1>LOGIN</h1>
<form name="loginform" id="loginform" action="" method="POST">
<p>
<label for="user_login">Username<br />
<input type="text" name="username" id="username" class="input" value="" size="20" /></label>
</p>
<p>
<label for="user_pass">Password<br />
<input type="password" name="password" id="password" class="input" value="" size="20" /></label>
</p>
<p class="submit">
<input type="submit" name="login" class="button" value="Log In" />
</p>
<p class="regtext">No account yet? <a href="register.php" >Register Here</a>!</p>
</form>
</div>
</div>
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Passwords
I noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
<?php
session_start();
require_once("includes/connection.php");
include("includes/header.php");
$message = '';
if(isset($_REQUEST["login"])) {
if((isset($_POST['username']) && strlen(trim($_POST['username'])) > 0) && (isset($_POST['password']) && strlen(trim($_POST['password'])) > 0)) {
$username = filter_var($_POST['username'],FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'],FILTER_SANITIZE_STRING);
$query = mysql_query("SELECT * FROM usertbl WHERE username='".$username."' AND password='".$password."' LIMIT 1");
if(mysql_num_rows($query) == 1) {
$row = mysql_fetch_assoc($query));
$_SESSION['session_username'] = $row['username'];
/* Redirect browser */
header("Location: intropage.php");
} else {
$message = "Invalid username or password!";
}
} else {
$message = "All fields are required!";
}
}
?>
<div class="container mlogin">
<div id="login">
<h1>LOGIN</h1>
<form name="loginform" id="loginform" action="" method="POST">
<p>
<label for="user_login">Username<br />
<input type="text" name="username" id="username" class="input" value="" size="20" />
</label>
</p>
<p>
<label for="user_pass">Password<br />
<input type="password" name="password" id="password" class="input" value="" size="20" />
</label>
</p>
<p class="submit">
<input type="submit" name="login" class="button" value="Log In" />
</p>
<p class="regtext">No account yet? <a href="register.php" >Register Here</a>!</p>
</form>
</div>
</div>
<?php
include("includes/footer.php");
if (!empty($message)) {
echo "<p class=\"error\">" . "MESSAGE: ". $message . "</p>";
}
?>
That won't do it, session_start needs to be at the top of the file to work properly. So either include it at the beginning of the file "includes/header.php" (which you are including in your login page) or in some other include file which you will be using in all of your pages.
Put your session_start() into your top of the page.
i have just commented your code. and its worked for me. Just copy and run this code directly.
<?php session_start();
//require_once("includes/connection.php"); ?>
<?php //include("includes/header.php"); ?>
<?php
if(isset($_POST["login"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$username=$_POST['username'];
$password=$_POST['password'];
/* $query=mysql_query("SELECT * FROM usertbl WHERE username='".$username."' AND password='".$password."'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['username'];
$dbpassword=$row['password'];
}
if($username == $dbusername && $password == $dbpassword)
{*/
$_SESSION['session_username']=$username;
print_r($_SESSION);
/* Redirect browser */
/* header("Location: intropage.php");
}
} else {
$message = "Invalid username or password!";
}
*/
} else {
$message = "All fields are required!";
}
}
?>
<div class="container mlogin">
<div id="login">
<h1>LOGIN</h1>
<form name="loginform" id="loginform" action="" method="POST">
<p>
<label for="user_login">Username<br />
<input type="text" name="username" id="username" class="input" value="" size="20" /></label>
</p>
<p>
<label for="user_pass">Password<br />
<input type="password" name="password" id="password" class="input" value="" size="20" /></label>
</p>
<p class="submit">
<input type="submit" name="login" class="button" value="Log In" />
</p>
<p class="regtext">No account yet? <a href="register.php" >Register Here</a>!</p>
</form>
</div>
</div>
<?php include("includes/footer.php"); ?>
<?php if (!empty($message)) {echo "<p class=\"error\">" . "MESSAGE: ". $message . "</p>";} ?>
You are unnecessarily checking session username in intropage.php
you should remove the code
if(!isset($_SESSION["session_username"])){
header("location:login.php");
From intro file and start session only once and it should be in header file's first line.