I am having difficulty with header redirecting me to index.html from my login page. I'm not sure header is even the way to go but it is all that I could find on page redirection.
This code is just a simple login page which checks the username and password against a MySQL database.
The problem I am having is inside the if statement:
if(mysqli_num_rows($res) == 1){
header("Location: index.php");
exit();
}
full code for login.php:
<?php
//Connects to MySQL database using sql_connect.php
require "sql_connect.php";
?>
<?php
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM login_test WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysqli_query($connection, $sql);
if(mysqli_num_rows($res) == 1){
header("Location: index.php");
exit();
} else {
echo "Invalid login information!";
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link rel="stylesheet" href="../style.css">
</head>
<body>
<form name="login" method="post" action="login.php">
<h3>Login</h3>
<p>Username: </p><input type="text"name="username">
<p>Password: </p><input type="password" name="password">
<br/>
<input type="submit"name="submit"value="log in">
</form>
<script src="../script.js" type="text/javascript"></script>
</body>
</html>
While I'm sure the rest of my code is far from perfect I am just really looking at how to redirect to a new page if the user is authenticated in the database? Is there a better option than header in my case or am I just implementing it wrong?
I used php header before, but have bad experience.
Normally I use javascript
echo '<script type="text/javascript">' . "\n";
if(isset($from))
{
echo 'window.location="..";';
}
else
{
echo 'window.location="..";';
}
echo '</script>';
header() function didn't work well may cause by your "mysqli_num_rows($res) == 1" result is false.
And There is no space between "Location" and your "index.php" like:
header("Location:index.php");
Or you can create a php function and use JavaScript, its a good way to avoid that.
function redirect($url, $prompt) {
$js_string = "<script>";
$js_string .= $prompt ? "alert('". $prompt ."');" : "";
$js_string .= "window.location = '{$url}';";
$js_string .= "</script>";
exit($js_string);
}
Related
I'm trying to create a login page using Mysql, I checked DB connection and such everything works as intended. However I've created the loginprocess now but when submitting the login information it just links me to the loginprocess.php and nothing else happens. I tried searching for a while but everyone's issue what that they didn't give the username input a name.
Here's my code for the index.php (login screen)
<?php
include_once 'header.php';
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<header>
</header>
<section>
<div class="nav-login">
<form action="includes/loginprocess.php" method="POST">
<input class="txtbox" type="text" name="username" placeholder="Username"><br>
<input class="txtbox" type="password" name="userpass" placeholder="Password"><br>
<button class="good-looking" type="submit" name="submit">Login</button>
</form>
</div>
</section>
</body>
</html>
and this is the loginprocess.php (it's in includes folder)
<?php
session_start();
if(isset($_POST['submit'])) {
include 'dbconn.php';
$username = mysqli_real_escape_string($conn, $_POST['username']);
$userpass = mysqli_real_escape_string($conn, $_POST['userpass']);
if (empty($username) || empty($userpass)) {
header("Location: ../index.php?login=empty");
exit();
} else {
$sql = "SELECT * FROM samokslogin WHERE samokslogin_username='$username'";
$result = mysqli_query($conn, $sql);
$reultCheck = mysqli_num_rows($result);
if($resultCheck < 1) {
header("Location: ../index.php?login=error");
exit();
} else {
if($row = mysqli_fetch_assoc($result)) {
$LoginCheck = password_verify($pwd, $row['samokslogin_userpass']);
if($LoginCheck == false) {
header("Location: ../index.php?login=failed");
exit();
} elseif ($LoginCheck == true) {
$_SESSION['u_id'] = $row['samokslogin_id'];
$_SESSION['u_username'] = $row['samokslogin_username'];
header("Location: ../index.php?login=success");
exit();
}
}
}
}
} else {
header("Location: ../index.php?login=failed");
exit();
}
I really did search for a long time, and re-read all my codes to make sure I've even tried using try catch to see the error but nothing came up. I hope I'm not missing something obvious..
Best regards :)
-Samo
I had made a slim mistake by forgetting the $username = mysqli_real_escape_string($conn, $_POST['username']) after checking the error logs I've now fixed it, thanks to everyone who helped me out with this one it's my first php project I wasn't sure if there were error logs at all even.
So I need to pass a variable from one php to another php page but I dont know how to do it. I got this piece of code "$realname= $row['name'];" that stores the real name of the person to display it in another page after they successfully login, but when I try to use $realname variable in the other page it wont display it. How can I make this posible??? thanks in advance
page one login.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
include 'functions.php';
if(loggedin())
{
header("Location: userarea.php");
exit();
}
if(isset($_POST['login']))
{
//get data
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
//validate
if($username&&$password)
{
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($login) == 1)
{
while($row = mysql_fetch_assoc($login))
{
$db_password = $row['password'];
if($password == $db_password)
$loginok= TRUE;
else
$loginok = FALSE;
if($loginok==TRUE)
{
$realname= $row['name'];
if($rememberme == "on")
setcookie("username", $username, time() + 7200);
else if ($rememberme == "")
$_SESSION['username'] = $username;
header("Location: userarea.php");
exit();
}
else
die("Incorrect username or password. Please try again or contact your local admin.");
}
}die("Incorrect username or password. Please try again or contact your local admin.gdfgdfgdfg");
}
else
die("Please enter a username and password.");
}
?>
<h>Welcome!</h>
<form action="login.php" method="POST">
Username:<br />
<input type="text" name="username"><p />
Password:<br />
<input type="password" name="password"><p / >
<input type="checkbox" name="rememberme"> Remember me<br />
<input type="submit" name="login" value="Log in">
</form>
</body>
</html>
Page 2 userarea.php (as you can see I declared $realname variable but I cant use it)
<html>
<body>
<?php
include 'functions.php';
if(!loggedin())
{
header("Location: login.php");
exit();
}
echo "Hello $realname";
?>
<h>Access Granted! Yeiy! </h>
Log out
</body>
</html>
This is exactly what sessions are for:
Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.
page one login.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
$_SESSION['realname'] = $row['name'];
Page 2 userarea.php
<?php session_start(); ?>
<!DOCTYPE html>
<html>
...
echo "Hello $_SESSION['realname']";
First pass $_SESSION['var_name']; on login page and then
start session_start() on the top of the userarea page and echo your session variable
echo $_SESSION['var_name'];
I have a log-in script for user login. The user information is stored in the MYSQL database. When i login for first time, it stores the information in the session and display the welcome message. But when i log-out and try to log-in again, the session array display empty although it is logged in.
Here are my codes:
reservation.php
<?php
session_start();
require_once("./includes/config_db.php");
$error1=array();
if(isset($_POST['submit'])){
if (preg_match ('%^[A-Za-z0-9]{4,8}$%', stripslashes(trim($_POST['user_id'])))) {
$e = escape_data($_POST['user_id']);
} else {
$e = FALSE;
$error1['user_id']="UserID Required!";
}
if (preg_match ('%^[A-Za-z0-9]{8,}$%', stripslashes(trim($_POST['password'])))) {
$p = escape_data($_POST['password']);
} else {
$p = FALSE;
$error1['password']="Password Required!";
}
if($e && $p){
$query="SELECT * FROM users WHERE(user_id='$e' AND password=SHA('$p')) AND active='NULL'";
$results=mysql_query($query);
if(mysql_affected_rows() == 1){
$row=mysql_fetch_array($results, MYSQL_NUM);
mysql_free_result($results);
$_SESSION['name']=$row[0];
$_SESSION['department']=$row[1];
$_SESSION['email']=$row[2];
$_SESSION['user_id']=$row[4];
$_SESSION['phone']=$row[5];
$_SESSION['pre']=$row[8];
//create second token
$tokenid=rand(10000,9999999);
$query2="UPDATE r_users SET token='$tokenid' WHERE user_id='$_SESSION[user_id]'";
$result2=mysql_query($query2);
$_SESSION['tokenid']=$tokenid;
session_regenerate_id();
mysql_close();
header("Location:local.php");
exit();
}else
{
$error1['active']="Either your Account is inactive or Email/Password is incorrect";
mysql_close();
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Reservation System</title>
<!--Link to external files-->
<link rel="stylesheet" type="text/css" href="css/reservation.css"></link>
</head>
<body class="body">
<div id="mainHeader">
<?php include('includes/ers_header.php'); ?>
</div>
<div id="content">
</div>
<div id="navigation">
<?php include('includes/ers_nav.php');?>
<h3>Member Login</h3>
<form id="login" action="reservation.php" method="post">
<?php if(!empty($error1['active'])) echo '<p><font color="red">'.$error1['active'].'</font></p>'; ?>
<label for="userid">User ID:</label>
<input type="text" name="user_id" <?php if (!empty($error1['user_id'])){ echo 'value="'.htmlentities($_POST['user_id']).'"';} ?> autofocus />
<?php if (!empty($error1['user_id'])){ echo '<p><font color="red">'.$error1['user_id'].'</font></p>';} ?>
<label for="password">Password:</label>
<input type="password" name="password" />
<?php if (!empty($error1['password'])){ echo '<p><font color="red">'.$error1['password'].'</font></p>';} ?>
<button class="submit" name="submit" type="submit">Login</button>
</form
</div>
</body>
</html>
ers_header.php:
<h1>XXXXXXXXXX</h1>
<h2>YYYYYYYYYYY</h2>
<h2>ZZZZZZZZZZZZ</h2>
<?php
require_once("./includes/config_db.php");
if(isset($_SESSION['name'])){
$sql="SELECT token FROM users WHERE(user_id='$_SESSION[user_id]')";
$result=mysql_query($sql);
if (mysql_affected_rows() == 1) { // A match was made.
$row = mysql_fetch_array ($result, MYSQL_NUM);
mysql_free_result($result);
mysql_close(); // Close the database connection.
if($_SESSION['tokenid'] == $row[0]){
echo '<p>Welcome';
echo " {$_SESSION['name']}";
$loggedin=1;
}else{
$loggedin=0;
}
}
}
if(isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'] AND $loggedin,-10)!='logout.php')){
echo' Logout';
echo'</p>';
}
?>
logout.php
<?php
session_start();
require_once("./includes/config_db.php");
if ( !isset( $_SESSION['name'] ) ) {
header("Location: reservation.php");
exit();
} else {
$_SESSION = array(); // Destroy the variables.
session_destroy(); // Destroy the session itself.
setcookie( session_name(), ", time()-300, '/', ", 0 ); // Destroy the cookie.
header("Location:reservation.php");
}
I don't know what is the problem. I have tried a lot but couldn't find it out. Please can anyone figure out my mistake.
You really should only need to unset the $_SESSION array, not destroy the session and cookie data, try removing those lines, but also:
mysql_affected_rows should be mysql_num_rows
also this line of code is incorrect:
$query2="UPDATE r_users SET token='$tokenid' WHERE user_id='$_SESSION[user_id]'";
$_SESSION[user_id] should be $_SESSION["user_id"] and you should wrap it in {}. PHP probably gives warnings about this.
and this line of code is strange:
if(isset($_SESSION['user_id']) AND (substr($_SERVER['PHP_SELF'] AND $loggedin,-10)!='logout.php')
is the $loggedin,-10 really supposed to be in substr?
I looked on http://www.phpportalen.net/wiki/index.php?page=Enkel+inloggning+med+MySql+och+sessioner to how to do a simple login.
But when i try to login now it says that the username or password is wrong. So Im guessing something is not right in my control dokument, where im checking the usernamne and password to the database.
In the exampel i looked on they have it all in the same page, so im guessing I need to change more than i thougt.
This is the code in the loginside:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="stylesheet.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
if(!isset($_SESSION["sess_user"])){
if(isset($_GET['badlogin'])){
echo "Fel användarnamn eller lösenord, försök igen!";
}
?>
<form method="post" action="check.php">
<p>User</p>
<input name="user" type="text" />
<p>Password</p>
<input name="password" type="text" />
<input name="logIn" type="submit" value="Log in" />
</form>
<?php
}
else{
header("Location: admin.php");
}
?>
</body>
</html>
And this is the code in my controlside:
<?php
session_start();
?>
<?php
function db_escape($post){
if(is_string($post)){
if(get_magic_quotes_gpc()){
$post = stripslashes($post);
}
return mysqli_real_escape_string($post);
}
foreach($post as $key => $val){
$post[$key] = db_escape($val);
}
return $post;
}
if(isset($_POST["logIn"])){
// Connect to db
$dbConn = mysqli_connect("localhost","sabe0011","lösen","sabe0011");
$dbConn->set_charset("utf8");
// Check connection
if(mysqli_connect_errno($dbConn)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$_POST = db_escape($_POST);
$checkUserSQL = mysqli_query($dbConn, "SELECT * FROM Users WHERE User ='{$_POST['user']}' AND Password ='{$_POST['password']}'");
if(mysqli_num_rows($checkUserSQL) == 0){
header("Location: login.php?badlogin=");
exit;
}
$_SESSION['sess_id'] = mysqli_store_result($checkUsersSQL, 0);
$_SESSION['sess_user'] = $_POST['user'];
header("Location: admin.php");
exit;
}
?>
Your parameters in your query should be escaped like:
$checkUserSQL = mysqli_query($dbConn, "SELECT * FROM Users WHERE User =" . $_POST['user'] . " AND Password = " . $_POST['password']);
But in term of security, you have to see at the prepared query here.
There are two cases here.
The user enters an empty input. In this case, the login page will warn the user that he has entered an empty input.
The user enters the wrong username or password. In this case, the login page will warn the user that he has entered a wrong username or password.
In both the scenarios, the input processing will be done on the server(PHP). My problem is, how do I modify the login page dynamically to show the warning messages?
I tried passing the PHP boolean value into a javascript variable in login page but after some research, I found out that you cannot mix Javascript and PHP codes. The code is below:
function error_msg()
{
<?php session_start();?>
var failed_login= <?php echo $_SESSION['failed_login'];?>;
var empty_field= <?php echo $_SESSION['empty_field'];?>;
var txt=document.getElementById("failed_login_text");
if (empty_field== 1)
{
txt.innerHTML="No empty fields allowed.";
<?php unset($_SESSION['empty_field']);?>
}
else if (failed_login== 1)
{
txt.innerHTML="Failed login. Wrong username or password.";
<?php unset($_SESSION['failed_login']);?>
}
<?php session_destroy();?>
}
Another method I used is by echoing the whole Javascript into the login.php using PHP. This PHP code is in the login page file.
<?php
session_start();
$failed_login= $_SESSION['failed_login'];
$empty_field= $_SESSION['empty_field'];
echo $_SESSION["empty_field"];
echo $_SESSION["failed_login"];
$script="<script>
var empty_field= $empty_field;
var failed_login= $failed_login;
var txt=document.getElementById(\"failed_login_text\");
txt.innerHTML= empty_field;
if (empty_field== 1)
{
txt.innerHTML=\"No empty fields allowed.\";
}
else if (failed_login== 1)
{
txt.innerHTML=\"Failed login. Wrong username or password.\";
}</script>";
echo $script;
unset($_SESSION['empty_field']);
unset($_SESSION['failed_login']);
?>
What did I do wrong?
I have written this script for dynamic login , you can use it if it serves you , and i have used jquery for validation , Hope this might help you
<?php
if (isset($_POST['user'])){
$email = $_POST['user'];
$password = $_POST['password'];
$sql = "SELECT * FROM `register` WHERE `email` = '{$email}' AND BINARY `password` = '{$password}'";
$result = mysql_query($sql);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($result);
$_SESSION['email'] = $row['email'];
$_SESSION['sno'] = $row['sno'];
header("location:some_page.php");
}
else
{
$msg ="Invalid Username / Password";
header('location:your_page_name?msg='.$msg);
}
}
else
{
$msg = "Internal Server error";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>login-user</title>
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/validity.form.js"></script>
<link rel="Stylesheet" type="text/css" href="js/jquery.validity.css" />
<link rel="stylesheet" href="js/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validity(function() {
$("#user").require().match("email");;
$("#password").require();
});
});
</script>
</head>
<body>
<div id="container">
<?php
if(isset($_REQUEST['msg']) && $_REQUEST['msg']!='')
{
echo "<div id='message'>".$_REQUEST['msg']."</div>";
}
?>
<form id="form1" name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<lable>User Name:</lable>
<input name="user" type="text" id="user" size="30" />
<lable>Password:</lable>
<input name="password" type="password" id="password" size="30" value=""/>
<input type="submit" name="Log In" id="Log In" value="Login" />
</form>
</div>
</body>
</html>