PHP -从$_SESSION检索电子邮件

busg9geu  于 2023-02-15  发布在  PHP
关注(0)|答案(1)|浏览(182)

我正在学习PHP。我试图建立一个网站,在$_SESSION存储的电子邮件旁边存储PDF文件。但我尝试的一切都导致“未定义数组键错误”。以下是主要代码:
报名表:

<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>

非常基本,这里没有什么特别的。它连接到存储数据的“insert.php”页面。

<?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);
?>

登录名:

<?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.";
        }
    }
    ?>

现在是索引页中的存储部分。除了电子邮件,一切都正常。

<?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.";
            }
}

先谢谢你,我只是不明白为什么它不存储电子邮件。
编辑:没关系,解决了!我只是添加到登录部分:

$row = mysqli_fetch_assoc($result);
  $_SESSION['email'] = $row['email'];
    ```
jchrr9hc

jchrr9hc1#

1.您的login.php和index.php代码缺少为您初始化会话的session_start();
2.)您没有将email变量设置为session.类似于$_SESSION['email'] = $email;
3.)您的代码也容易受到SQL注入攻击。您最好使用预准备语句或PDO
4.)您的代码容易受到会话劫持和会话固定attack.you将不得不重新生成登录时的会话。类似于session_regenerate_id();

登录名.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应如下所示

<?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();
}

试试看然后告诉我

相关问题