2

I'm working with the following code, that can pass the user entered value to the next page and will be used to insert in a database using SESSION. All of my code parts are working except from the SESSION. The common.php includes session_start(); Why is that ? What shoud I do?

<?php ob_start();?>

<?php 
  // First we execute our common code to connection to the database and start the session 
    require("common.php"); 

    // This variable will be used to re-display the user's username to them in the 
    // login form if they fail to enter the correct password.  It is initialized here 
    // to an empty value, which will be shown if the user has not submitted the form. 

    // This if statement checks to determine whether the login form has been submitted 
    // If it has, then the login code is run, otherwise the form is displayed 
    if(!empty($_POST)) 
    { 
        // This query retreives the user's information from the database using 
        // their username. 
       if(isset($_POST['validEmail'])) 
        {
              $query = " 
            SELECT 
                *
            FROM registered_email 
            WHERE 
                email = :validEmail 
        "; 

        }


        // The parameter values 
        $query_params = array( 
            ':validEmail' => $_POST['validEmail'] 
        ); 

        try 
        { 
            // Execute the query against the database 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        { 
            // Note: On a production website, you should not output $ex->getMessage(). 
            // It may provide an attacker with helpful information about your code. 
            die("Failed to run query");
        } 

        // This variable tells us whether the user has successfully logged in or not. 
        // We initialize it to false, assuming they have not. 
        // If we determine that they have entered the right details, then we switch it to true. 
        $login_ok = false; 

        // Retrieve the user data from the database.  If $row is false, then the username 
        // they entered is not registered. 
        $row = $stmt->fetch(); 
        if($row) 
        { 


            if($_POST['validEmail'] === $row['email']) 
            { 
                // If they do, then we flip this to true 
                $login_ok = true; 
            } 
        } 

        // If the user logged in successfully, then we send them to the private members-only page 
        // Otherwise, we display a login failed message and show the login form again 
        if($login_ok) 
        { 

            $_SESSION['sesEmail'] = $row; 

            // Redirect the user to the private members-only page. 
            if (isset($_POST['validEmail'])) {
                 echo "<script>location='http://www.some.com/Crd/next.php'</script>";

            } 

        }


        else 
        { 
            // Tell the user they failed 

            print "Sorry to say that your Email is not Registered!."; 

        } 
    } 

?> 

My common.php

// These variables define the connection information for your MySQL database 
    $username = "localhost"; 
    $password = ""; 
    $host = "localhost"; 
    $dbname = "test"; 

    // UTF-8 is a character encoding scheme that allows you to conveniently store 
    // a wide varienty of special characters, like ¢ or €, in your database. 
    // By passing the following $options array to the database connection code.
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

    // A try/catch statement is a common method of error handling in object oriented code. 
    // First, PHP executes the code within the try block.  If at any time it encounters an 
    // error while executing that code, it stops immediately and jumps down to the 
    // catch block.  
    try 
    { 
        // This statement opens a connection to your database using the PDO library 
        // PDO is designed to provide a flexible interface between PHP and many 
        // different types of database servers. 
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 
        // If an error occurs while opening a connection to your database, it will 
        // be trapped here.
        die("Failed to connect to the database");
    } 

    // This statement configures PDO to throw an exception when it encounters 
    // an error.  This allows us to use try/catch blocks to trap database errors. 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

    // This statement configures PDO to return database rows from your database using an associative 
    // array.  This means the array will have string indexes, where the string value
    // represents the name of the column in your database. 
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 


    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 

        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 

    // This tells the web browser that your content is encoded using UTF-8 
    // and that it should submit content back to you using UTF-8 
    header('Content-Type: text/html; charset=utf-8'); 



    session_start();
    // Note that it is a good practice to NOT end your PHP files with a closing PHP tag. 
    // This prevents trailing newlines on the file from being included in your output, 
    // which can cause problems with redirecting users.

and here's my test page.

<?php require "common.php";
ob_start();


  echo $_SESSION['validEmail'];


?>
Sotiris Kiritsis
  • 3,178
  • 3
  • 23
  • 31
  • are you starting the session – Drew Jul 11 '16 at 05:13
  • yes and the other page i have the session_start() on top of my page too – user3933865 Jul 11 '16 at 05:13
  • where is session_start, I am no PHP genius – Drew Jul 11 '16 at 05:14
  • Show us the other page you're using sessions on and common.php – awl19 Jul 11 '16 at 05:17
  • my problem is that im trying to echo the value to the other page, but its showing blank wait ill post it . – user3933865 Jul 11 '16 at 05:19
  • We need the other page. How do you access `$_SESSION` there? do you `session_start()` on the other page? – BeetleJuice Jul 11 '16 at 05:20
  • Do you know whether your code ever gets to the `$login_ok=true` line? ie does the location actually get changed to `next.php`? – BeetleJuice Jul 11 '16 at 05:22
  • 1
    Okay, take out ob_start from both files and move session_start in common.php from the bottom to the very top line, just under the – awl19 Jul 11 '16 at 05:24
  • @BeetleJuice yes its correct – user3933865 Jul 11 '16 at 05:24
  • i've tried print_r($_SESSION); on the other page . the value is there. but if i tried echo its not. – user3933865 Jul 11 '16 at 05:28
  • you're accessing the wrong variable name. See my answer. – BeetleJuice Jul 11 '16 at 05:34
  • Here is my hashing PDO login example if you want it: http://stackoverflow.com/a/32556010 ,, password_hash and password_verify .... set the session vars to a row's column, not the whole row – Drew Jul 11 '16 at 05:37
  • You must notice that, just a blank new line at the beginning of the PHP file may corrupt session. – SaidbakR Jul 11 '16 at 05:40
  • @Drew thanks , i'll try using it sometime. im just validating to login in. my code is not using password. – user3933865 Jul 11 '16 at 05:41
  • At the top of page 1 and page 2: `error_reporting(E_ALL); ini_set("display_errors", 1); session_start(); ` That way if something is making a critical error, it is not dying silently. Then PDO gets constructing, you have PDOExceptions, everything in a try / catch block. Then sprinkle a some echos here and there. It is turning on the sonar til you get it in good shape. Right now you are flying blind. With error reporting enabled, if you have a "Headers have already been Sent Error" or similar, you will at least show the error to yourself – Drew Jul 11 '16 at 06:00

2 Answers2

1

Your problem is that you're echoing a variable that doesn't exist. The user-submitted email is stored in $_POST['validEmail'], but you never store it in the session so you can't access it on another page. Add this line, once you've authenticated the user

if($login_ok){
    ...
    $_SESSION['validEmail'] = $_POST['validEmail'];
    ...
}

Now that it's saved in the session, you can access it on other pages.

echo $_SESSION['validEmail'];

PS: By the way your login is not good. Anyone can impersonate a victim just by entering the victim's email in the form. You never check the email against a user's password.

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165
0

In common.php add the first line as session_start() and remove from test page

SattyamBhatt
  • 338
  • 2
  • 13