-2

Im trying to save my username to the SESSION variable using a login system however it doesn't save.

I tried printing the session variable straight away in the same page and that works however when i go to another page, it won't save.

I'm very new this stuff so im sorry if it's something obvious :)

Any help will be much appreciated :)

PHP CODE 1:

$app->post('/api/customer/login/{Username}/{PassW}', function(Request $request, Response $response){
    $Username = $request->getParam('Username');
    $PassW = $request->getParam('PassW');

    $PassW = md5($PassW);//FIND NEW WAY OF HASHING AS MD5 IS DEPRECIATED
    $sql = "SELECT * FROM login WHERE Username= '$Username' AND PassW='$PassW' LIMIT 1";

    try{
        $db = new db();
        $db = $db->connect();

        $stmt = $db->query($sql);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if(count($result) == 1){
        session_start();      
        $_SESSION['Username'] = $Username;

       echo "<script type='text/javascript'>alert('Correct!');
       window.location='http://localhost/testing/dashboard.php';
       </script>";
        exit();

PHP CODE 2 (The next page):

This page is simply a HTML page with other stuff but has the below PHP code in its body to test if its saved the variable.

<?php
        session_start(); 
        print_r($_SESSION);
  ?>
early237
  • 25
  • 1
  • 7

2 Answers2

0

This code is missing the session_start(): PHP CODE 2 (The next page)

It should have been:

<?php
session_start();
print_r($_SESSION);
?>
rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38
0

whenever you use session on the page so you must start the session on that page so your code on code 2 page should be like this

<?php session_start(); print_r($_SESSION); ?>

also, add the same line on a login page

session_start();

if everything seems fine to you then try to remove the cache from your browser as you are using javascript to redirect the page and there might be a chance that browser is loading the page from cache.

Noman
  • 1
  • 3