如何在PHP中保护我的$ _GET?

ggf*_*fan 1 php mysql

我的profile.php显示所有用户的帖子,评论,图片.如果用户想要删除,它会将发布的id发送到remove.php,这就像remove.php?action = removeposting&posting_id = 2.如果他们想要删除图片,那就是remove.php?action = removepicture&picture_id = 1.

使用获取数据,我对数据库进行查询以显示他们想要删除的信息,如果他们想删除它们,则单击"是".因此,数据将通过$ POST NOT $ GET删除,以防止跨站点请求伪造.

我的问题是如何确保GET不是一些javascript代码,sql注入会搞砸我.

这是我的remove.php

    //how do I make $action safe? 
    //should I use mysqli_real_escape_string?
    //use strip_tags()?
    $action=trim($_GET['action']);

    if (($action != 'removeposting') && ($action != 'removefriend') 
    && ($action != 'removecomment'))
    {
            header("Location: index.php");
            exit();
    }

if ($action == 'removeposting')
{
   //get the info and display it in a form. if user clicks "yes", deletes
}

if ($action =='removepicture')
{
   //remove pic
}
Run Code Online (Sandbox Code Playgroud)

我知道我不能百分百安全,但我可以使用哪些常见的防御措施.

编辑

Do this to prevent xss
$oldaction=trim($_GET['action']);
$action=strip_tags($oldaction);

Then when I am 'recalling' the data back via POST, I would use 
$posting_id = mysqli_real_escape_string($dbc, trim($_POST['posting_id']));
Run Code Online (Sandbox Code Playgroud)

        if ($action == 'removeposting')
{
    //get the posting id from the user  
    $getposting_id = htmlspecialchars(trim($_GET['posting_id']));

    //basic checks for the posting id
    if (empty($getposting_id)){
        //header ("Location: index.php");
        echo '<p>Sorry, no posting was specified for removal.</p>';
        exit();
    }

    if (!is_numeric($getposting_id))
    {   
        echo "Not an integer";
        exit();
    }
        //Also have check to see if the posting_id is the user's. If so, can delete
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 5

因为您没有存储$action并且仅在条件中使用它,所以不必进行所有修剪/剥离/转义.简单的字符串比较在"安全性"方面就足够了,但我建议使用===而不是==.

或者,例如,如果要将一个$_GET$_POST值存储到MySQL数据库的整数列中,则可以在将值intval()存储到数据库之前将其传递给该值.如果您需要存储纯文本,请mysql_real_escape_string()在存储之前将其传递出去.您还可以使用preg_match()preg_replace()确保您只存储有效值(不同用途的不同模式,例如/^\d{5}(?:-?\d{4})?$/邮政编码).