-2

I'm learning PHP. I'm trying to build a website that stores a pdf alongside the $_SESSION's stored email. But everything I try results in "undefined array key error". Here's the main code:

The registration form:

 <form action="insert.php" method="post">
        <div class="container" style="margin-left: 30%; margin-top: 15%">
            <div class="card align-content-center" style="width: 50%; padding-left: 13%">
                <div class="form-row mb-2"></div>
                <div class="form-row mb-2"> <!-- migliore gestione form php -->
                    <div class="col-2">
                        <label for="firstName">Nome:</label>
                    </div>
                    <div class="col-3">
                        <input type="text" name="first_name" id="firstName" required>
                    </div>
                </div>
                <div class="form-row mb-2">
                    <div class="col-2">
                        <label for="email">Email:</label>
                    </div>
                    <div class="col-3">
                        <input type="email" name="email" id="email" required>
                    </div>
                </div>
                <div class="form-row mb-2">
                    <div class="col-2">
                        <label for="Password">Password:</label>
                    </div>
                    <div class="col-3">
                        <input type="password" name="password" id="Password" required>
                    </div>
                </div>
                <div class="form-row mb-2">
                    <div class="col-2 offset-4">
                        <input type="submit" value="Invia" class="btn btn-outline-primary" onclick="return verifica();"> <!-- parte con return true, se false non prosegue -->
                    </div>
                </div>
            </div>
        </div>
    </form>

Pretty basic, nothing special here. It connects to the "insert.php" page which stores the data.

<?php

include('conn.inc');

$first_name = $_REQUEST['first_name'];
$email      = $_REQUEST['email'];
$password   = password_hash($_REQUEST['password'], PASSWORD_DEFAULT);

// nome table: ListaUtenti
$sql = "INSERT INTO ListaUtenti (first_name, email, password) VALUES ('$first_name','$email','$password')";

if(mysqli_query($conn, $sql)){
    echo "<h3>Dati immagazzinati correttamente in SQL.</h3>";

    echo nl2br("\n$first_name\n $email\n $password");
} else{
    echo "ERRORE: Qualcosa non è andato come doveva."
        . mysqli_error($conn);
}

// Chiudi connessione
mysqli_close($conn);
?>

The login:

        <?php

    $_SESSION['connesso'] = false;
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $first_name = $_POST['username'];
        $password = $_POST['password'];
        $email = $_POST['email'];
//        echo "$password<br>";
        // Get username and password from form

        // Check if username and password match a record in the database
        $result = mysqli_query($conn, "SELECT * FROM listautenti WHERE first_name = '$first_name' AND password = '$password'");
        if (mysqli_num_rows($result) == 1) {
            // Store the username in the session to indicate that the user is logged in
            $_SESSION['username'] = $first_name;
            $_SESSION['connesso'] = true;
            header("Location: index.php");
            exit;
        } else {
            $error = "Nome o password errati.";
        }
    }
    ?>

And now the storing part in the index page. Everything works except the email.

<?php

        $message = "File caricato correttamente.";
        if(isset($_POST['email'])){
            $_SESSION['email'] = $_POST['email'];
        }
        #connection string
        if (isset($_POST["submit"])) {
            if (is_uploaded_file($_FILES["file"]["tmp_name"]) && ($_FILES["file"]["type"] == 'application/pdf')) {
                echo "";
                #file name ha un numero casuale, in modo che non verrà rimpiazzato
                $pname = rand(1000, 10000) . "-" . $_FILES["file"]["name"];
                #nome temporaneo per immagazzinare il file
                $tname = $_FILES["file"]["tmp_name"];
                #path per l'upload
                $uploads_dir = 'img';
                #spostare l'upload in una directory specifica
                move_uploaded_file($tname, $uploads_dir . '/' . $pname);
                #sql query per inserire in un databse
//                $sql = "INSERT into fileup(pdf) VALUES('$pname')";"INSERT into fileup(email) VALUES('email')";
                $sql = "INSERT into fileup(pdf, email) VALUES('$pname', '".$_SESSION['email']."')";
                if (mysqli_query($conn, $sql)) {
                    echo "<script type='text/javascript'>alert('$message');</script>";
                } else {
                    echo "Errore.";
                }
            } else {
                echo "Il file è di tipo errato.";
            }
}

Thanks in advance, I just don't get why it wouldn't store the email.

EDIT: nevermind, solved! I just added to the login part:

  $row = mysqli_fetch_assoc($result);
  $_SESSION['email'] = $row['email'];
    ```
Gabriele
  • 1
  • 1
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Feb 13 '23 at 20:43

1 Answers1

-2
  1. Your login.php and index.php code is lacking session_start(); that will initialize the session for you.

2.) You did not set email variable to session. something like $_SESSION['email'] = $email;

3.) Your Code is also vulnerable to SQL Injection Attack. You should better use prepared statement or PDO

4.) Your Code is vulnerable to session hijacking and Session fixation attack.you will have to regenerate session on login. something like session_regenerate_id();

login.php

    <?php
    
    //initialize sessions
    session_start();
        $_SESSION['connesso'] = false;
        if (isset($_POST['username']) && isset($_POST['password'])) {
            $first_name = $_POST['username'];
            $password = $_POST['password'];
            $email = $_POST['email'];
    //        echo "$password<br>";
            // Get username and password from form
    
            // Check if username and password match a record in the database
            
    $sql = "SELECT * FROM listautenti WHERE first_name=? and password=?"; // SQL with parameters
    $stmt = $conn->prepare($sql); 
    $stmt->bind_param("ss", $first_name,$password);
    $stmt->execute();
    $result = $stmt->get_result(); // get the mysqli result
    //$user = $result->fetch_assoc();  // get data
/*
while ($row = $result->fetch_assoc()) {
   $row['first_name'];
} 
 */   
    
            if (mysqli_num_rows($result) == 1) {
    
    //stop session hijacking and Session fixation attack.
    session_regenerate_id();
    
                // Store the username in the session to indicate that the user is logged in
                $_SESSION['username'] = $first_name;
               $_SESSION['email'] = $email;
                $_SESSION['connesso'] = true;
                header("Location: index.php");
                exit;
            } else {
                $error = "Nome o password errati.";
            }
        }
        ?>

index.php should look like

   <?php


//initialize sessions
session_start();
        $message = "File caricato correttamente.";

echo  $email= $_SESSION['email'];

/*
        if(isset($_POST['email'])){
            $_SESSION['email'] = $_POST['email'];
        }
*/
        #connection string
        if (isset($_POST["submit"])) {
            if (is_uploaded_file($_FILES["file"]["tmp_name"]) && ($_FILES["file"]["type"] == 'application/pdf')) {
                echo "";
                #file name ha un numero casuale, in modo che non verrà rimpiazzato
                $pname = rand(1000, 10000) . "-" . $_FILES["file"]["name"];
                #nome temporaneo per immagazzinare il file
                $tname = $_FILES["file"]["tmp_name"];
                #path per l'upload
                $uploads_dir = 'img';
                #spostare l'upload in una directory specifica
                move_uploaded_file($tname, $uploads_dir . '/' . $pname);
                #sql query per inserire in un databse

$sql = $conn->prepare("INSERT INTO fileup (pdf, email) VALUES (?, ?)");
$sql->bind_param("ss", $pname, $email);

                if ($sql) {
                    echo "<script type='text/javascript'>alert('$message');</script>";
                } else {
                    echo "Errore.";
                }
            } else {
                echo "Il file è di tipo errato.";
            }
//$sql->close();
//$conn->close();
}

Try it and let me know

Nancy Moore
  • 2,322
  • 2
  • 21
  • 38