2012-11-01 107 views
0

在我的網站上,我有2個獨立的地方供用戶上傳圖片。第一個完美的作品。第二個不是。據我所知,他們是完全一樣的。爲了測試,我在兩者上都使用了相同的圖像,它在第一個而不是第二個上進行。這裏是從非工作的代碼:PHP圖片未上傳到網站

<?php 
include('cn.php'); 

$name = $_FILES['image']['name']; 
$type = $_FILES['image']['type']; 
$size = $_FILES['image']['size']; 
$temp = $_FILES['image']['tmp_name']; 
$error = $_FILES['image']['error']; 

echo $name; //Doesnt echo anything 

$rand_num = rand(1, 1000000000); 

$name = $rand_num . "_" . $name; 

echo $name; //Echos just the random number followed by _ 

if ($error > 0) { 
    die("Error uploading file! Go back to the <a href='gallery.php'>gallery</a> page and try again."); 
} else { 
    $sql = "INSERT INTO gallery (image) VALUES ('".$name."')"; //Inserts the random number to the database 
    $query = mysql_query($sql) or die(mysql_error()); 
    echo $sql; 

    move_uploaded_file($temp, "gallery_pics/$name"); //Doesn't move the file. gallery_pics exists, if that matters 
    echo "Upload complete! Go back to the <a href='gallery.php'>album</a>."; 
} 

?> 

如果有人可以請幫助我在這裏。我相信這很簡單,但我還沒有找到任何有用的東西。謝謝!

編輯:上面有兩行代碼不會正確顯示。一個開始的PHP和另一個打開數據庫。

+0

這兩個地方都在同一臺服務器上? – Bgi

+0

你可以把你的HTML代碼? – George

+0

兩個文件都移動到gallery_pics?檢查該文件夾的權限。 – Bgi

回答

0

這兩個腳本都駐留在同一個目錄中嗎?如果沒有,請確保您指定正確的相對或完整路徑,通過斜線像這樣開頭:

move_uploaded_file($temp, "/some_folder/gallery_pics/$name"); 

另外,你檢查上傳的文件擴展名?例如,如果沒有,用戶可以上傳並執行PHP文件。順便說一句,你的文件名會更好看是這樣的:

$rand_num = rand(1111111111, 9999999999); 
0

制定或試圖找到故障也檢查你的服務器錯誤日誌時,啓用錯誤報告。檢查$_FILES['image']['error']錯誤代碼並相應地顯示錯誤。去下面的代碼。希望它有幫助

<?php 
//Enable error reporting 
error_reporting(E_ALL); 
ini_set('display_errors',1); 

$error_types = array(
    0=>"There is no error, the file uploaded with success", 
    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini", 
    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form", 
    3=>"The uploaded file was only partially uploaded", 
    4=>"No file was uploaded", 
    6=>"Missing a temporary folder" 
); 

if($_FILES['image']['error']==0) { 
    // process 
    $name = $_FILES['image']['name']; 
    $type = $_FILES['image']['type']; 
    $size = $_FILES['image']['size']; 
    $temp = $_FILES['image']['tmp_name']; 

    //mt_rand() = 0-RAND_MAX and make filename safe. 
    $name = mt_rand()."_".preg_replace('/[^a-zA-Z0-9.-]/s', '_', $name); 

    //insert into db, swich to PDO 
    ... 

    //Move file upload 
    if (move_uploaded_file($_FILES['image']['tmp_name'], "gallery_pics/$name")) { 
     echo "Upload complete! Go back to the <a href='gallery.php'>album</a>."; 
    } else { 
     echo "Failed to move uploaded file, check server logs!\n"; 
    } 
} else { 
    // error 
    $error_message = $error_types[$_FILES['userfile']['error']]; 
    die("Error uploading file! ($error_message)<br/>Go back to the <a href='gallery.php'>gallery</a> page and try again."); 
} 
?>