2012-04-22 75 views
1

我想用PHP上傳文件。我寫了無法在PHP中進行文件上傳

<form target="_self" enctype="multipart/form-data"> 
<input type="file" name="file" id="file" /> 
<input name="submit" type="submit" value="submit" /> 
</form> 
<?php 

if ($_FILES["file"]["error"] > 0) 
    { 
    echo "Error: " . $_FILES["file"]["error"] . "<br />"; 
    } 
else 
    { 
    echo "Upload: " . $_FILES["file"]["name"] . "<br />"; 
    echo "Type: " . $_FILES["file"]["type"] . "<br />"; 
    echo "Size: " . ($_FILES["file"]["size"]/1024) . " Kb<br />"; 
    echo "Stored in: " . $_FILES["file"]["tmp_name"]; 
    } 

?> 

但它不工作。文件對我來說是不可見的,他們要去哪裏?

回答

4

您是從一個工作腳本

很長的路要走,您可以嘗試

<?php 
$output = array(); 
$errors = array(); 
$savePath = "uploaded"; // PATH to upload images 
$allowedExt = array (
     "png", 
     "jpg" 
); 
if (isset ($_FILES ['file']) && $_FILES ["file"] ["error"] == UPLOAD_ERR_OK) { 

    $fileName = $_FILES ['file'] ['name']; 
    $fileSize = $_FILES ['file'] ['size']; 
    $fileTemp = $_FILES ['file'] ['tmp_name']; 
    $fileType = $_FILES["file"]["type"] ; 
    $fileExt = pathinfo ($fileName, PATHINFO_EXTENSION); 
    $fileExt = strtolower ($fileExt); 

    //var_dump($fileExt); 

    if (!in_array ($fileExt, $allowedExt)) { 
     $errors [] = "Invalid File Extention"; 
    } 

    if ($fileSize > 800*1024) { 
     $errors [] = "File Too large"; 
    } 

    if (! is_writable ($savePath)) { 
     $errors [] = "File Destination not writeable"; 
    } 

    $fileDst = $savePath . DIRECTORY_SEPARATOR . $fileName; 
    $filePrifix = basename ($fileName, "." . $fileExt); 
    $i = 0; 
    while (file_exists ($fileDst)) { 
     $i ++; 
     $fileDst = $savePath . DIRECTORY_SEPARATOR . $filePrifix . "_" . $i . "." . $fileExt; 

    } 
    if (count ($errors) == 0) { 
     if (@move_uploaded_file ($fileTemp, $fileDst)) { 
      $output['STATUS'] = "OK"; 
      $output['TYPE'] = $fileType; 
      $output['Size'] = $fileSize; 
      $output['Destination'] = $fileDst; 
     } else { 
      $errors [] = "Error Saving File"; 
     } 

    } 


    if(count($errors) > 0) 
    { 
     echo "<h2>Upload Error</h2>" ; 

     foreach ($errors as $error) 
     { 
      echo $error , "<br/>" ; 

     } 
    } 
    else 
    { 
     echo "<h2>File Uploaded</h2>" ; 
     foreach ($output as $key => $value) 
     { 
      echo $key , ":" , $value , "<br/>" ; 
     } 

    } 
} 

?> 
<br/> 
<br /> 
<form method="post" target="_self" enctype="multipart/form-data"> 
    <input type="file" name="file" id="file" /> <input name="submit" 
     type="submit" value="submit" /> 
</form> 
+0

這是不安全的,因爲我的網站被黑了。 – 2012-09-27 10:49:14

+0

@Christian Nikkanen這個上傳不是爲了檢測假圖片......你必須真的是忘恩負義的人 – Baba 2012-09-27 10:50:52

+0

這將是很好的說,它可以很容易地被黑客入侵。 – 2012-09-27 11:11:39

3

你的代碼甚至沒有接近工作,因爲你實際上沒有通過PHP來上傳任何文件。我建議從PHP file upload tutorialmore)開始並重試。如果您的新代碼有任何問題,請尋求幫助,並向我們展示您遇到問題的代碼。

+0

tizag的代碼是不工作的文件上傳。 – Thompson 2012-04-22 17:44:19

0

您需要使用POST方法才能使文件上傳正常工作。
因此,只需將method="post"屬性添加到form標記即可完成。