Web form with attachment

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
greatme
Forum Newbie
Posts: 14
Joined: Fri Jul 09, 2010 10:55 am

Web form with attachment

Post by greatme »

Hi,
I have designed a web form which is functioning very well but i want my guest to be able to attach their passport photograph so that i will receive it as an attachment in the designation mail address.
Please i need a script to add to what i have to handle file attachment. my present php script is as below:

Code: Select all

<?php
require_once "Mail.php";

$from = "<username@mydomain.com>";
$to = "<username@mydomain.com>";
$username = "username@myDomain.com";
$password = "my password";
$host = "smtp.myDomain.com"; 


$email = $_POST['email'] ;
$name = $_POST['Name'] ;
$message = $_POST['Comments'];
$message .= "\n\n ";
$message .= $name;
$subject = $_POST['Subject'];

/*The message is assembled for sending */
$name = $_POST['Name'] ;
$subject = $_POST['Subject'];

$message = $_POST['Comments'];
$message .= "\n\n ";
$message .= $name . "\n";
$message .= $_POST['email'];


$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mail = $smtp->send($to, $headers, $message);

if (PEAR::isError($mail)) 
{
  echo("<p>" . $mail->getMessage() . "</p>");
} 
else 
{
	/*This is were you redirect your customers after he/she feels out the form.*/
	header("Location: thankyou.html");
 }
?>
Thanks.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Web form with attachment

Post by flying_circus »

I dont see any code to handle file uploads. What have you tried?

If you want to learn how to handle file uploads, the php manual can get you started ( http://php.net/manual/en/features.file-upload.php ). As an alternative, you will find a staggering amount of information returned by any search engine.

If you just want someone to hand you a working solution, then you need to hire a developer.
greatme
Forum Newbie
Posts: 14
Joined: Fri Jul 09, 2010 10:55 am

Re: Web form with attachment

Post by greatme »

Thanks to you flying circus,

Well this is what i have tried, though it post the form with the sign of attachment but the actual attached file is not shown. I need your help

Code: Select all

<?php

error_reporting(E_ALL - (E_NOTICE + E_WARNING));
require_once "Mail.php";

$from = "name@domain_name";
$to = "name@domain_name";
$username = "name@domain_name";
$password = "password";
$host = "smtp.domain_name";

//if there is post
if(isset($_POST) && !empty($_POST) ) {
	//if there is attachment
	if(!empty($_FILES['attachment']['name'])) {
		//store some varibles
		$file_name = $_FILES['attachment']['name'];
		$temp_name = $_FILES['attachment']['temp_name'];
		$file_type = $_FILES['attachment']['type'];
		
		//get the extention of the file
		$base = basename($file_name);
		$extension = substr($base, strlen($base)-4, strlen($base));
		
		//only these files types wil be allowed
		$allowed_extensions = array(".doc","docx",".zip", ".png", ".jpg");
		
		//check that this file type is allowed
			if(in_array($extension,$allowed_extensions)) {
			
				//mail essentials
				$subject = "Testing mail attachment";
				$message = "From the office od the Guru";
				
				//things you need
				$file = $temp_name;
				$content = chunk_split(base64_encode(file_get_contents(file)));
				$uid = md5(uniqid(time()));
				
				// standards mail headers
				$header = "From: ".$from. "\r\n";
				$header .= "Reply-To: ".$replyto. "\r\n";
				$header .= "MIME-Version: 1.0\r\n";
				
				// declaring we have multiple kinds of mails (plain text and attachment
				 $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
				 $header .= "This is a multi-part message in MIME format.\r\n";
				 
				 //plain text part
				  $header .= "--".$uid."\r\n";
				  $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
				  $header .= "Content-Transfer-Encoding:7bit\r\n\r\n";
				  $header .= $message."\r\n\r\n";
				  
				  //file attachment
				   $header .= "--".$uid."\r\n";
				   $header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
				   $header .= "Content-Transfer-Encoding: base64\r\n";
				   $header .= "Content-Disposition: attachment; filename=\"". $file_name."\"r\n\r\n";
				   $header .= $content. "\r\n\r\n";
				   
				   //send the mail
				   if (mail($to, $subject, $message, $header)) {
				   	echo "success";
					} else {
						echo "fail";
					}
			
			} else {
				echo "file type not allowed";
			}
	}else {
		echo "no file posted";
	}

}

exit();
?>
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Web form with attachment

Post by flying_circus »

It is unclear what is actually happening.

To diagnose your code, we need to know if the attachment is actually being posted. This will tell us if the error is on the HTML form side, or the php side

dump the contents of the $_FILES superglobal to determine if the files are actually getting transmitted in your form post. You can do this with. var_dump()


Code: Select all

/* snippet */
//if there is post
 if(isset($_POST) && !empty($_POST) ) {

    var_dump( $_FILES );
    exit();

/* snippet */
Insert those 2 lines into your code after you check if the request is POST and see let us know what the output is.
greatme
Forum Newbie
Posts: 14
Joined: Fri Jul 09, 2010 10:55 am

Re: Web form with attachment

Post by greatme »

After inseting the above given 2 lines into my code, this is the message i got fro the browser.

array(1) { ["attachment"]=> array(5) { ["name"]=> string(26) "my passport photograph.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(26) "C:\Windows\Temp\phpB5D.tmp" ["error"]=> int(0) ["size"]=> int(83614) } }
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: Web form with attachment

Post by mikosiko »

in your code (part showed here)

Code: Select all

...
//things you need
                                $file = $temp_name;
                                $content = chunk_split(base64_encode(file_get_contents(file)));
                                $uid = md5(uniqid(time()));
....
what is "file" ?
http://php.net/manual/en/function.file-get-contents.php
greatme
Forum Newbie
Posts: 14
Joined: Fri Jul 09, 2010 10:55 am

Re: Web form with attachment

Post by greatme »

thanks mikosiko,
i have added the proper variable as $file but it is still not attaching.

Code: Select all

//things you need
                                $file = $temp_name;
                                $content = chunk_split(base64_encode(file_get_contents($file)));
                                $uid = md5(uniqid(time()));
....
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: Web form with attachment

Post by flying_circus »

I think this is the line that got you:

$temp_name = $_FILES['attachment']['temp_name'];

should be:

$temp_name = $_FILES['attachment']['tmp_name'];


and

$header .= "Content-Disposition: attachment; filename=\"". $file_name."\"r\n\r\n";

Should be

$header .= "Content-Disposition: attachment; filename=\"". $file_name."\"\r\n\r\n";


I tested your script, made a few changes in my test environment, and here is what I ended up with. I have tested it all the way up until the point of sending the email

Code: Select all

<?php
  # Enable Error Reporting
    error_reporting(E_ALL - (E_NOTICE + E_WARNING));
    
  # If there is post
    if( $_SERVER["REQUEST_METHOD"] == "POST" ) {
    # Imports
      //require_once "Mail.php";
      
    # Constants
      $from = "name@domain_name";
      $to = "name@domain_name";
      $username = "name@domain_name";
      $password = "password";
      $host = "smtp.domain_name";
     
     # Handle File Attachments
      if( !empty( $_FILES['attachment'] ) ) {
      //store some varibles    
        $file_name = $_FILES['attachment']['name'];
        $temp_name = $_FILES['attachment']['tmp_name'];
        $file_type = $_FILES['attachment']['type'];

      //get the extention of the file
        $extension = pathinfo( $file_name, PATHINFO_EXTENSION );

      //only these files types wil be allowed
        $allowed_extensions = array("doc","docx","zip", "png", "jpg");

      //check that this file type is allowed
        if( in_array( $extension, $allowed_extensions ) ) {

        //mail essentials
          $subject = "Testing mail attachment";
          $message = "From the office of the Guru";

        //things you need
          $file = $temp_name;
          $content = chunk_split( base64_encode( file_get_contents( $temp_name ) ) );
          $uid = md5(uniqid(time()));

        // standards mail headers
          $header = "From: ".$from. "\r\n";
          $header .= "Reply-To: ".$replyto. "\r\n";
          $header .= "MIME-Version: 1.0\r\n";

        // declaring we have multiple kinds of mails (plain text and attachment
          $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
          $header .= "This is a multi-part message in MIME format.\r\n";

        //plain text part
          $header .= "--".$uid."\r\n";
          $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
          $header .= "Content-Transfer-Encoding:7bit\r\n\r\n";
          $header .= $message."\r\n\r\n";

        //file attachment
          $header .= "--".$uid."\r\n";
          $header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
          $header .= "Content-Transfer-Encoding: base64\r\n";
          $header .= "Content-Disposition: attachment; filename=\"". $file_name."\"\r\n\r\n";
          $header .= $content . "\r\n\r\n";

        //send the mail
          if (mail($to, $subject, $message, $header)) {
            echo "success";
          } else {
            echo "fail";
          }

        } else {
          echo "file type not allowed";
        }
      } else {
        echo "no file posted";
      }
    }
?>

<html>
  <head>
  </head>
  <body>
    <form action="" method="post" enctype="multipart/form-data">
    Send these files:<br />
    <input name="attachment" type="file" /><br />
    <input type="submit" value="Send files" />
  </body>
</html>
greatme
Forum Newbie
Posts: 14
Joined: Fri Jul 09, 2010 10:55 am

Re: Web form with attachment

Post by greatme »

thank you so much flying_circus,

I copied and pasted the code above as edited by you and the situation is still the same. I get the message in my mail with a symbol of an attachment but the file is actually not attached to the mail
Post Reply