nl2br和htmlspecialchars的使用

本文介绍了PHP中如何使用htmlspecialchars函数将HTML中的特殊字符转换为安全的格式,以避免潜在的安全风险,如XSS攻击等。同时对比了htmlspecialchars与htmlentities函数的区别。
string nl2br (string $string)
说明:将换行符用 <br/>代替
范例:
<?php
echo nl2br("foo isn't\n bar");
?>

将输出:
foo isn't<br />
bar

string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
说明:将特殊字符转成 HTML 的字符串格式 ( &....; )。最常用到的场合可能就是处理客户留言的留言版了。
'&' 转换成 '&amp;'
'"' (双引号)转换成 '&quot;' 要设置ENT_NOQUOTES
''' (单引号)转换成 '&#039;' 要设置ENT_QUOTES
'<' (小于)转换成 '&lt;'
'>' (大于)转换成 '&gt;'
htmlspecialchars()比htmlentities()支持的字符集多一些(PHP5支持12个),不容易出线中文的乱码
范例:
<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new;
?>

运行结果: &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
这两个函数一般用于网页提交内容的转换,防止恶意的注入HTML代码。
<?php $username = $_POST["username"] ; $password = $_POST["password"] ; if($username === "admin" && $password === "admin1") { // 读取所有笔记文件 $notes = []; $note_files = glob('notes/*.txt'); foreach ($note_files as $file) { $id = basename($file, '.txt'); $content = file_get_contents($file); $notes[$id] = $content; } ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>读书笔记系统</title> <link rel="stylesheet" href="styles.css"> </head> <body> <script> alert('登陆成功'); </script> <div class="container"> <h1>我的读书笔记</h1> <form action="add_note.php" method="post" class="note-form"> <h2>添加新笔记</h2> <div class="form-group"> <label for="book_title">书名:</label> <input type="text" id="book_title" name="book_title" required> </div> <div class="form-group"> <label for="note_content">笔记内容:</label> <textarea id="note_content" name="note_content" rows="5" required></textarea> </div> <button type="submit">保存笔记</button> </form> <div class="notes-list"> <h2>我的笔记</h2> <?php if (empty($notes)): ?> <p>暂无笔记,添加你的第一条读书笔记吧!</p> <?php else: ?> <?php foreach ($notes as $id => $content): ?> <div class="note-card"> <div class="note-content"><?= nl2br(htmlspecialchars($content)) ?></div> <form action="delete_note.php" method="post" class="delete-form"> <input type="hidden" name="note_id" value="<?= $id ?>"> <button type="submit" class="delete-btn">删除</button> </form> </div> <?php endforeach; ?> <?php endif; ?> </div> </div> </body> </html> <?php } else { echo "<script>alert('账号或者密码不正确');</script>"; } ?>
最新发布
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值