PHP에서 HTML 페이지로 로그인 점프 기능을 구현하는 방법
PHP에서 HTML 페이지로 로그인 점프를 구현하려면 몇 가지 기본 프로그래밍 기술이 필요합니다. 프로세스를 구현하는 구체적인 단계는 다음과 같습니다.
- 로그인 페이지 만들기
먼저 사용자의 로그인 자격 증명을 수집하기 위한 로그인 페이지를 만들어야 합니다. 이 페이지는 사용자 자격 증명을 확인하고 로그인한 사용자를 다른 보호된 페이지로 안내하는 데 사용됩니다.
- 로그인 확인 논리 설정
PHP에서는 사용자가 입력한 자격 증명이 유효한지 확인하는 확인 논리를 만들 수 있습니다. 이 기능은 MySQL 데이터베이스와 PHP 세션을 사용하여 구현할 수 있습니다. 구체적인 단계는 다음과 같습니다.
- 사용자가 입력한 사용자 이름과 비밀번호를 기록합니다.
- 사용자 이름과 비밀번호를 MySQL 데이터베이스에 저장된 계정 정보와 비교합니다.
- 입력한 사용자 이름과 비밀번호가 데이터베이스와 일치하면 사용자 자격 증명이 PHP의 세션 변수에 저장되고 보호된 페이지로 리디렉션됩니다.
- 입력한 사용자 이름과 비밀번호가 일치하지 않으면 사용자에게 오류 메시지를 표시합니다.
다음은 유효성 검사 논리의 코드 예입니다.
<?php // Start the session session_start(); // Check if the user is already logged in if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ header("location: welcome.php"); exit; } // Include config file require_once "config.php"; // Define variables and initialize with empty values $username = $password = ""; $username_err = $password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if username is empty if(empty(trim($_POST["username"]))){ $username_err = "Please enter username."; } else{ $username = trim($_POST["username"]); } // Check if password is empty if(empty(trim($_POST["password"]))){ $password_err = "Please enter your password."; } else{ $password = trim($_POST["password"]); } // Validate credentials if(empty($username_err) && empty($password_err)){ // Prepare a select statement $sql = "SELECT id, username, password FROM users WHERE username = ?"; if($stmt = $mysqli->prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt->bind_param("s", $param_username); // Set parameters $param_username = $username; // Attempt to execute the prepared statement if($stmt->execute()){ // Store result $stmt->store_result(); // Check if username exists, if yes then verify password if($stmt->num_rows == 1){ // Bind result variables $stmt->bind_result($id, $username, $hashed_password); if($stmt->fetch()){ if(password_verify($password, $hashed_password)){ // Password is correct, so start a new session session_start(); // Store data in session variables $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; // Redirect user to welcome page header("location: welcome.php"); } else{ // Display an error message if password is not valid $password_err = "The password you entered was not valid."; } } } else{ // Display an error message if username doesn't exist $username_err = "No account found with that username."; } } else{ echo "Oops! Something went wrong. Please try again later."; } } // Close statement $stmt->close(); } // Close connection $mysqli->close(); } ?>
- 보호된 HTML 페이지 만들기
PHP에서는 세션 변수를 사용하여 사용자가 로그인했는지 확인할 수 있습니다. 사용자가 로그인하면 보호된 HTML 페이지가 표시될 수 있습니다. 그렇지 않으면 로그인 페이지로 리디렉션해야 합니다.
- 로그인 페이지에 PHP 코드 추가
로그인 페이지에서 PHP 코드를 사용하여 양식 제출 및 유효성 검사를 처리할 수 있습니다. 구체적인 단계는 다음과 같습니다.
- 사용자 자격 증명을 제출하는 양식을 만듭니다.
- 양식을 제출할 때 사용자가 입력한 자격 증명이 유효한지 확인하고 보호된 페이지로 리디렉션되거나 오류 메시지를 표시합니다.
- 사용자가 이미 로그인한 경우 로그인 양식을 표시하는 대신 보호된 페이지로 자동 리디렉션됩니다.
다음은 로그인 양식과 PHP 코드가 포함된 샘플 코드입니다.
<?php // Initialize the session session_start(); // Check if the user is already logged in, if yes then redirect him to welcome page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ header("location: welcome.html"); exit; } // Include config file require_once "config.php"; // Define variables and initialize with empty values $username = $password = ""; $username_err = $password_err = ""; // Processing form data when form is submitted if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if username is empty if(empty(trim($_POST["username"]))){ $username_err = "Please enter username."; } else{ $username = trim($_POST["username"]); } // Check if password is empty if(empty(trim($_POST["password"]))){ $password_err = "Please enter your password."; } else{ $password = trim($_POST["password"]); } // Validate credentials if(empty($username_err) && empty($password_err)){ // Prepare a select statement $sql = "SELECT id, username, password FROM users WHERE username = ?"; if($stmt = $mysqli->prepare($sql)){ // Bind variables to the prepared statement as parameters $stmt->bind_param("s", $param_username); // Set parameters $param_username = $username; // Attempt to execute the prepared statement if($stmt->execute()){ // Store result $stmt->store_result(); // Check if username exists, if yes then verify password if($stmt->num_rows == 1){ // Bind result variables $stmt->bind_result($id, $username, $hashed_password); if($stmt->fetch()){ if(password_verify($password, $hashed_password)){ // Password is correct, so start a new session session_start(); // Store data in session variables $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; // Redirect user to welcome page header("location: welcome.html"); } else{ // Display an error message if password is not valid $password_err = "The password you entered was not valid."; } } } else{ // Display an error message if username doesn't exist $username_err = "No account found with that username."; } } else{ echo "Oops! Something went wrong. Please try again later."; } } // Close statement $stmt->close(); } // Close connection $mysqli->close(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <style> body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } </style> </head> <body> <div class="wrapper"> <h2>Login</h2> <p>Please fill in your credentials to login.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username</label> <input type="text" name="username" class="form-control" value="<?php echo $username; ?>"> <span <?php echo (!empty($username_err)) ? 'help-block' : ''; ?>"><?php echo $username_err; ?></span> </div> <div <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password</label> <input type="password" name="password" class="form-control"> <span <?php echo (!empty($password_err)) ? 'help-block' : ''; ?>"><?php echo $password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> <p>Don't have an account? <a href="register.html">Sign up now</a>.</p> </form> </div> </body> </html>
위는 PHP를 통해 HTML 페이지로 이동하기 위한 사용자 로그인을 구현하는 기본 단계 및 코드 예제입니다.
위 내용은 PHP에서 HTML 페이지로 로그인 점프 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제









