CSRF защита
формы по отправке сообщений.
Идем
в send-message.php
Открываем сессию,
генерируем токен и сохраняем его в
форму.
<?php
session_start();
$cstrong = true; //
генерируем токен
$token =
bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
if
(!isset($_SESSION['token'])) {
$_SESSION['token'] =
$token;
}
include('./classes/DB.php');
include('./classes/Login.php');
if
(Login::isLoggedIn()) {
$userid =
Login::isLoggedIn();
} else {
die ('Not logged
in!');
}
if
(isset($_POST['send'])) {
if
(!isset($_POST['nocsrf'])) {
die("Invalid
token!");
}
if
($_POST['nocsrf'] != $_SESSION['token']) {
die("Invalid
token!");
}
if
(DB::query('SELECT id FROM users WHERE id =:receiver',
array(':receiver'=>$_GET['receiver']))) {
DB::query("INSERT INTO messages VALUES(:id, :body, :sender,
:receiver, 0)", array(':id'=>null, ':body'=>$_POST['body'],
':sender'=>$userid,
':receiver'=>htmlspecialchars($_GET['receiver'])));
echo "Message
Sent!";
} else {
die('Invalid
ID!');
}
session_destroy();
// после того, как сообщение было
отправлено, токен удаляется из сессии
}
?>
<h1>Send a
Message</h1>
<form
action="send-message.php?receiver=<?php echo
htmlspecialchars($_GET['receiver']); ?>" method="post">
<textarea
name="body" cols="80" rows="8"></textarea>
<input
type="hidden" name="nocsrf" value="<?php
echo $_SESSION['token']; ?>"/>
<input
type="submit" name="send" value="Send
Message"/>
</form>
Файл
my-messages.php
<?php
include('./classes/DB.php');
include('./classes/Login.php');
if
(Login::isLoggedIn()) {
$userid = Login::isLoggedIn();
}
else {
die('Not logged in');
}
if
(isset($_GET['mid'])) {
$message = DB::query('SELECT * FROM messages WHERE id=:mid AND
(receiver=:receiver OR sender=:sender)', array(':mid'=>$_GET['mid'],
':receiver'=>$userid, ':sender'=>$userid))[0];
echo '<h1>View Message</h1>';
echo htmlspecialchars($message['body']);
echo '<hr />';
if ($message['sender'] == $userid) {
$id = $message['receiver'];
} else {
$id = $message['sender'];
}
DB::query('UPDATE messages SET `read`=1 WHERE id=:mid', array
(':mid'=>$_GET['mid']));
?>
<form action="send-message.php?receiver=<?php echo $id;
?>" method="post">
<textarea name="body" rows="8"
cols="80"></textarea>
<input type="submit" name="send"
value="Send Message">
</form>
<?php
}
else {
?>
<h1>My
Messages</h1>
<?php
$messages
= DB::query("SELECT * FROM messages WHERE sender=:sender OR
receiver=:receiver", array(':sender'=>$userid,
':receiver'=>$userid));
foreach
($messages as $message) {
$sender = DB::query("SELECT username FROM users WHERE
id=:senderid",
array(':senderid'=>$message['sender']))[0]['username'];
if (strlen($message['body']) > 10) {
$m = substr($message['body'], 0, 10)." ...";
} else {
$m = $message['body'];
}
if ($message['read'] == 0) {
echo "<a
href='my-messages.php?mid=".$message['id']."'><strong>".$m."</strong></a>
sent by ".$sender.'<hr />';
} else {
echo "<a
href='my-messages.php?mid=".$message['id']."'>".$m."</a>
sent by ".$sender.'<hr />';
}
}
}
?>
Комментариев нет:
Отправить комментарий