2014-10-16 96 views
0

我使用這個代碼圖片上傳:PHP文件上傳缺少的文件擴展名

$target_dir = "../uploads/"; 
$uploadOk=1; 

$newname = $target_dir .'file_' . rand(0, 1000000) . '.' . end(explode(".", $_FILES["vimage1"]["name"])); 

if (move_uploaded_file($_FILES["vimage1"]["tmp_name"], $newname)) { 
    echo "The file ". basename($_FILES["vimage1"]["name"]). " has been uploaded."; 
} 

else { 
    echo "Sorry, there was an error uploading your file."; 
} 

的神祕之處在於我使用一個功能相同的代碼和所有的偉大工程。

我已經然後複製相同的代碼來第二功能和一些奇怪的原因,我不斷收到上傳錯誤,因爲文件擴展名是從$newname丟失。

任何人有,爲什麼這可能是發生什麼想法?

+0

顯示更改前後的功能 – Etixpp 2014-10-16 10:51:42

+1

我寧願使用'pathinfo($ _ FILES [「vimage1」] [「name」],PATHINFO_EXTENSION)'獲得擴展名 – halloei 2014-10-16 10:53:23

+0

另外,請提供表單的代碼用於上傳兩種不同的功能。 – Dencker 2014-10-16 10:54:04

回答

0

你可以用這個做的工作:

<?php 
function upload($index,$destination,$maxsize=FALSE,$extensions=FALSE) 
{ 
    if (!isset($_FILES[$index]) OR $_FILES[$index]['error'] > 0) return FALSE; 

    if ($maxsize !== FALSE AND $_FILES[$index]['size'] > $maxsize) return FALSE; 
    // extension 
    $ext = substr(strrchr($_FILES[$index]['name'],'.'),1); 
    if ($extensions !== FALSE AND !in_array($ext,$extensions)) return FALSE; 
/
    return move_uploaded_file($_FILES[$index]['tmp_name'],$destination); 
} 

//EXEMPLES 
    $upload1 = upload('icone','uploads/monicone1',15360, array('png','gif','jpg','jpeg')); 
    $upload2 = upload('mon_fichier','uploads/file112',1048576, FALSE); 

    if ($upload1) "Successfully uploaded<br />"; 
    if ($upload2) "Failure in uploading!<br />"; 
?> 
0

無法使用/上運行時間在end()傳遞數組/變量。你必須先爆炸的文件名,然後將它傳遞。像這樣的東西。

$proposedExtension = explode(".", $_FILES["vimage1"]["name"]); 
$extension = end($imageExtension); 
$newname = $target_dir .'file_' . rand(0, 1000000) . '.'.$extension; 
echo $newname; 

最好用pathinfo($_FILES["vimage1"]["name"], PATHINFO_EXTENSION)來獲得文件的擴展名。