0

好的,所以我想知道向用户展示他们自己的照片的最佳方式是什么,以及我的方式是否安全或者我应该改变什么。

网址:

http://localhost/project/everyone/myphoto.php?num=2

php代码:

$user_id = $_SESSION['user_id'];

if (isset($_GET['num'])) {
    $num = $_GET['num'];

    if ($stmt = $dbconn->prepare("SELECT 1 FROM t_photos WHERE id ='$num' AND user_id ='$user_id' LIMIT 1")) {
        $stmt->execute();
        $stmt->store_result();

        $rows = $stmt->num_rows;
        if ($rows === 1) {
            $stmt = $dbconn->prepare("SELECT url,uploaddate FROM t_photos WHERE id = ?");
        $stmt->bind_param('i', $num); // Bind "$email" to parameter.
        $stmt->execute(); // Execute the prepared query.
        $stmt->store_result();
        $stmt->bind_result($photopath, $uploadtime); // get variables from result.
        $stmt->fetch();
        } else {
            $error2 = "Error 2";
            require 'notfound.php';
            die();
        }
    }
}

html & PHP 代码:

<div id="pathwrap">
    <div class="photowrap">
        <?php if (isset($photopath)) {
        echo '<img src="' . $photopath . '">';
        } ?>
    </div>
</div>
4

1 回答 1

1

这就是我使用 PDO 和 Exception 样式的方法:

function requestCurrentUserPhoto(){
if( !isset($_GET['num']) ){
    throw new Exception('Bad request. The generated link missing get prop num.');
}
if( !isset($_SESSION['user_id']) ){
    throw new Exception('Bad request. The generated link linked to a guest.');
}
$sth = $dbh->prepare('SELECT url,uploaddate FROM t_photos WHERE id = :id AND user_id = :user_id LIMIT 1');
$sth->execute(array(
    ':id' => (int) $_GET['num'],
    ':user_id' => (int) $_SESSION['user_id']
));
$result = $sth->fetch(PDO::FETCH_ASSOC);
if( $result === false ){
    throw new Exception('Bad request. The generated link linked to a non-existence photo or unauthorized user.');
}
//optional...
if( empty($result['url']) || empty($result['uploaddate']) ){
    throw new Exception('Bad database table row. There is a invalid photo row in t_photos');
}
return $result;
}

这段代码应该是安全的。它还应该检查相关代码是否有任何错误。

于 2013-10-07T00:23:35.600 回答