如何使用 PHP 将撇号从文本区域传递到 MySQL [英] How to pass apostrophies from text areas to MySQL using PHP

查看:18
本文介绍了如何使用 PHP 将撇号从文本区域传递到 MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户也可以添加注释的文本区域.在下一页上,我使用 $_POST[Comments] 来显示输入的内容.我有一个编辑按钮可以返回并查看输入的内容并编辑注释,但是当我显示 $_POST[Comments] 时,它会显示所有内容,直到撇号.

I have a text area that users add notes too. On the next page I use the $_POST[Comments] to show what was typed. I have an edit button to go back and see what was typed and edit the notes but when I show the $_POST[Comments] it shows everything up to an apostrophe.

示例:

原始输入:让我们试试这个.

编辑时:Let

现在,当我将它传递给服务器以执行 SQL 添加时,我使用以下函数来防止 SQL 注入

Now when I pass it to the server to do an SQL add I use the following function to protect against SQL injection

function keepSafe($value) {
        if (get_magic_quotes_gpc()) {
            $value = stripslashes($value);
        }
        if (!is_numeric($value)) {
            $value = "'" . mysqli_real_escape_string($value) . "'";
        }
        return $value;
    }

以下是我用来格式化 SQL 插入输入的内容.

The following is what I use to format the input for SQL insertion.

$Comments = str_replace("\n","<br />",$_POST['CustComments']);
    $Comments = keepSafe($_POST['Comments']);

在提交前进行编辑时,我需要能够看到备注部分中的所有撇号.而且我想确保当我提交时,它是一个防止 SQL 注入的安全代码.

I need to be able to see all of the apostrophes in the notes section when editing before submission. And I want to make sure that when I do submit it is a SQL injection prevented safe code.

推荐答案

撇号的问题:

您可能会使用这样的输入:

You probably use an input like this:

<input type='text' value='<?php echo $value;?>'/>

问题是,如果值有撇号,就会发生这种情况:

The problem is that if the value has an apostrophe this happens:

<input type='text' value='Let's play'/>

所以值标签因为变量中的撇号而结束.

So the value tag is ended because of the apostrophe in your variable.

要修复它,只需将 htmlspecialchars 与 ENT_QUOTES 一起使用:

To fix it simply use htmlspecialchars with ENT_QUOTES:

<?php 
 $value = htmlspecialchars("Let's play", ENT_QUOTES);
?>
<input type='text' value='<?php echo $value; ?>'/>

这样撇号就会被编码并且可以在您的表单中编辑

That way the apostrophe's get encoded and will be editable in your form

关于 SQL 注入:

只需使用 mysqli 的准备好的语句 就可以了.为了让您免受 XSS 的侵害,请始终在 HTML 输出中使用 htmlspecialchars 用户输入.更好的是将输入过滤为仅您需要的内容,并将过滤后的输入仅保存到您的数据库中.

Simply use mysqli's prepared statements and you will be fine. To also keep you safe from XSS, always htmlspecialchars user input in HTML output. Even better is to filter the input to only what you need, and save only the filtered input to your database.

这篇关于如何使用 PHP 将撇号从文本区域传递到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆