在 PHP 中保护 $_GET 请求

Securing a $_GET request in PHP

保护 GET 请求的最佳方法是什么,或者是否有更安全的替代方法?


我在我的网站中使用了几个 GET 请求来动态生成网页并根据 ID 删除记录。

最后一个让我有点担心,因为人们可以将 URL 更改为他们想要删除的任何文件。

要访问删除文件,他们需要登录并拥有一定的权限,如果他们没有足够的权限,将会抛出错误。


我遇到了 a really old SO post,说明您应该使用 mysqli_real_escape_string 函数使其至少 安全。

我还了解到验证非常重要,所以我在考虑检查 ID 是否为实际整数。

There's another post 声明将请求隐藏在 URL 中基本上没有用,因为请求将始终是 URL.

的一部分

这是我的删除文件,它使用两条语句,一条删除实际的post,另一条删除与post相关的图像。

include('./utils/auth.php');

require('./utils/db.php');

$stmt_1 = $connect->prepare('DELETE FROM `dias` WHERE diaserie_id = ?');

if($stmt_1) {
    $id = $_GET['id'];
    $stmt_1->bind_param('i', $id);
    if($stmt_1->execute()) {
        // Als de afbeeldingen uit de database zijn, verwijder dan ook de serie zelf
        $stmt_2 = $connect->prepare('DELETE FROM `diaseries` WHERE diaserie_id = ?');
        if($stmt_2) {
            $stmt_2->bind_param('i', $id);
            if($stmt_2->execute()) {
                echo "Both the files and post have been deleted.";
            } else {
                echo "The files have been deleted, the post iself could not be deleted.";
            }
        }
    } else {
        echo "Files and post could not be deleted.";
    }
}

将图像和相关文件存储在数据库中 (MySQL),并且只允许从与同一登录凭据相关的数据库中删除。

您不应该考虑将图像上传到数据库,而是可以将上传文件的名称存储在数据库中,然后检索文件名并在您想要显示图像的任何地方使用它。

HTML 代码:

<input type="file" name="imageUpload" id="imageUpload">

PHP 代码:

if(isset($_POST['submit'])) {

    //Process the image that is uploaded by the user

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }

    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

    //storind the data in your database
    $query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
    mysql_query($query);

    require('heading.php');
    echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
    header( "Refresh:3; url=account.php", true, 303);
}

显示图像的代码:

while($row = mysql_fetch_row($result)) {
    echo "<tr>";
    echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
    echo "</tr>\n";
}

如果您的 $_GET[] 请求不安全: 只需执行这些步骤:

1) 假设 Url = localhost/hungry.com?id=1

2) 在 url 的末尾添加 ' 例如:localhost/hungry.com?id=1' 如果它给出错误那么你的 $_GET[] 是不安全的

3) 假设您的 get var 是这样的:$piid=$_GET['piid'];就做这个:

$piid=(int)($_GET['piid']);只需添加 (int) 然后

4) 在 url 的末尾添加 ' 例如:localhost/hungry.com?id=1' 你不会收到任何错误这意味着你的 $_GET[] 现在是安全的