2013-10-06 73 views
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 fuck"; 
      require 'notfound.php'; 
      die(); 
     } 
    } 
} 

HTML & PHP代碼:

​​
+0

是的,我做到了這一點,以防萬一我得到一個錯誤,那我怎麼知道什麼部分搞亂 – ThinkkSo

+2

你應該連接表而不是做2個查詢。 – vikingmaster

+0

@Jari我會,但如果查詢1失敗它會導致其他而不是2查詢 – ThinkkSo

回答

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

此代碼應該是安全的。它還應該檢查相關的代碼是否有錯誤。

相關問題