これで、PHPを書く方法を学んでいます。私は小さなショッピングサイトを作りたいと思っています。私のindex.htmlは次のようなものになります。私たちが初めてアップロードするページのPHPコードセクションをスキップ
<!DOCTYPE html>
<html>
<head>
<link href="index.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="topnav">
<a class="active" href="#index.html">Home</a>
<a href="loginAdmin.php">Administrator</a>
<a href="loginUser.php">Register User</a>
<a href="newAccount.php">Register New Account</a>
</div>
<img class="centerImage" src="eshop.jpg">
</body>
</html>
をしてloginAdmin.phpファイルは次のようになります。PHPコードのでloginAdminリンク上で押されたユーザーが実行された場合
<?php
session_start();
// here is the code that connects to the database. Note that the username
// and password are "hard-coded".
$user="root";
$passwd="";
$database="";
$link = mysqli_connect(localhost,$user,$passwd);
@mysqli_select_db($link,$database) or die ("Unable to select database");
// try to create a new record from the submission
$username = mysqli_real_escape_string($link,$_REQUEST['username']);
$password= mysqli_real_escape_string($link,$_REQUEST['password']);
if ($username && $password) {
// here we define the SQL command
$query = "SELECT * FROM people WHERE Username='$username' AND Password='$password'";
// submit the query to the database
$res=mysqli_query($query);
// make sure it worked!
if (!$res) {
echo mysql_error();
exit;
}
// find out how many records we got
$num = mysqli_numrows($res);
if ($num==0) {
echo "<h3>Invalid login</h3>\n";
exit;
} elseif ($num!=1) {
echo "<h3>Error - unexpected result!\n";
exit;
}
// valid login, set the session variable
$_SESSION['userid']=mysql_result($res,0,'userid');
echo "<h3>Welcome $username</h3>\n";
?>
<head>
<link href="login.css" rel="stylesheet" />
<title>
eShop
</title>
</head>
<body>
<div class="login-page">
<div class="form">
<form class="login-form">
<input type="text" placeholder="User Name:" />
<input type="password" placeholder="Password:" />
<button onclick="writeMsg()">login</button>
</form>
</div>
</div>
</body>
、および私は望んでいない、ユーザーがログインボタンを押した後にのみ、私はPHPコードブロックが実行されたいです。どうやってやるの?たぶん私はファイル(phpとhtml)とindex.htmlのPHPファイルのユーザーhrefを分離する必要がありますか? index.htmlファイルはindex.phpにする必要がありますか?
'$ _POST ['username']'(または$ _REQUEST、しかし私はpreciceが好きです)が設定されているかどうかを確認する必要があります( 'isset($ _ POST ['username'] ') - >必要なものを実行してください。それ以外の場合は、認証されたユーザーのためにセッションを使用して、適切な方法で – Jeff
フォームを表示してください。より多くのコンテンツを表示するためにユーザーセッションが存在するかどうかを判断します。 –
[Little Bobby](http://bobby-tables.com/)によると*** [あなたのスクリプトはSQLインジェクション攻撃の危険にさらされています。](http://stackoverflow.com/questions/60174/how-can- i-prevent-sql-injection-in-php)*** [MySQLi](http://php.net/manual)の[prepared](http://en.wikipedia.org/wiki/Prepared_statement)ステートメントについて学びます。 /en/mysqli.quickstart.prepared-statements.php)。 [文字列をエスケープする](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)でも安全ではありません! –