はい、ユーザーがログインしているかどうかを確認する簡単な方法があり、$_SESSION
スーパーグローバルを使用するのが最善の方法です。セッションスーパーグローバルを使用すると、基本的に特定のユーザーに関するサーバーに情報を保存すると同時に、セッションが有効である限り(通常は30分)、ユーザーを一意に識別するCookieをユーザーのコンピュータに保存します。普通の英語では、PHP開発者は極端な量のコードを実行することなく、開発者が「状態を維持する」ことが基本的に簡単にできるスーパーグローバルを作りました。
これはセッションスーパーグローバルを使用する方法です。これは(他の多くのものの中で)している何
<?php session_start(); ?>
は、特定のユーザーのコンピュータ上にクッキーを保存します。あなたのウェブサイトの各ページの上部に、あなたは(さえ<!DOCTYPE html>
上記)のコードのこの部分を持っているでしょうセッションが有効である間、彼は一意になります。あなたが持っている、あなたは以下のコードが含まれるすべてのページに今
<?php
$username = $_POST['username'];//obtaining username from form
$password = $_POST['password'];//obtaining password from form
// i did not include any encryption code in this example
// so that the example is easier to understand, but keep in mind
// that encrypting your users passwords is super important
//for security reasons, I used prepared statements and binding parameters
//to compare the password and username obtained from the form with
//those in the database (in order to prevent sql injection):
$sql = "SELECT 1 FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
if ($stmt->rowCount()>0)//if a row was found, then you know this user exists
{
//here I am saving information in the session super global that
//can be used to not only identify if a user is logged in on each
//page, but also to see which user is logged in, since often
//you want to give a user his own control panel or other features.
$_SESSION['authenticated'] = TRUE;
$_SESSION['username'] = htmlspecialchars($username);
}
?>
:
はNOW ...ユーザーがログインした後に入るページのは、次のようなコードを持っています
<?php
if (isset($_SESSION['authenticated']))
{
echo "Hello there ".$_SESSION['username']."!<br>";
}
?>
前のコードでは、「Hello there John!」のようなメッセージが返されます。ユーザー名がJohnの場合ここからは、ユーザがログインしただけにしたい括弧の中にコードを含めることができます。あなたはログインしていないので、サイトを見ることはできますが、ウェブサイトのその部分を見ることはできませんロゴ、および条件付きのの内部にないすべてのものが含まれます。また、前のコードは一番上にある必要はなく、<?php session_start(); ?>
だけが必要であり、これはHTTPプロトコルの仕組みに関する理由からです。
これが役に立ったかどうか、他にご質問がありましたら教えてください。
この投稿彼女:http://stackoverflow.com/questions/37234576/php-setting-session-information-in-a-cookie-after-page-reload – Munsterlander
@Paulは私の回答を助けましたか? – Webeng