2013-04-09 110 views
0

我正在使用getimagesize驗證圖像類型,但不知道如何爲多個文件編寫腳本。基本上,我有一個表單,允許上傳多個圖像文件,如下圖。getimagesize()期望參數1是字符串,數組給出

<input type="file" name="photo[]" class="file" /> 
    <input type="file" name="photo[]" class="file" /> 
    <input type="file" name="photo[]" class="file" /> 

然後我用這來驗證它,並通過PHPMailer的發送。

<?php 
ob_start(); 
require("class.phpmailer.php"); 

$errors = array(); 

if ('POST' === $_SERVER['REQUEST_METHOD']) 
{ 
    $firstname   = sanitize($_POST['firstname']); 
    $lastname   = sanitize($_POST['lastname']); 
    $email     = sanitize($_POST['email']); 

    if (empty($firstname)) 
    { 
     $errors['firstname'] = "Please provide first name."; 
    } 
    if (empty($lastname)) 
    { 
     $errors['lastname'] = "Please provide last name."; 
    } 
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) 
    { 
     $errors['email'] = "Please provide a valid email address."; 
    } 

    if (count($errors) === 0) 
    { 


$imageinfo = array(); 
    $my_files = $_FILES['photo']['tmp_name']; 
    foreach($my_files as $single_file) { 
    if(!empty($single_file)) { 
    $imageinfo[$single_file] = getimagesize($single_file); 
    if ($single_file['mime'] != 'image/png' && $single_file['mime'] != 'image/jpeg') 
    { echo "Invalid Image File"; 
    exit(); 
    } } 
    } 


foreach($_FILES['photo']['tmp_name'] as $photo) 
if(!empty($photo)) { 
$mail->AddAttachment($photo); 


$message = 'some message'; 

$mail = new PHPMailer(); 

$mail->SetFrom($email); 
$mail->AddAddress($from); 

$mail->Subject = "Submitted"; 
$mail->Body  = $message; 
$mail->WordWrap = 50; 
} 

$mail->Send(); 

header("Location: thankyou.php"); 
exit();  
}} 

function sanitize($value) 
{ 
    return trim(strip_tags($value, $problem='')); 
} 
?> 

我收到錯誤消息警告:和getimagesize()預計參數1是字符串數組給定我知道這是因爲我的樣子將一個陣列。如何將腳本更改爲適用於多個文件/數組?請幫忙。謝謝。

+0

你能'回聲'

' . print_r($_FILES, true) . '
';'只是爲了檢查FILES結構? – MatRt 2013-04-09 05:12:16

回答

3

$_FILES['photo']['tmp_name']有多個文件,所以它是一個數組。

getimagesize()旨在只接受一個文件。

,所以你需要將每個文件傳遞給函數

$imageinfo = array(); 
$my_files = $_FILES['photo']['tmp_name']; 
foreach($my_files as $single_file) { 
    if(!empty($single_file)) { 
    $imageinfo[$single_file] = getimagesize($single_file); 
    } 
} 

print_r($imageinfo); // now you have info of all files in an array. 

,或者你可以嘗試

$imageinfo0 = getimagesize($_FILES['photo']['tmp_name'][0]); 
$imageinfo1 = getimagesize($_FILES['photo']['tmp_name'][1]); 
$imageinfo2 = getimagesize($_FILES['photo']['tmp_name'][2]); 

....等..

+0

打印看起來像文件附加,但它給錯誤**警告:getimagesize()[function.getimagesize]:文件名不能爲空**我需要它只需要1上傳。如果其他人沒有任何東西上傳可以發送電子郵件。我怎麼做? thx非常感謝你的幫助。 – 2013-04-09 05:36:54

+0

嗨..我做了一個編輯。添加。一個空值檢查。 – Dino 2013-04-09 05:40:43

+0

我改變了我的問題編輯的代碼。但是即使當我附加一個pdf文件並且在電子郵件天氣中沒有附件時,它也不會給出任何消息我附上圖像或非圖像。我做錯了什麼?請幫忙。謝謝。 – 2013-04-09 07:50:24

相關問題