Handling PHP sessions in MVC architecture - php

I was trying to code a login system in a MVC architecture, of course, handling sessions but I realized that I'm not sure if my idea is properly formulated.
I'm going to show you the code writing the pretension of this.
My view:
<?php
session_start();
session_destroy();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="../css/backend.css">
<script src="../js/admlog.js"></script>
<title>Access to administration panel</title>
</head>
<body>
<form method="post" action="../controller/admlog.php">
<h2><span class="entypo-login"></span> Login</h2>
<button class="submit"><span class="entypo-lock"></span></button>
<span class="entypo-user inputUserIcon"></span>
<input type="text" name="user" class="user" placeholder="username"/>
<span class="entypo-key inputPassIcon"></span>
<input type="password" name="password" class="pass"placeholder="password"/>
</form>
</body>
</html>
Nothing to say here, basic html form.
Controller of the login page:
<?php
//controller!
require "../model/backend.php";
$username = $_POST['user'];
$password = $_POST['password'];
$dbcom = new dbInteraction;
$dbcom->admlog($username, $password);
$dbcom->conclose();
?>
Very simple too, what I do here is take the values of my inputs and send them to the backend.php, where petition will be handled.
Backend function where the login is handled:
public function admlog($username, $password){
$this->username = $username;
$this->password = $password;
//$this->pdo = $pdo;
//$adm = 1;
$myquery = 'SELECT username FROM users WHERE username = :username AND password = :password'; //check admin flag
$stmt = $this->pdo->prepare($myquery);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
//$stmt->bindParam(':isadmin', $adm, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (count($result) > 0){
session_start();
$_SESSION['login'] = $result['username'];
header('Location: ../view/backMain.php');
}else{
session_start();
$_SESSION['login'] = "";
//header('Location: ../manage.php');
echo 'Incorrect user or password';
}
}
All the code works without problem, I mean, the select is performed correctly and user can log in the system.
The problem is the way that I handle the sessions. When user is found in the db, I coded:
session_start();
$_SESSION['login'] = $result['username'];
header('Location: ../view/backMain.php');
So it should create a new session, no? Well, the target page (backMain.php) have a restriction, restriction that check if there is a settled session or not.
<?php
if(!isset($_SESSION['login']))
{
header("Location: http://google.es");
}
?>
I have to suppose that it is, but when I try to access I see that no.
How is handled the session in this kind of architecture? For me, the code make sense but the result is obvious that not.
I'm being redirected to google.es because the condition does not find any settled session even when I set that session in the backend.
I have to be missing something.
Thanks

You are right, the problem is the way how you handle the session.
Seems, that you redirect user to another page before he gets session Cookie. Check with Chrome/FF developer console, if you receive session cookie properly.
If no, I'd recommend to make redirect on meta/js level instead of HTTP headers, it will make user receive and write cookies before being processed to another page.

Related

PHP secure login form with SQLSRV

It's "day two" of my php experiments, and I'm trying to put together a secure login form with php / MS SQL (sqlsrv).
Looked at a number of examples, and they all pretty much reference mysql, which doesn't really apply to my needs.
Also, just as an fyi (before someone says, why aren't you using PDO), I've had zero luck getting PDO to run in my local environment, (php 7.2) so I've been sticking to sqlsrv type of commands.
Here's what I've attempted to create so far:
data.php page
class getUsers {
function get_all_users() {
global $conn;
$dbUsers = [];
$sql = "SELECT user_name, user_password FROM users";
$stmt = sqlsrv_query($conn, $sql) or die( print_r(sqlsrv_errors(), true));
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
array_push($dbUsers, $row);
}
return $dbUsers;
sqlsrv_free_stmt($stmt);
}
}
First thing right off the bat, I know is not an optimal way to do this, I should probably just be retrieving one record, not all records, but I'm using the method that I gleamed from another SO post.
login.php page
<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
include_once("../includes/connection.php");
include_once("../includes/data.php");
$udata = new getUsers();
$udatas = $udata->get_all_users();
$userlist = array_column($udatas, null, 'user_name');
if(isset($_SESSION['logged_in'])) {
//go to logged in page.
echo "session state = logged in";
} else {
//display login
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required';
} else if (isset($userlist[$username], $userlist[$password])) {
$_SESSION['username'] = $username;
echo "logged in, should only display when logged in.";
//header('Location: cp-logged-in.php');
} else {
$error = "Invalid user information";
}
}
}
?>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link rel="stylesheet" href="../css/styles.css" />
</head>
<body>
<div class="grid-header">
<?php include("../includes/header.php"); ?>
</div>
<div class="grid-login">
<?php include("cp-login.php") ?>
</div>
</body>
</html>
Lots of issues with this:
1) Since I don't have the checking the input against the database part correct, it won't actually log in.
2) There's zero security implimented on this, and from what I've gleaned on SO, at the very least, I should be doing some sort of hashtag / salting of pw's, and perhaps some other stuff to protect against SQL injections.
So to the first issue, I'm quite certain there's a more efficient way to check the un/pw against the database. Ideally, I'd like to keep the login function in a separate file, (to keep it cleaner) but perhaps that would make things more difficult? (as it would require passing the username/password variables back and forth between the two php pages).
And to the second issue, in looking at a couple of security articles, would blowfish or php's native password_hash() be the way to go? As I understand it, md5 isn't all that secure.
In thinking about future improvements, this may be a bigger question, but would a smarter approach be to not store passwords in the database at all, and somehow include a random password generator type of function? Maybe that's too much to tackle right off the bat?
thanks! :)

PHP/MySQL Login Page Not Redirecting

I'm trying to create a login page that queries the database to check if the username and password are valid and allowing access to the following pages using sessions. Currently, I'm just using XAMPP to test the login. This is the following code I have in a PHP page.
<?php
include("config.php");
session_start();
// Check for POST method
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_POST['password']);
$password = mysqli_real_escape_string($con, $password);
//Search database for username and password
$stmt = $con->prepare("SELECT * FROM users
WHERE username = ? LIMIT 1"); // Prepared statement
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_object();
if(password_verify($_POST['password'], $user->password)) {
echo("working");
$_SESSION['loggedin'] = true;
$_SESSION['user'] = $user->username;
header("Location: index.php");
} else {
echo("no user");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
<form id="loginForm" method="post" action="">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
I added an echo statement just to see if it would output "no user" for both user/passwords sets in the database and not in it. They both display "no user" so I don't think I'm searching the database correctly. I'm sort of new to PHP and I used this code.
UPDATE
Thanks to comments, fixed passwords so that they were hashed.
When it still was not working:
Set password datatype in database to VARCHAR(60), recommended VARCHAR(255)
I realized it was because I had password datatype set to VARCHAR(40). Since I was using bycrypt to hash, it is a 60 character string. I set my password to the recommended VARCHAR(255) in case I decided to use PASSWORD_DEFAULT in the future. I failed to realize this is all mentioned in password_hash() documentation when initially creating the database and fields.
Added session_start() to all pages referencing $_SESSION[]
Echoed var_dump() to display the result of password_verify() that returned true when I entered the correct information, however, the page stil kept redirecting me to login. In the PHP I was redirecting to I had this section of code:
<?php
if($_SESSION['loggedin'] == false) {
header("Location: login.php");
} else {
}
?>
I forgot to put session_start(); in the PHP page so it kept redirecting me to the login.

My session is not passing to the different page

The session is not passing and I want to restrict the users from viewing the login page while they are logged in for that I tried many things, but it didn't work:
My login page
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
session_start();
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title>Login page</title>
<link href="style.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="frm">
<form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
<h1> Login</h1>
<p>
<label>Username</label>
<input type="text" id="username" name="username" />
</p>
<p>
<label>password</label>
<input type="password" id="password" name="password"/>
</p>
<p>
<input type="submit" id="btn" value="login" name="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
</p>
<p>
Not yet a member Register here
</form>
</div>
</body>
</html>
My home page
<?php
session_start();
if ($_SESSION['nID'] == false) {
header("Location: login.php");
die();
} elseif ($_SESSION['nID'] == true) {
header("Location: Home.php");
die();
} else {
echo"cant connect";
}
?>
<html>
<head>
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<ul class="nav nav-pills">
<li role="presentation" class="active">Home</li>
<li role="presentation">Information</li>
<li>Logout
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</body>
</html>
The session is not passing and it doesn't prevent the user from viewing the homepage while they aren't logged in.
I have tried many different things, but nothing seems to work.
Some thoughts on this question:
1) Stop using extract(). You simply don't need it.
Warning Do not use extract() on untrusted data, like user input (i.e. $_POST, $_FILES, etc.). If you do, for example if you want to temporarily run old code that relied on register_globals, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini.
From the Manual.
2) As noted in another answer Your SQL query is far too vague; you're returning the first answer of a search of the whole DB rather than searching for any specific criteria.
SELECT password FROM users WHERE username=username_here LIMIT 1
And then take this row and compare with the given password:
if($password === $row['password'])
3) Your password system used on MySQL / PHP is NOT GOOD ENOUGH. Stop using md5() and employ password_hash and password_verify PHP functions. Please read how to do it properly and this comment.
4) Every time you use header("Location: ...") to redirect the user it is highly recommended you add a die or exit command immediately afterwards in order to cease the code execution on the current page. For example:
header("Location: this_page_will_never_load.php");
header("Location: this_page_will_always_load_instead.php");
5) require and include functions do not require brackets.
NOTE
Re the numerous answers here referencing session_start(); if session_start() is called after output is sent to the browser, then there will be an error notice generated. OP has not reported an error notice even with:
error_reporting(E_ALL);
ini_set('display_errors',1);
So session_start() placement in the code is not an issue in this specific situation.
However:It is best practise to put your session_start() as early as possible in your code and before such debug things as var_dump which would cause session_start not to load becase var_dump has already thrown data out to the browser.
Finally, an answer to your problem:
I want to restrict the users from viewing the login page while they are logged in for that I tried many things but it didn't work:
Your code in login.php:
if(isset($_POST['login'])){
///session stuff etc.
}
The above code on your login.php page will only execute if the page is being given POSTed data. What you have is that once someone is logged in correctly and they then return to the login.php page, they are not resubmitting the POSTed data so this code block is simply not running.
Because this code block contains all your $_SESSION references this is why it looks like $_SESSION is not running.
Instead you want to do this (simplified) in login.php:
session_start();
if(isset($_POST['login'])){
// setup session values,
// once POSTed login data is checked and authorised in the database
$_SESSION['nID'] = true;
}
elseif ($_SESSION['nID'] === true){
// is already logged in so redirect to the index page.
header("Location: index.php");
exit;
}
else {
// this fires if no POSTed data is sent and no valid
// session is found.
}
Try this condition in your home.php file:
session_start();
if (!isset($_SESSION['nID']) || empty($_SESSION['nId'])) {
header("Location: login.php");
die();
}
You try this code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('connect.php');
extract($_POST);
$result = mysqli_query($link, "SELECT * FROM users ");
$row = mysqli_fetch_assoc($result);
//var_dump($row['username']);
//var_dump($row['password']);
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
if ($username == $row['username'] && $password == $row['password']){
//session_start(); removed it
$_SESSION['nID'] = true;
//echo"Login";
header('Location: home.php');
} else {
echo"Login failed";
}
}
?>
On every page, you need to add session_start() in the page heading.
First: First of all, your query is wrong. You're always checking the value with the first user in the table. You need to a query with the where clause.
SELECT * FROM users WHERE username=username_here AND password=hash_password_here
Second: Your If statement should be like the following.
<?php
session_start();
if (!isset($_SESSION['nID'])) {
header("Location: login.php");
die();
}
?>
Third: Try to use prepared statements to avoid an SQL injection.
$stmt = $link->prepare("SELECT * FROM users where username=? and password=?");
$stmt->bind_param('ss', $username, md5($password));
$stmt->execute();
$get_result = $stmt->get_result();
$row_count = $get_result->num_rows;
if ($row_count > 0) {
session_start();
$_SESSION['nID'] = true;
header('Location: home.php');
die();
}
else {
echo"Login failed";
}
4th: Don't use Md5() for passwords. Try to use password_hash() and password_verify(). Reference link.
While registrating, use password_hash() to hash the password and store it in the database and while logging in, use password_verify() to verify the password like this. Reference link.
You have to call the session_start() function in the file where you are trying to use a session variable.
You need to add session_start(); on every page to get the session variables.

PHP sessions don't seem to work after login! Wamp - 4 sessions created / login?

this is my first question asked on SO so please excuse me if I go against some of the post etiquette - I'll do my best to explain my problem clearly, and I have searched for previous questions but none match my issue as far as I'm aware.
Background: Running on WAMP server 2.4 with Apache 2.4.4 and PHP 5.4.12 - Please let me know if you need any specifics.
I've been working on a new webapp project and seem to have run into a problem while trying to get PHP sessions working. My login process works as follows;
Once a user submits details and they are crosschecked with those stored in a Mysql database, a session is created and they are redirected to a temporary protected page.
The temporary page checks that the user has a valid session and if so displays a welcome message.
If the user does not have a valid session then they receive an error.
PROBLEM: Whenever I login (successfully might I add) I'm redirected and receive the error message "You are not authorized to access this page."
Here is the code for the login process (process_login.php):
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
//Form data error handling.
if ($email == "" || $password == ""){
echo "login failed";
exit();
} else {
//DB stuff.
$stmt = $mysqli->prepare("SELECT id, username, password, salt
FROM members
WHERE email = ?
LIMIT 1");
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
header('Location: ../protected_page.php');
} else {
// Login failed
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
header('Location: ../index.php?error=1');
}
}
}
Here is the code for my session_start function (sec_session_start() )
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = true;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
Here is my temporary test code (protected_page.php);
-note I'm new to this and seem to be having trouble posting my html.
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions.php';
sec_session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Secure Login: Protected Page</title>
<link rel="stylesheet" href="styles/main.css" />
</head>
<body>
<?php if (login_check($mysqli) == true) {?>
<p>Welcome <?php echo htmlentities($_SESSION['username']); ?>!</p>
<p>
This is an example protected page. To access this page, users
must be logged in. At some stage, we'll also check the role of
the user, so pages will be able to determine the type of user
authorised to access the page.
</p>
<p>Return to login page</p>
<?php } else {?>
<p>
<span class="error">You are not authorized to access this page.</span> Please login.
</p>
<?php }?>
</body>
</html>
As far as any other specifics that might make a difference - the login form is loaded through a sidebar and sends
Any help is much appreciated! I'm semi new to this stuff and I've spent 5+ hours fiddling and can't seem to figure it out. Login works, the session code (as far as I'm aware) makes sense and SHOULD be working - ugh halp me.
ADDED NOTE: I've checked my C:/wamp/etc/ file and cleared the sessions, just by logging in apparently 4 session files are created? I think this must have something to do with it.
http://puu.sh/71Lhm.png
Okay I ended up solving my own problem, but I'm going to leave the answer here incase anybody has a similar issue with WAMP. (I think it's because I was using WAMP)
In my custom session function (sec_session_start) I had the option for $secure enabled. Though I believe this is only functional when you have it live on a production server using HTTPS. (Not on my local machine.) My reasoning could be wrong, but I changed the value of
$secure = true;
to
$secure = false;
And it worked! Great success.

PHP Login & MySql Query

I'm having some trouble with my login feature. I've been searching for hours and I could'nt find any problem. I hope you guys will help me.
I want to get users' login and check if it exists in my DB. Problem is it keeps returning me : "Password was probably incorrect!".
I tried an "echo ($count)", it doesn't return anything. Same thing for "echo($result)".
I'm pretty lost right, I can't understand why this doesn't work...
PS : I'm french so you might see some french words.
Here's my login form :
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Applications</title>
<!--Chargement des feuilles de style-->
<link rel="stylesheet" type="text/css" href="./css/style.css" />
<link rel="stylesheet" type="text/css" href="./css/styleLogin.css" />
<script src="./js/login/modernizr.custom.63321.js"></script>
</head>
<body>
<div class="container">
<header></header>
<section class="main">
<form class="form-2" id="loginForm" action="./controller/checkLogin.php" method="post">
<h1><span class="log-in">Se connecter</span></h1>
<p class="float">
<label for="loginLabel"><i class="icon-user"></i>Nom d'utilisateur</label>
<input type="text" name="login" id="login">
</p>
<p class="float">
<label for="passwordLabel"><i class="icon-lock"></i>Mot de passe</label>
<input type="password" name="password" class="showpassword" id="password">
</p>
<p class="clearfix">
<input type="submit" name="submit" value="Se connecter">
<input type="button" name="submitVisit" value="Accès utilisateur">
</p>
</form>​​
</section>
</div>
</body>
And here's my checkLogin.php :
<?php
session_start();
try {
$bdd = new PDO('mysql:host=localhost;dbname=stage','root','');
}
catch (Exception $e){ //en cas d'erreur de connexion, afficher le message
die('Erreur : '.$e->getMessage());
}
if(isset($_POST['submit'])){
// username and password sent from form
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = 'admin'";
$result = mysql_query($qry);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
if($count == 0){
die("Password was probably incorrect!");
}
// If result matched $myusername and $mypassword, table row must be 1 row
elseif($count == 1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['login'] = $login;
header("location: ./login_success.php");
}
else {
echo "Wrong Username or Password";
}
}
mysql_close($bdd);
?>
I want to log in with this couple : admin/admin.
Thank you in advance.
There are a few problems with your script.
First off, you start by using PDO to connect to the database, then you use mysql_* functions (which are deprecated, stick to PDO !!!). Plus, you are not properly escaping your data, and your code is potentially vulnerable to SQL injection.
Secondly, the query you are using is ... not good.
// this is not checking for either the user input data !!!
$qry = "SELECT login FROM users WHERE login = 'admin'";
Your verification code should be something like this:
$ps = $bdd->prepare("SELECT COUNT(*) FROM users WHERE login = :login AND pass = :password");
$params = array("login" => $_POST['login'], "password" => $_POST['password']);
$ps->execute($params);
$status = (bool) $ps->fetchColumn(0);
if ($status) {
// login successful
} else {
// login failed
}
Read up on PDO and prepared statements (they automatically escape your data, so you don't have to).
Note:
If you don't use prepared statements in future code, remember to always escape input from users and pretty much any other source of information.
1) You are mixing mysql and PDO which is a disaster. Mysql_ interface is deprecated use mysqli or pdo please...
2)
"SELECT login FROM users WHERE login = 'admin'";
finds only users with login admin... So you have to
"SELECT login FROM users WHERE login = '$login'";
3) $_POST variables are not safe. Users can inject malicious code...
For instance If you use mysqli then
$login = mysqli_real_escape_string($_POST['login']);
To sanitize login entry and do the same for password too.
since everybody gave advice on general issues i cut to the chase
change:
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = 'admin'";
assuming the password ist saved to a database field named "passwort" to:
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = '".mysql_real_escape_string($login)."' and password= '".mysql_real_escape_string($password)."'";
mysql_real_escape_string keeps you from beeing hacked and the database query now uses the values from the post ...
The problem is, that you are mixing mysql_* functions and PDO.. the code should looks like this:
Note the prepare function which binds parameters to your SQL query - it prevents SQL injections.
session_start();
try {
$pdo = new PDO('mysql:host=localhost;dbname=stage','root','');
}
catch (Exception $e){ //en cas d'erreur de connexion, afficher le message
die('Erreur : '.$e->getMessage());
}
if(isset($_POST['submit'])){
// username and password sent from form
$login = $_POST['login'];
$pass = $_POST['password'];
$sql = "SELECT login FROM users WHERE login = :login AND password = :password";
$params = array( 'login' => $login, 'password' => $pass );
$sqlprep = $pdo->prepare($sql);
if($sqlprep->execute($params)) {
$count = $sqlprep->rowCount();
if($count != 1){
die("Incorrect login!");
} else {
$_SESSION['login'] = $login;
header("location: ./login_success.php");
}
}
}

Categories