Html-форма сайта с вложенным изображением… не могу получить вложение по электронной почте

0

Я пытаюсь создать форму, в которой пользователь может загрузить свой собственный образ через форму контакта с веб-сайтом... однако я могу получить входные формулировки, но не вложение... может ли кто-нибудь указать на ошибку?

//Settings 
$max_allowed_file_size = 10000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp");
$upload_folder = './uploads/'; //<-- this folder must be writeable by the script
$your_email = '[email protected]';//<<--  update this to your email address

$errors ='';

if(isset($_POST['submit']))
{
  //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;

  ///------------Do Validations-------------
  if(empty($_POST['name'])||empty($_POST['email']))
  {
      $errors .= "\n Name and Email are required fields. ";   
  }
  if(IsInjected($visitor_email))
  {
      $errors .= "\n Bad email value!";
  }

  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);
  }

  //send the email 
  if(empty($errors))
  {
      //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';
          }
      }

  }}
  ?>




      //send the email
       <?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//define the receiver of the email
$to = '[email protected]';
//define the subject of the email
$subject = 'Decor';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: [email protected]\r\nReply-To: [email protected]";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('./uploads/'.$_POST[$path_of_uploaded_file])));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

Name: <?php echo $_POST['name']; ?>
Email: <?php echo $_POST['email']; ?>
Picture Name: <?php echo $_POST['picname']; ?>
Description: <?php echo $_POST['description']; ?>

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 7bit

Name: <?php echo $_POST['name']; ?><br/>
Email: <?php echo $_POST['email']; ?><br/>
Picture Name: <?php echo $_POST['picname']; ?><br/>
Description: <?php echo $_POST['description']; ?><br/>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: data:image/jpg; name="photo.jpg " 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$sent = mail($to, $subject, $message, $headers) ;

    if ($sent) {
      header("Location: http://www.tcc.hk/vday2014/thanks.php");
      exit();
    } else {
      print "We encountered an error sending your mail"; 
    }




}
?>

<?
///////////////////////////Functions/////////////////
// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
<head>
  <title>File upload form</title>
<!-- define some style elements-->
<style>
label,a, body 
{
  font-family : Arial, Helvetica, sans-serif;
  font-size : 12px; 
}

</style>  
<!-- a helper script for vaidating the form-->
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>  
</head>

<body>
<?php
if(!empty($errors))
{
  echo nl2br($errors);
}
?>
<form method="POST" name="email_form_with_php" 

onsubmit="return validateForm()"

> 
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<p>
<label for='uploaded_file'>Select A File To Upload:</label> <br>
<input type="file" name="uploaded_file">
</p>
<input type="submit" value="Submit" name='submit'>
</form>
<script language="JavaScript">
// Code for validating the form
// Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
// for details
var frmvalidator  = new Validator("email_form_with_php");
frmvalidator.addValidation("name","req","Please provide your name"); 
frmvalidator.addValidation("email","req","Please provide your email"); 
frmvalidator.addValidation("email","email","Please enter a valid email address"); 
</script>
<noscript>
<small><a href='http://www.html-form-guide.com/email-form/php-email-form-attachment.html'
>How to attach file to email in PHP</a> article page.</small>
</noscript>

</body>
</html>

Форма (тот же документ)

<form method="POST" name="email_form_with_php" 

onsubmit="return validateForm()"

> 
<p>
<label for='name'>Name: </label><br>
<input type="text" name="name" >
</p>
<p>
<label for='email'>Email: </label><br>
<input type="text" name="email" >
</p>
<p>
<label for='message'>Message:</label> <br>
<textarea name="message"></textarea>
</p>
<p>
<label for='uploaded_file'>Select A File To Upload:</label> <br>
<input type="file" name="uploaded_file">
</p>
<input type="submit" value="Submit" name='submit'>
</form>
Теги:
base64

2 ответа

1

Установите атрибут enctype в вашей форме на "multipart/form-data". В противном случае поля файла не работают.

  • 0
    ммм ... все еще не могу получить вложение .... мне интересно, это из-за этого .. $ attachment = chunk_split (base64_encode (file_get_contents (' tcc.com/vday2014/test/uploads/… )));
  • 0
    Могу я спросить, почему вы не используете что-то вроде PHPMailer или SwiftMailer, который обрабатывает все эти записи заголовков для вас? Это сделало бы работу намного проще для кодирования, а еще лучше - для отладки.
0

В вашей форме вам нужно добавить enctype="multipart/form-data"

Итак, т.е.:

<form method="POST" name="email_form_with_php" 
enctype="multipart/form-data"
onsubmit="return validateForm()"
> 
  • 0
    ммм ... все еще не могу получить вложение .... мне интересно, это из-за этого .. $ attachment = chunk_split (base64_encode (file_get_contents (' tcc.com/vday2014/test/uploads/… )));

Ещё вопросы

Сообщество Overcoder
Наверх
Меню