PHP:file_get_contents中的文件名不能为空

时间:2012-05-19 02:44:02

标签: php forms email server-side

我想在进入此之前指出我是一个PHP新手,我一直在努力争取一段时间,最后决定我不知道我在做什么它。我不认为我拼错了任何东西或错误地像this guy那样大写,但请原谅我凌乱的代码。

<?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 = 'me@myemail.com';
$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 me@myemail.com');
window.location = 'contact.html';
</script>
<?php
}
?>

我一直收到这个错误:

警告:file_get_contents()[function.file-get-contents]:第57行的/% ROOT%/contact.php中的文件名不能为空

我的问题是,在尝试将上传的文件作为附件传递时,我做错了什么?而且,为什么$ path_of_uploaded_file似乎是空的?此外,并非每个人都会上传文件,所以我怎么能允许提交?

3 个答案:

答案 0 :(得分:4)

$_FILES['uploaded_file']['name']只是用户选择上传文件时的文件名称 $_FILES['uploaded_file']['tmp_name']是上传到服务器的文件 Php Post File Uploads

答案 1 :(得分: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 = 'me@myemail.com';
$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 me@myemail.com');
        window.location = 'contact.html';
    </script>

<?php } ?>

答案 2 :(得分: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@email.com";

$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 info@cannysoftware.com.\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()
?>