2012-05-19 3 views
3

Я хотел бы указать, прежде чем я получу в этом, что я PHP newb, и я некоторое время боролся с этим, прежде чем окончательно решить, что я не знаю, что я Я делаю с этим. Я не думаю, что я что-то ошибся или неправильно капитализировал, как this guy, но, пожалуйста, простите мой грязный код.PHP: Имя файла не может быть пустым в file_get_contents

<?php 
$field_name = $_POST['name']; 
$field_email = $_POST['email']; 
$field_comment = $_POST['comment']; 
$field_question = $_POST['question']; 
$field_support = $_POST['support']; 
$field_steam = $_POST['steam']; 
$field_file = $_POST['file']; 
$field_message = $_POST['message']; 
//Get the uploaded file information 
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']); 
//get the file extension of the file 
$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1); 
$size_of_uploaded_file = $_FILES["uploaded_file"]["size"]/1024;//size in KBs 
//Settings 
$max_allowed_file_size = 10000; // size in KB 
$allowed_extensions = array("doc", "docx", "txt", "pdf", "rtf", "otf"); 
//Validations 
if($size_of_uploaded_file > $max_allowed_file_size) 
{ 
$errors .= "\n Size of file should be less than  $max_allowed_file_size"; 
} 
//------ Validate the file extension ----- 
$allowed_ext = false; 
for($i=0; $i<sizeof($allowed_extensions); $i++) 
{ 
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0) 
{ 
$allowed_ext = true; 
} 
} 
if(!$allowed_ext) 
{ 
$errors .= "\n The uploaded file is not supported file type. ". 
" Only the following file types are supported: ".implode(',',$allowed_extensions); 
} 

//copy the temp. uploaded file to uploads folder 
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; 
$tmp_path = $_FILES["uploaded_file"]["tmp_name"]; 
if(is_uploaded_file($tmp_path)) 
{ 
if(!copy($tmp_path,$path_of_uploaded_file)) 
{ 
$errors .= '\n error while copying the uploaded file'; 
} 
} 

$to = '[email protected]'; 
$subject = 'Contact Form Message from '.$field_name; 
$attachment = chunk_split(base64_encode(file_get_contents($path_of_uploaded_file))); 

$boundary = md5(date('r', time())); 

$body_message = 'From: '.$field_name."\n"; 
$body_message .= 'E-mail: '.$field_email."\n"; 
$body_message .= 'Message Type: '." "; 
$body_message .= ''.$field_comment." "; 
$body_message .= ''.$field_question." "; 
$body_message .= ''.$field_support." "; 
$body_message .= ''.$field_steam."\n"; 
$body_message .= 'Message: '.$field_message; 



$headers = 'From: '.$field_email."\r\n"; 
$headers .= 'Reply-To: '.$field_email."\r\n"; 
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$boundary."\""; 

$mail_status = mail($mail_to, $subject, $attachment, $body_message, $headers); 

if ($mail_status) { ?> 
<script language="javascript" type="text/javascript"> 
alert('Thank you for the message. We will contact you shortly.'); 
window.location = 'contact.html'; 
</script> 
<?php 
} 
else { ?> 
<script language="javascript" type="text/javascript"> 
alert('Message failed. Please, send an email to [email protected]'); 
window.location = 'contact.html'; 
</script> 
<?php 
} 
?> 

И я получаю эту ошибку:

Внимание: file_get_contents() [function.file-получить содержание]: Имя файла не может быть пустым в /%ROOT%/contact.php на линии 57

Мои вопросы: что я делаю неправильно, пытаясь передать загруженный файл в виде вложения? И почему файл $ path_of_uploaded_file кажется пустым? Кроме того, не все будут загружать файлы, так как я могу разрешить отправку?

+0

вы, кажется, не определили '$ upload_folder' в коде, при условии, прежде чем использовать его в этой строке:' $ path_of_uploaded_file = $ upload_folder. $ name_of_uploaded_file; ' –

+0

. Вы должны прочитать этот документ о загрузке и перемещении/подтверждении загрузки файлов: http://www.php.net/manual/en/features.file-upload.post-method.php –

ответ

1

Решил идти об этом по-разному и чище.

<?php 
//start session 
session_start(); 

// prints form 
function print_form(){ 
?> 

<form method="post" action="<?php echo $_SERVER[’PHP_SELF’];?>" id="uploadform" enctype="multipart/form-data"> 
<input name="name" id="name" type="text" style="border: none;background-color: transparent;background-image: url(images/text_field.png);width: 418px;height: 48px;padding-left: 15px;background-repeat: no-repeat;background-size: 450px 48px;padding-right: 13px;" class="field" value="Name" tabindex="1"/></p> 
<p> 
<input name="email" id="email" type="text" style="border: none;background-color: transparent;background-image: url(images/text_field.png);width: 418px;height: 48px;padding-left: 15px;background-repeat: no-repeat;background-size: 450px 48px;padding-right: 13px;float:right;margin-top: -65px;" class="field" value="Email" tabindex="2"/> 
</p> 
<p> 
<table width="950" style="padding-top: 10px;text-align: center;"><tr><td width="115"><input name="comment" type="checkbox" value="Comment" /> Comment </td><td width="119"><input name="question" type="checkbox" value="Question" /> Question </td><td width="139"><input name="support" type="checkbox" value="Support" /> Support </td><td width="171"><input name="steam" type="checkbox" value="Street Team" /> Street Team</td><td width="382"><input type="hidden" name="MAX_FILE_SIZE" value="2048"><span style=";margin-left: -180px;">Resume : </span><br /> 
<span style="font-size:9px;margin-left: -180px;">1 file only, max file size 2 MB.</span><br /><span style="font-size:9px;margin-left: -180px;">Allowed file formats are </span><br /><span style="font-size:9px;margin-left: -180px;">.doc, .docx, .txt, .pdf, .rtf, .otf</span><br /></label> 
<input name="attachment" id="attachment" style="position: absolute;margin-left: 100px;margin-top: -40px;" type="file" tabindex="7"></td></tr></table><br /> 
<textarea name="comments" id="comments" style="background-color: #fff;width: 922px;height: 172px;padding-left: 10px;background-repeat: no-repeat;padding-top:8px;resize:none;border-color: #CCC;padding-right: 15px;border-width: 2px;margin-left: 7px;border-radius: 1em;box-shadow: inset #EEE 0.25em 0.25em 0.3em;" rows="" cols="" class="field" tabindex="6">Message 
</textarea> 
</p> 
<p> 
<p><input type="submit" name="submit" id="submit" style="width: 112px;height: 32px;background-image: url(images/submit.png);color: transparent;border: none;background-repeat: no-repeat;background-position: -5px;float: right;" value="Send" tabindex="8"/></p> 
<p><input type="hidden" name="submitted" value="true" /></p> 
</form> 
<?php 
} 

// enquiry form validation 

function process_form() { 
// Read POST request params into global vars 
$to = "[email protected]"; 

$name = trim($_POST['name']); 
$email = trim($_POST['email']); 
$comment = trim($_POST['comment']); 
$question = trim($_POST['question']); 
$support = trim($_POST['support']); 
$steam = trim($_POST['steam']); 
$comments = trim($_POST['comments']); 
$from = $email; 
$subject = 'Contact Form Message From '.$name; 

// Allowed file types. add file extensions WITHOUT the dot. 
$allowtypes=array("doc", "docx", "txt", "pdf", "rtf", "otf"); 

// Require a file to be attached 
$requirefile="true"; 

// Maximum file size for attachments in KB NOT Bytes for simplicity. MAKE SURE your php.ini can handle it 
// post_max_size, upload_max_filesize, file_uploads, max_execution_time! 
$max_file_size="2048"; 

// Thank you message 
$thanksmessage="Your message has been sent, we will respond as soon as possible."; 

$errors = array(); //Initialize error array 

//checks for a name 
if (empty($_POST['name'])) { 
$errors[]='Please enter your name.'; 
} 

//checks for an email 
if (empty($_POST['email'])) { 
$errors[]='Please enter your email.'; 
} else { 

if (!eregi ('^[[:alnum:]][a-z0-9_\.\-]*@[a-z0-9\.\-]+\.[a-z]{2,4}$', stripslashes(trim($_POST['email'])))) { 
$errors[]='Please enter a valid email address.'; 
} // if eregi 
} // if empty email 


//checks for a message 
if (empty($_POST['comments'])) { 
$errors[]='Did you want to tell us something?'; 
} 

// checks for required file 
//if($requirefile=="true") { 
// if($_FILES['attachment']['error']==4) { 
//  $errors[]='You forgot to attach a file'; 
// } 
//} 

//checks attachment file 
// checks that we have a file 
if((!empty($_FILES["attachment"])) && ($_FILES['attachment']['error'] == 0)) { 
// basename -- Returns filename component of path 
$filename = basename($_FILES['attachment']['name']); 
$ext = substr($filename, strrpos($filename, '.') + 1); 
$filesize=$_FILES['attachment']['size']; 
$max_bytes=$max_file_size*1024; 

//Check if the file type uploaded is a valid file type. 
if (!in_array($ext, $allowtypes)) { 
$errors[]="Invalid extension for your file: <strong>".$filename."</strong>"; 

// check the size of each file 
} elseif($filesize > $max_bytes) { 
$errors[]= "Your file: <strong>".$filename."</strong> is too big. Max file size is ".$max_file_size."kb."; 
} 

} // if !empty FILES 

if (empty($errors)) { //If everything is OK 

// send an email 
// Obtain file upload vars 
$fileatt  = $_FILES['attachment']['tmp_name']; 
$fileatt_type = $_FILES['attachment']['type']; 
$fileatt_name = $_FILES['attachment']['name']; 

// Headers 
$headers = "From: $email"; 

// create a boundary string. It must be unique 
$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

// Add the headers for a file attachment 
$headers .= "\nMIME-Version: 1.0\n" . 
"Content-Type: multipart/mixed;\n" . 
" boundary=\"{$mime_boundary}\""; 

// Add a multipart boundary above the plain message 
$message ="This is a multi-part message in MIME format.\n\n"; 
$message.="--{$mime_boundary}\n"; 
$message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n"; 
$message.="Content-Transfer-Encoding: 7bit\n\n"; 
$message.="From: ".$name."\n"; 
$message.="Email: ".$email."\n"; 
$message .= 'Message Type: '." "; 
$message .= ''.$comment." "; 
$message .= ''.$question." "; 
$message .= ''.$support." "; 
$message .= ''.$steam."\n"; 
$message.="Message: ".$comments."\n\n"; 

if (is_uploaded_file($fileatt)) { 
// Read the file to be attached ('rb' = read binary) 
$file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

// Base64 encode the file data 
$data = chunk_split(base64_encode($data)); 

// Add file attachment to the message 
$message .= "--{$mime_boundary}\n" . 
"Content-Type: {$fileatt_type};\n" . 
" name=\"{$fileatt_name}\"\n" . 
//"Content-Disposition: attachment;\n" . 
//" filename=\"{$fileatt_name}\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . 
$data . "\n\n" . 
"--{$mime_boundary}--\n"; 
} 


// Send the completed message 

$envs = array("HTTP_USER_AGENT", "REMOTE_ADDR", "REMOTE_HOST"); 
foreach ($envs as $env) 
$message .= "$env: $_SERVER[$env]\n"; 

if(!mail($to,$subject,$message,$headers)) { 
exit("Mail could not be sent. Sorry! An error has occurred, please email [email protected]\n"); 
} else { 
echo '<div id="formfeedback"><h3>Thank You!</h3><p>'. $thanksmessage .'</p></div>'; 
unset($_SESSION['myForm']); 
print_form(); 

} // end of if !mail 

} else { //report the errors 
echo '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) have occurred:<br />'; 
foreach ($errors as $msg) { //prints each error 
echo " - $msg<br />\n"; 
} // end of foreach 
echo '</p><p>Please correct the errors and try again.</p></div>'; 
print_form(); 
} //end of if(empty($errors)) 

} // end of process_form() 
?> 
4

$_FILES['uploaded_file']['name'] только имя файла с момента, когда пользователь выбирает его для загрузки
$_FILES['uploaded_file']['tmp_name'] является файл, который был загружен на сервер.
Php Post File Uploads

1

Это делает то, что вы хотите? (Я сделал некоторые небольшие изменения, но без формы представления я не был в состоянии проверить.)

<?php 
$field_name = $_POST['name']; 
$field_email = $_POST['email']; 
$field_comment = $_POST['comment']; 
$field_question = $_POST['question']; 
$field_support = $_POST['support']; 
$field_steam = $_POST['steam']; 
$field_file = $_POST['file']; 
$field_message = $_POST['message']; 

$errors = ''; 

//Get the uploaded file information 
$upload_folder = '/path/to/file/'; 
$name_of_uploaded_file = basename($_FILES['file']['name']); 

//get the file extension of the file 
$type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1); 
$size_of_uploaded_file = $_FILES["file"]["size"]/1024;//size in KBs 

//Settings 
$max_allowed_file_size = 10000; // size in KB 
$allowed_extensions = array("doc", "docx", "txt", "pdf", "rtf", "otf"); 

//Validations 
if($size_of_uploaded_file > $max_allowed_file_size) 
{ 
    $errors .= "\n Size of file should be less than $max_allowed_file_size"; 
} 

//------ Validate the file extension ----- 
// could use in_array here, but its OK 
$allowed_ext = false; 
for($i=0; $i<sizeof($allowed_extensions); $i++) 
{ 
    if(strcasecmp($allowed_extensions[$i], $type_of_uploaded_file) == 0) 
    { 
     $allowed_ext = true; 
    } 
} 

if(!$allowed_ext) 
{ 
    $errors .= "\n The uploaded file is not supported file type. ". 
     " Only the following file types are supported: ".implode(',', $allowed_extensions); 
} 

//copy the temp. uploaded file to uploads folder 
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; 
$tmp_name = $_FILES["file"]["tmp_name"]; 

if(is_uploaded_file($tmp_name)) 
{ 
    if(!move_uploaded_file($tmp_name, $path_of_uploaded_file)) 
    { 
     $errors .= '\n error while copying the uploaded file'; 
    } 
} 

$mail_to = '[email protected]'; 
$subject = 'Contact Form Message from '.$field_name; 
$message = readfile($path_of_uploaded_file); 

$boundary = md5(date('r', time())); 

$additional_headers = 'From: '.$field_name."\n"; 
$additional_headers .= 'E-mail: '.$field_email."\n"; 
$additional_headers .= 'Message Type: '." "; 
$additional_headers .= ''.$field_comment." "; 
$additional_headers .= ''.$field_question." "; 
$additional_headers .= ''.$field_support." "; 
$additional_headers .= ''.$field_steam."\n"; 
$additional_headers .= 'Message: '.$field_message; 

$additional_parameters = 'From: '.$field_email."\r\n"; 
$additional_parameters .= 'Reply-To: '.$field_email."\r\n"; 
$additional_parameters .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$boundary."\""; 

$mail_status = mail($mail_to, $subject, $message, $additional_headers, $additional_parameters); 

if ($mail_status) { ?> 

    <script language="javascript" type="text/javascript"> 
     alert('Thank you for the message. We will contact you shortly.'); 
     window.location = 'contact.html'; 
    </script> 

<?php } else { ?> 

    <script language="javascript" type="text/javascript"> 
     alert('Message failed. Please, send an email to [email protected]'); 
     window.location = 'contact.html'; 
    </script> 

<?php } ?> 
+0

I я не уверен, что код, который я поставил выше, фактически будет включать вложение в электронном письме. Но уже поздно, поэтому я увижу, не будет ли это по-прежнему без ответа утром. –

+0

Нет, я получаю много странных вещей, которые происходят с этим, но я думаю, что это помогает мне приблизиться к ответу. если вы хотите протестировать интерфейс, вы можете использовать KylieKarnage

+0

При попытке создать форму кажется, что сообщение об ошибке не видит файл в/uploads /, потому что нет имени файла. Что произойдет, если вы измените строку, определяющую имя файла: $ name_of_uploaded_file = basename ($ _ FILES ['file'] ['name']); –

Смежные вопросы