向用户展示他们照片的最佳方式

时间:2013-10-06 21:04:26

标签: php html mysql

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

url:

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>

1 个答案:

答案 0 :(得分:1)

这就是我用PDO和异常风格的方式:

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;
}

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