0

first at all sorry for my bad English. I was a student for Programming and now I run into some Session problems. I know if you go through my code it's open for SQL Injection or some types of Cyber attack because I just learn to code in PHP. So here my problem

I have some problems when initializing my Session from Log In page. Here the code for login

LOGIN

<?php
include 'api.php';
session_start(); 
$msg = "";

if (isset($_POST['login'])) {
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $pswd = mysqli_real_escape_string($con, $_POST['pswd']);

    $SQL = "SELECT * FROM member WHERE email = '$email'";
    $QuerySQL = mysqli_query($con, $SQL);
    $FetchingData = mysqli_fetch_array($QuerySQL);
    $VerifyingUserPswd = password_verify($pswd, $FetchingData['password']);

    if (mysqli_num_rows($QuerySQL)) {
        if ($VerifyingUserPswd == true) {
            $email = $_SESSION['email'];
            header("Location: index-session.php");
            exit();
        } else {
            $msg = "Your credentials are inccorect !";
        }
        } else {
            $msg = "Login Attempt Failed! Try again";
        }
        }
 ?>

and this is where i wanted to echo out the session name

INDEX SESSION

<?php
session_start();
$email = $_SESSION['email']; 
include 'api.php';

$SessionInit = mysqli_query($con, "SELECT * FROM member WHERE email = '$email'");
$PaparSession = mysqli_fetch_array($SessionInit);
?>

Thank you in advance for your help. If there's any comments don't hesitate to leave it. I am a newbie. Much love from Malaysia

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
FARISKMRDN
  • 23
  • 5
  • You are not assigning the session variable, it's backwards: `if ($VerifyingUserPswd == true) { $_SESSION['email'] = $email;` – msg Apr 25 '20 at 03:46
  • You shouldn't be manipulating passwords in any way. `password_hash()` takes this into account and you would probably be doing more harm than good. – Funk Forty Niner Apr 25 '20 at 03:53
  • You should use a prepared statement for everything. Don't leave yourself open to SQL injection. – Funk Forty Niner Apr 25 '20 at 03:54

1 Answers1

0

Session start should always be at the very top of every page.

Change your code from

<?php
include 'api.php';
session_start(); 
$msg = "";

to

<?php
session_start();
include 'api.php'; 
$msg = "";

Also, note that you cannot initialize session twice in one page/file.

other point to look into, when you assign value into session it should be like this:

$_SESSION['email'] = $emailDataFromSomewhere;

To display the value you have to echo like this

echo $_SESSION['email']

To validation if your session initialized or your assigned value is as per desire, use the print_r() function to see all session data

print_r($_SESSION)
Gabriel
  • 970
  • 7
  • 20