Page 1 of 1

Modify PHP Script to allow Web Form to Upload Files to Email

Posted: Thu Jun 14, 2007 4:05 pm
by WebMagi
Greetings,

I am temporarily in need of a solution that will allow me to send a maximum of three photos from an online form to an email address. I am currently combining JavaScript from this source: http://the-stickman.com/web-development ... le-element

and PHP from this source: http://www.top-frog.com/files/scripts/u ... ample.phps (Shawn's updated script wasn't working out, so I am using the original)

The form I have now easily uploads up to three files to my server, but so far, the developer of the PHP script has been unable to show me how to configure PHP to send the files to an email address. Does anyone here know how this might be accomplished?

I am also using the following to harvest other information from the form:

Code: Select all

$name = $_POST["name"];
$city = $_POST["city"];
$state = $_POST["state"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$year = $_POST["year"];
$make = $_POST["make"];
$model = $_POST["model"];
$price = $_POST["price"];
$comments = $_POST["comments"];
$today = date("M d, Y");
$recipient = "MyEmail@thisaddress.com";
$subject = "Online Form";
$forminfo =
"Name: $name\n
City: $city\n
State: $state\n
Phone: $phone\n
Email: $email\n
Year: $year\n
Make: $make\n
Model: $model\n
Price: $price\n
Comments: $comments\n
Form Submitted: $today\n\n";

$formsend = mail("$recipient", "$subject", "$forminfo", "From: $email\r\nReply-to:$email");
?>
Thanks in advance for your consideration.

Posted: Thu Jun 14, 2007 6:12 pm
by feyd
Here's the thing: General Discussion is not for posting programming questions. If you read the description, read it again.

Posted: Fri Jun 15, 2007 2:07 am
by WebMagi
feyd wrote:Here's the thing: General Discussion is not for posting programming questions. If you read the description, read it again.
Thanks for the heads up fyed.

So any ideas on how to solve the problem?

Posted: Mon Jun 18, 2007 4:47 pm
by WebMagi
Is there anyone who has ever run across a script that can do what I am suggesting, or is this beyond the scope of PHP?

Posted: Mon Jun 18, 2007 4:57 pm
by superdezign
You mean sending attachments? Yeah, mail() can do it, but I'd suggest SwiftMailer. It's very clean and easy to use. mail() is.. not. Also, some servers block mail() because it doesn't automatically send proper mail sometimes.

Posted: Wed Jun 20, 2007 5:03 am
by WebMagi
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


[quote="superdezign"]You mean sending attachments? Yeah, mail() can do it, but I'd suggest [url=http://www.swiftmailer.org]SwiftMailer[/url]. It's very clean and easy to use. mail() is.. not. Also, some servers block mail() because it doesn't automatically send proper mail sometimes.[/quote]

Thanks superdezign, SwiftMailer looks very promising. Unfortunately, I am just a simple web designer and it looks as though SwiftMailer was intended for PHP developers. The form I have, which is based on the technologies provided by two separate developers shown in the links in my first post,  uploads files to the server perfectly. But I have yet to determine how to make it send those files to an email address instead. The form is temporary, and will only be used by one person, so I'm not sure I have a great need for SwiftMailer just yet. 

Here is the form, with most of the HTML removed:

[syntax="html"]
<html>
<head>
<script language="JavaScript" src="../file_upload_element.js" type="text/JavaScript"></script>
</head>
<body>
<form action="form.php" method = "post" enctype="multipart/form-data" class="flyer_text6">
<input type="text" name="name" />
<input type="text" name="city" />
<select name="state">
            <option value="" selected="selected"> </option>
            <option value="AL">Alabama </option>
            <option value="AK">Alaska </option>
            <option value="AZ">Arizona </option>
            <option value="AR">Arkansas </option>
            <option value="CA">California </option>
            <option value="CO">Colorado </option>
            <option value="CT">Connecticut </option>
            <option value="DE">Delaware </option>
            <option value="DC">District of Columbia (DC) </option>
            <option value="FL">Florida </option>
            <option value="GA">Georgia </option>
            <option value="HI">Hawaii </option>
            <option value="ID">Idaho </option>
            <option value="IL">Illinois </option>
            <option value="IN">Indiana </option>
            <option value="IA">Iowa </option>
            <option value="KS">Kansas </option>
            <option value="KY">Kentucky </option>
            <option value="LA">Louisiana </option>
            <option value="ME">Maine </option>
            <option value="MD">Maryland </option>
            <option value="MA">Massachusetts </option>
            <option value="MI">Michigan </option>
            <option value="MN">Minnesota </option>
            <option value="MS">Mississippi </option>
            <option value="MO">Missouri </option>
            <option value="MT">Montana </option>
            <option value="NC">N. Carolina </option>
            <option value="ND">N. Dakota </option>
            <option value="NE">Nebraska </option>
            <option value="NV">Nevada </option>
            <option value="NH">New Hampshire </option>
            <option value="NJ">New Jersey </option>
            <option value="NM">New Mexico </option>
            <option value="NY">New York </option>
            <option value="OH">Ohio </option>
            <option value="OK">Oklahoma </option>
            <option value="OR">Oregon </option>
            <option value="PA">Pennsylvania </option>
            <option value="RI">Rhode Island </option>
            <option value="SC">S. Carolina </option>
            <option value="SD">S. Dakota </option>
            <option value="TN">Tennessee </option>
            <option value="TX">Texas </option>
            <option value="UT">Utah </option>
            <option value="VT">Vermont </option>
            <option value="VA">Virginia </option>
            <option value="WV">W. Virginia </option>
            <option value="WA">Washington </option>
            <option value="WI">Wisconsin </option>
            <option value="WY">Wyoming </option>
          </select>
<input type="text" name="phone" />
<input type="text" name="email" />
<input name="year" type="text" id="year" />
<input name="make" type="text" id="make" />
<input name="model" type="text" id="model" />
<input name="price" type="text" id="price" />
<textarea name="comments" cols="50" rows="5" id="comments"></textarea>
<input name="file_1" type="file" class="flyer_text6" id="my_file_element" size="25">
<input name="submit" type="submit" class="flyer_text6" id="submit" value="Submit" />
<input name="Reset" type="reset" class="flyer_text6" id="Reset" value="Reset" />
</form>
<!-- This is where the output will appear -->
<script>
	<!-- Create an instance of the multiSelector class, pass it the output target and the max number of files -->
	var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
	<!-- Pass in the file element -->
	multi_selector.addElement( document.getElementById( 'my_file_element' ) );
</script>
</body>
</html>
Here's the PHP Script:[/syntax]

Code: Select all

<?php


    // images dir - relative from document root
    // this needs to be a folder that is writeable by the server
    $image_dir = '/file_uploads/';
    
    // upload dir
    $destination = $_SERVER['DOCUMENT_ROOT'].$image_dir;
        
    if(isset($_FILES))
        {
            // initialize error var for processing
            $error = array();     
            
            // acceptable files
            // if array is blank then all file types will be accepted
            $filetypes = array(
                        'ai' => 'application/postscript',
                        'bin' => 'application/octet-stream',
                        'bmp' => 'image/x-ms-bmp',
                        'css' => 'text/css',
                        'csv' => 'text/plain',
                        'doc' => 'application/msword',
                        'dot' => 'application/msword',
                        'eps' => 'application/postscript',
                        'gif' => 'image/gif',
                        'gz' => 'application/x-gzip',
                        'htm' => 'text/html',
                        'html' => 'text/html',
                        'ico' => 'image/x-icon',
                        'jpg' => 'image/jpeg',
                        'jpe' => 'image/jpeg',
                        'jpeg' => 'image/jpeg',
                        'js' => 'text/javascript',
                        'mov' => 'video/quicktime',
                        'mp3' => 'audio/mpeg',
                        'mp4' => 'video/mp4',                        
                        'mpeg' => 'video/mpeg',
                        'mpg' => 'video/mpeg',
                        'pdf' => 'application/pdf',
                        'png' => 'image/x-png',
                        'pot' => 'application/vnd.ms-powerpoint',
                        'pps' => 'application/vnd.ms-powerpoint',
                        'ppt' => 'application/vnd.ms-powerpoint',
                        'qt' => 'video/quicktime',
                        'ra' => 'audio/x-pn-realaudio',
                        'ram' => 'audio/x-pn-realaudio',
                        'rtf' => 'application/rtf',
                        'swf' => 'application/x-shockwave-flash',
                        'tar' => 'application/x-tar',
                        'tgz' => 'application/x-compressed',
                        'tif' => 'image/tiff',
                        'tiff' => 'image/tiff',
                        'txt' => 'text/plain',
                        'xls' => 'application/vnd.ms-excel',
                        'zip' => 'application/zip'
                    );
                    
            // function to check for accpetable file type
            function okFileType($type)
                {
                    // if filetypes array is empty then let everything through
                    if(count($GLOBALS['filetypes']) < 1)
                        {
                            return true;
                        }
                    // if no match is made to a valid file types array then kick it back
                    elseif(!in_array($type,$GLOBALS['filetypes']))
                        {
                            $GLOBALS['error'][] = $type.' is not an acceptable file type. '.
                                                  $type.' has been ignored.';
                            return false;
                        }
                    // else - let the file through
                    else
                        {                        
                            return true;
                        }
                }
            
            // function to check and move file
            function processFile($file)
                {    
                    // set full path/name of file to be moved
                    $upload_file = $GLOBALS['destination'].$file['name'];
                    
                    if(file_exists($upload_file))
                        {
                            $GLOBALS['error'][] = $file['name'].' - Filename exists - please change your image filename';
                            return false;
                        }
                    
                    if(!move_uploaded_file($file['tmp_name'], $upload_file)) 
                        {
                            // failed to move file
                            $GLOBALS['error'][] = 'File Upload Failed on '.$file['name'].' - Please try again';
                            return false;
                        } 
                    else 
                        {
                            // upload OK - change file permissions
                            chmod($upload_file, 0755);
                            return true;
                        }    
                }
                
            // check to make sure files were uploaded
            $no_files = 0;
            $uploaded = array();
            foreach($_FILES as $file)
                {
                    switch($file['error'])
                        {
                            case 0:
                                // file found
                                if($file['name'] != NULL && okFileType($file['type']) != false)
                                    {
                                        // process the file
                                        if(processFile($file) == true)
                                            $uploaded = $file['name'];
                                    }
                                break;
                                
                            case (1|2):
                                // upload too large
                                $error[] = 'file upload is too large for '.$file['name'];
                                break;
                                
                            case 4:
                                // no file uploaded
                                break;
                                
                            case (6|7):
                                // no temp folder or failed write - server config errors
                                $error[] = 'internal error - flog the webmaster on '.$file['name'];
                                break;
								
                        }
                }
                
        }

$name = $_POST["name"];
$city = $_POST["city"];
$state = $_POST["state"];
$phone = $_POST["phone"];
$email = $_POST["email"];
$year = $_POST["year"];
$make = $_POST["make"];
$model = $_POST["model"];
$price = $_POST["price"];
$comments = $_POST["comments"];
$today = date("M d, Y");
$recipient = "myemail@mydomain.com";
$subject = "File Uploads";
$forminfo =
"Name: $name\n
City: $city\n
State: $state\n
Phone: $phone\n
Email: $email\n
Year: $year\n
Make: $make\n
Model: $model\n
Price: $price\n
Comments: $comments\n
Form Submitted: $today\n\n";

$formsend = mail("$recipient", "$subject", "$forminfo", "From: $email\r\nReply-to:$email");
?>
...and here is the JavaScript code used to generate the file upload elements in the form:

Code: Select all

function MultiSelector( list_target, max ){this.list_target = list_target;this.count = 0;this.id = 0;if( max ){this.max = max;} else {this.max = -1;};this.addElement = function( element ){if( element.tagName == 'INPUT' && element.type == 'file' ){element.name = 'file_' + this.id++;element.multi_selector = this;element.onchange = function(){var new_element = document.createElement( 'input' );new_element.type = 'file';this.parentNode.insertBefore( new_element, this );this.multi_selector.addElement( new_element );this.multi_selector.addListRow( this );this.style.position = 'absolute';this.style.left = '-1000px';};if( this.max != -1 && this.count >= this.max ){element.disabled = true;};this.count++;this.current_element = element;} else {alert( 'Error: not a file input element' );};};this.addListRow = function( element ){var new_row = document.createElement( 'div' );var new_row_button = document.createElement( 'input' );new_row_button.type = 'button';new_row_button.value = 'Delete';new_row.element = element;new_row_button.onclick= function(){this.parentNode.element.parentNode.removeChild( this.parentNode.element );this.parentNode.parentNode.removeChild( this.parentNode );this.parentNode.element.multi_selector.count--;this.parentNode.element.multi_selector.current_element.disabled = false;return false;};new_row.innerHTML = element.value;new_row.appendChild( new_row_button );this.list_target.appendChild( new_row );};};
Just by looking at what I have provided, can anyone determine how to make the PHP script send the files to an email address?

Thanks


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Wed Jun 20, 2007 6:22 am
by superdezign
That's not our job, that's your job. :wink:

SwiftMailer is extremely easy to use, and only requires a basic understand of OOP, and I mean a very basic understanding. It's flexible and has plenty of examples, as well as an entire forum for it on this website.

Check the documentation on how to send emails and how to send file attachments.

Posted: Wed Jun 20, 2007 8:00 am
by WebMagi
superdezign wrote:That's not our job, that's your job. :wink:
I appreciate the wink as a gesture of humor, but your statement was rude nevertheless. I was not asking anyone to do my job, I was merely asking for what I assumed would be a simple answer to the PHP pros on this forum. Is my issue really that hard to figure out? If so, then I'd be happy to pay someone to come up with a solution using the components I have provided, just give me a quote. I offered to pay the original developer of the PHP script as well, but it's been a month and he has not responded.

No worries either way, I'm pretty sure I can build what I need using MX Kollection Pro, if it comes to that. My work load has just been so insane lately that I thought it best to see what was already out there. I guess I'm a little hesitant to start from scratch with SwiftMailer considering I need this form functional yesterday.
SwiftMailer is extremely easy to use, and only requires a basic understand of OOP, and I mean a very basic understanding. It's flexible and has plenty of examples, as well as an entire forum for it on this website.

Check the documentation on how to send emails and how to send file attachments.
Speaking of examples, can you show me a working file-to-email demo form online somewhere that uses SwiftMailer? I have little use for the snippets of PHP code in the tutorial sections on SwiftMailer's site, I need to see a live demo form in action.

Thanks.

Posted: Wed Jun 20, 2007 8:36 am
by superdezign
Rude or not, you don't learn if you don't try, right?

Sending attachments with Swiftmailer