2016-03-28 194 views
0

我有一個腳本來上傳圖片..它工作正常,並給圖像名稱image1.png。php圖片上傳擴展

我現在面臨的問題是,我只能上傳PNG圖像,我需要能夠上傳各種圖像。 我知道我必須得到分機。但我無法讓它工作。

這裏是腳本

<?php $target_dir = "images2/"; 
$target_file = $target_dir . ("image1.png"); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 

// Check if image file is a actual image or fake image 
if(isset($_POST["submit"])) { 
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); 
if($check !== false) { 
    echo "File is an image - " . $check["mime"] . "."; 
    $uploadOk = 1; 
} else { 
    echo "File is not an image."; 
    $uploadOk = 0; 
} 
} // Check if file already exists 
if (file_exists($target_file)) { 
echo "Sorry, file already exists."; 
$uploadOk = 0; 
} 
// Check file size 
if ($_FILES["fileToUpload"]["size"] > 500000) { 
echo "Sorry, your file is too large."; 
$uploadOk = 0; 
} 
// Allow certain file formats 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
&& $imageFileType != "gif") { 
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
$uploadOk = 0; 
} 
// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) { 
echo "Sorry, your file was not uploaded."; 
// if everything is ok, try to upload file 
} else { 
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
    echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
} else { 
    echo "Sorry, there was an error uploading your file.";}} 
    ?> 
+1

在檢查文件格式時,您需要測試OR,而不是AND。 –

回答

0

從你上傳腳本

// Allow certain file formats 
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" 
&& $imageFileType != "gif") { 
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
$uploadOk = 0; 
} 

刪除下面的代碼,並設置$uploadOk=1;或沒有必要設置。

可能會幫助你。

0

如果條件U僅可以使用以下條件

if($imageFileType != "png" ) { 
    echo "</br>Sorry, only PNG files are allowed."; 
    $uploadOk = 0; } 
+0

OP要*允許所有圖像類型。 ($ imageFileType!=「jpg」|| $ imageFileType!=「png」|| $ imageFileType!=「jpeg」 || $ imageFileType!=「 –

+0

在這種情況下,如果條件代碼 –

+0

使用此代碼, gif「){ echo」對不起,只允許JPG,JPEG,PNG和GIF文件。「; $ uploadOk = 0; } –

0

更新這一行: if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif") {

,並刪除$uploadOk

2

可能是更好的測試,看看如果圖像擴展在一個數組中。更短的代碼,少的問題:

$imgExt = array('jpg','png','jpeg','gif'); 
if(!in_array($imageFileType, $imgExt)) { 
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; 
    $uploadOk = 0; 
} 

PHP in_aray()

0

你可以使用上傳文件的擴展名的目標文件:

的$ TARGET_FILE變量不包含擴展名:

$target_file = $target_dir . ("image1."); 

它被添加在最後:

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file.$imageFileType)) {