2011-01-29 47 views
0

所以我只是學習PHP,並試圖讓它可以上傳圖片。當在本地主機上嘗試這樣做時,我所得到的只是一張紙被撕成兩半的圖片(它必須是一些錯誤/替換圖片)。該圖像的目錄是正確的,它只是沒有正確顯示。 感謝用php的問題上傳圖片?

代碼:

<?php 
//connect to the database 
$link = mysql_connect("localhost", "root", "root") 
    or die("Could not connect: " . mysql_error()); 
mysql_select_db("images", $link) 
    or die (mysql_error()); 

//make variables available 
$image_caption = $_POST['image_caption']; 
$image_username = $_POST['image_username']; 
$image_tempname = $_FILES['image_filename']['name']; 
$today = date("Y-m-d"); 

//upload image and check for image type 
//make sure to change your path to match your images directory 
$ImageDir ="/Users/JohnSmith/Desktop/images/"; 
$ImageName = $ImageDir . $image_tempname; 

if (move_uploaded_file($_FILES['image_filename']['tmp_name'], 
        $ImageName)) { 

    //get info about the image being uploaded 
    list($width, $height, $type, $attr) = getimagesize($ImageName); 

     switch ($type) { 
    case 1: 
     $ext = ".gif"; 
     break; 
    case 2: 
     $ext = ".jpg"; 
     break; 
    case 3: 
     $ext = ".png"; 
     break; 
    default: 
     echo "Sorry, but the file you uploaded was not a GIF, JPG, or " . 
      "PNG file.<br>"; 
     echo "Please hit your browser's 'back' button and try again."; 
    } 

    //insert info into image table 

    $insert = "INSERT INTO images 
      (image_caption, image_username, image_date) 
      VALUES 
      ('$image_caption', '$image_username', '$today')"; 
    $insertresults = mysql_query($insert) 
    or die(mysql_error()); 

    $lastpicid = mysql_insert_id(); 

    $newfilename = $ImageDir . $lastpicid . $ext; 

    rename($ImageName, $newfilename); 

} 

?> 

<html> 
<head> 
<title>Here is your pic!</title> 
</head> 
<body> 

<p>Here is the picture you just uploaded to our servers:</p> 
<img src="Users/AdamAshwal/Desktop/images/<?php echo $lastpicid . $ext; ?>" align="left"> 
<strong><?php echo $image_name; ?></strong><br> 
This image is a <?php echo $ext; ?> image.<br> 
It is <?php echo $width; ?> pixels wide 
and <?php echo $height; ?> pixels high.<br> 
It was uploaded on <?php echo $today; ?>. 
</body> 
</html> 
+2

您將需要顯示一些代碼。 –

+0

圖像存儲在桌面上的正確文件夾中,我似乎無法讓它顯示在瀏覽器中。 –

回答

1

圖像沒有被顯示,因爲你的桌面是不是公共根目錄。在您的應用程序中創建一個目錄以存儲上傳的圖像並從那裏呈現它們。

JMC Creative's answer也是正確的 - 您的圖片標籤似乎沒有在上傳圖片的正確位置。

在附註中,您提供的代碼示例中有一個非常明顯的SQL注入漏洞。所有存儲在數據庫中的用戶輸入都應該用mysql_real_escape_string進行消毒。有關幽默的解釋,請參閱this XKCD comic。示例如下:

$image_caption = mysql_real_escape_string($_POST['image_caption']); 
0

應該不是你的圖片src是:

<img src="/Users/JohnSmith/Desktop/images/<?php echo $lastpicid . $ext; ?>"> 

的SRC應該是相對於其中的腳本。

而且不要在html標記中使用align="left",請使用css。