[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Add attachment to form sent

Posted on 2009-12-21
20
Medium Priority
?
444 Views
Last Modified: 2013-12-17
I have a form and a handle form (send.php) to send form data + a file to an e-mail address. Emailing the general data and entering the CAPTCHA code works well, but I need PHP code to check for certain file types and add certain types of files to the email. I do not have PEAR at my disposal. Can someone help me editing this send.php that handles the form data so I can send attached files too?
<?php 
 
 
    
session_start();
 
$to      = 'someone@domain.net';
$subject = 'Rental Request';
$name    =  $_POST['name'];
$company =  $_POST['company'];
$email   =  $_POST['email'];
$url     =  $_POST['url'];
$contact =  $_POST['contact'];
$total_pages = $_POST['xpages'];
$headers = 'From: request@domain.com' . "\r\n" .
    'Reply-To: request@domain.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
$body  =  "From: $name\n Company: $company\n E-Mail: $email\n URL: $url\n Contact:\n $contact"; 
 
if( isset($_POST['submit'])) {
   if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
                // Insert you code for processing the form here, e.g emailing the submission, entering it into a database.
        mail($to, $subject, $body, $headers); 
                echo 'Thank you. Your message said "'.$_POST['xpages'].'"';
                unset($_SESSION['security_code']);
   } else {
                // Insert your code for showing an error message here
                echo 'Sorry, you have provided an invalid security code';
   }
} else {
?>
	<form action="/.send.php" method="post">
		<label for="name">Name: </label><input type="text" name="name" id="name" /><br />
		<label for="email">Email: </label><input type="text" name="email" id="email" /><br />
		<label for="message">Message: </label><textarea rows="5" cols="30" name="message" id="message"></textarea><br />
		<img src="./captcha/CaptchaSecurityImages.php?width=100&height=40&characters=5" /><br />
		<label for="security_code">Security Code: </label><input id="security_code" name="security_code" type="text" /><br />
		<input type="submit" name="submit" value="Submit" />
	</form>

<?php
	}
?>

Open in new window

0
Comment
Question by:rhandalthor
  • 17
  • 3
20 Comments
 

Author Comment

by:rhandalthor
ID: 26098333
I found some code on the EE forum. But I do not know how to add it yet. Still new at MIME and sendmail..
//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('Zodiac_Tri_Web.pdf'))); 
//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="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Open in new window

0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 26100706
Since you must upload the file to your server in order to send it, why not consider just storing the file and sending a link to the uploaded file.  Lots of good reasons to do it this way.  Less bulk in the in-box, etc.
0
 

Author Comment

by:rhandalthor
ID: 26102631
@ Ray Pasteur I agree, but as I am very new to this I would not know where to start. I was given a tutorial before, but it required PEAR and my ISP does not have it. Now I need guidance to send the form + a file using PHP and another option.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:rhandalthor
ID: 26102673
Maybe the following code is better?
<?php
$fileatt = ""; // Path to the file
$fileatt_type = "application/octet-stream"; // File Type
$fileatt_name = ""; // Filename that will be used for the file as the attachment

$email_from = ""; // Who the email is from
$email_subject = ""; // The Subject of the email
$email_txt = ""; // Message that the email has in it

$email_to = ""; // Who the email is too

$headers = "From: ".$email_from;

$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);

$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

$email_message .= "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$email_message . "\n\n";

$data = chunk_split(base64_encode($data));

$email_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";

$ok = @mail($email_to, $email_subject, $email_message, $headers);

if($ok) {
echo "<font face=verdana size=2>The file was successfully sent!</font>";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26102695
Maybe to upload the file to a folder I can use the attached script, but I need to know which client uploaded what files/images so they can be added to the site later..
<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}
?>

Open in new window

0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 2000 total points
ID: 26106078
Just curious - have you tried downloading PEAR and installing it yourself?  Here is a standard "teaching sample" that shows how to upload and store a file.  Perhaps you can integrate that into your logic.

If you're new to PHP, this is a tough place to start.  File uploads have a lot of trip-wires and security issues.  A good book that could help you get a foundation is available from SitePoint.
http://www.sitepoint.com/books/library/

Best regards, ~Ray
<?php // RAY_upload_example.php
error_reporting(E_ALL);

// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php


// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'uploads';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array('jpg', 'gif', 'png', 'txt', 'pdf');

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;



// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED IN $_FILES[]["error"]
$errors	= array(
	0 => "Success!",
	1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
	2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
	3 => "The uploaded file was only partially uploaded",
	4 => "No file was uploaded",
	6 => "Missing a temporary folder",
	7 => "Cannot write file to disk"
);




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
	?>
	<h2>Upload <?php echo $nf; ?> file(s)</h2>

	<!--
		SOME THINGS TO NOTE ABOUT THIS FORM...
		NOTE THE CHOICE OF ENCTYPE IN THE HTML FORM STATEMENT
		MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
		INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
	-->

	<form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
	<input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
	<p>
	Find the file(s) you want to upload and click the "Upload" button below.
	</p>

	<?php for ($n = 0; $n < $nf; $n++)
		{
			echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
		}
	?>
	<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
	<input type="submit" name="_submit" value="Upload" />
	</form>
	<?php
	die();
}
// END OF THE FORM SCRIPT




else // WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
{

// THERE IS POST DATA - PROCESS IT
	echo "<h2>Results: File Upload</h2>\n";

// ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
//	echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

// ITERATE OVER THE CONTENTS OF $_FILES
	foreach ($_FILES as $my_uploaded_file)
	{

// SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
		$error_code	= $my_uploaded_file["error"];
		if ($error_code == 4) continue;

// SYNTHESIZE THE NEW FILE NAME
		$f_type	= trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
		$f_name	= trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
		$my_new_file = getcwd() . '/' . $uploads . '/' . $f_name .'.'. $f_type;
		$my_file     = $uploads . '/' . $f_name .'.'. $f_type;

// OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
		if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

// IF THERE ARE ERRORS
		if ($error_code != 0)
		{
			$error_message = $errors[$error_code];
			die("Sorry, Upload Error Code: $error_code: $error_message");
		}

// GET THE FILE SIZE
		$file_size	= number_format($my_uploaded_file["size"]);

// MOVE THE FILE INTO THE DIRECTORY
// IF THE FILE IS NEW
		if (!file_exists($my_new_file))
		{
			if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
			{
				$upload_success = 1;
			}
			else
			{
				$upload_success = -1;
			}

// IF THE FILE ALREADY EXISTS
		}
		else
		{
			echo "<br/><b><i>$my_file</i></b> already exists.\n";

// SHOULD WE OVERWRITE THE FILE? IF NOT
			if (empty($_POST["overwrite"]))
			{
				$upload_success = 0;

// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
			}
			else
			{
				$now	= date('Y-m-d');
				$my_bak = $my_new_file . '.' . $now . '.bak';
				if (!copy($my_new_file, $my_bak))
				{
					echo "<br/><b>Attempted Backup Failed!</b>\n";
				}
				if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
				{
					$upload_success = 2;
				}
				else
				{
					$upload_success = -1;
				}
			}
		}

// REPORT OUR SUCCESS OR FAILURE
		if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
		if ($upload_success == 1) { echo "<br/><b><i>$my_file</i></b> has been saved.\n"; }
		if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>\n"; }
		if ($upload_success < 0)  { echo "<br/><b>ERROR <i>$my_file</i> NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>\n"; }
		if ($upload_success > 0)
		{
			echo "$file_size bytes uploaded.\n";
			if (!chmod ($my_new_file, 0755))
			{
				echo "<br/>chmod(0755) FAILED: fileperms() = ";
				echo substr(sprintf('%o', fileperms($my_new_file)), -4);
			}
			echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
		}
// END ITERATOR
	}
}
?>

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26130719
Apparently I can install PEAR. So I will try that today or tomorrow. Thanks for all the help so far..
0
 

Author Comment

by:rhandalthor
ID: 26130780
I found http://pear.php.net/manual/en/installation.getting.php with an explaantion on adding to a hosting environment. But where on my server do I add it?
0
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 2000 total points
ID: 26132485
That is a good question and I do not have a good answer for your configuration.  But it will all get installed in a single path, so you can try it and if it does not work for you, you can either rename the path or delete it and re-install.
0
 

Author Comment

by:rhandalthor
ID: 26145464
Installed PEAR. See attached log. they mentioned:
Note: To use PEAR without any problems you need to add your
PEAR Installation path (/var/www/vhosts/mydomain.com/subdomains/lab/httpdocs/apt-1/PEAR)
to your include_path.

Using a .htaccess file or directly edit httpd.conf would be working solutions
for Apache running servers, too.

I need to see how I can add this to an .htacess just in case I get into trouble somewhere along the way..
Preparing installer..................
Updating channel "doc.php.net"
Update of Channel "doc.php.net" succeeded
Updating channel "pear.php.net"
Update of Channel "pear.php.net" succeeded
Updating channel "pecl.php.net"
Update of Channel "pecl.php.net" succeeded

Installing selected packages..................
Downloading and installing package: PEAR.............ok
Installing bootstrap package: Structures_Graph.......ok
Downloading and installing package: Archive_Tar-stable.......ok
Downloading and installing package: Console_Getopt-stable.......ok
Downloading and installing package: PEAR_Frontend_Web-beta.......ok
Downloading and installing package: PEAR_Frontend_Gtk2.......ok
Downloading and installing package: MDB2.............ok

Writing WebFrontend file ... ok

Installation Completed !
	Note: To use PEAR without any problems you need to add your
PEAR Installation path (/var/www/vhosts/mydomain.com/subdomains/lab/httpdocs/apt-1/PEAR)
to your include_path.

Using a .htaccess file or directly edit httpd.conf would be working solutions
for Apache running servers, too.

For more information about PEAR, see:
PEAR FAQ
PEAR Manual

Thanks for using go-pear!

Start Web Frontend of the PEAR Installer >>

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26146279
Working on adding a .htpasswd and .htaccess to protect the PEAR folder. Never did that before and now I get a 505 internal server error. Wonder what it is. I have attached the .htaccess. The .htaccess and .htpasswd are in the same folder and PEAR is a sub directory in that folder..
AuthUserFile /var/www/vhosts/mydomain.com/subdomains/lab/apt-1/.htpasswd
AuthType Basic
AuthName "/PEAR/"
Require valid-user

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26146316
Made one small change.. No luck yet though..
AuthUserFile /var/www/vhosts/mydomain.com/subdomains/lab/httpdocs/apt-1/.htpasswd
AuthType Basic
AuthName "/PEAR/"
Require valid-user

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26146697
Here the new .htaccess. And no, still no luck. Still a 500 server error
AuthUserFile /var/www/vhosts/mydomain.com/subdomains/lab/httpdocs/apt-1/.htpasswd
AuthType Basic
AuthName me
<Files "go-pear.php">
Require valid-user
</Files>

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26147095
text editor corrupted the text. Fixed it using Gedit. Now I am getting a login screen and a 403... progress...
0
 

Author Comment

by:rhandalthor
ID: 26147706
As long as I access a file in the directory apt-1 directly and not the directory itself the log on on works and I d not get a 403. Time for configuring PEAR and get my form to work...
0
 

Author Comment

by:rhandalthor
ID: 26147725
Will read this one http://www.html-form-guide.com/email-form/php-email-form-attachment.html again and give the form + PEAR a shot and post back.
0
 

Author Comment

by:rhandalthor
ID: 26148174
To use PEAR without any problems you need to add your
PEAR Installation path (/var/www/vhosts/mydomain.com/subdomains/lab/httpdocs/apt-1/PEAR)
to your include_path.

How do I do that without access to php.ini ?
0
 

Author Comment

by:rhandalthor
ID: 26152144
I found a sample @ Tech Republic http://articles.techrepublic.com.com/5100-10878_11-5163311.html how to use a PHP function to load the path to PEAR. Will try it shortly.
<?php
ini_set(
    "include_path", (
        "/var/www/vhosts/mydomain.com/subdomains/lab/httpdocs/apt-1/PEAR/" .
        PATH_SEPERATOR .
        ini_get("include_path")
        )
    )
);
?>

Open in new window

0
 

Author Comment

by:rhandalthor
ID: 26291663
Will continue this as soon as possible.. But need to resolve other urgent issues first..
0
 

Author Comment

by:rhandalthor
ID: 26293162
Will open this one as a new one again when I have time. Thanks for the help I got so far Pasteur.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

As tax season makes its return, so does the increase in cyber crime and tax refund phishing that comes with it
The main intent of this article is to make you aware of ‘Exchange fail to mount’ error, its effects, causes, and solution.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.
Suggested Courses
Course of the Month19 days, 1 hour left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question