PHP - Trying To Get File To Attach To Email Message From Upload Form
Hi all
I have a script that I have patched together and got to work in pieces. I'm up to the last part. I have the form working and emailing. It also will upload an image by itself and put it in a folder. Now i just need to tie those together and have the image put in the email as an attachment then deleted from server. I have it at a stage where it sends me the users details.. and it tries to send the photo but it comes through as junk txt. I think its the MIME encoding stuff that I have wrong.. not sure? Here's what I have so far. Code: [Select] $attachment = $path_of_uploaded_file; $fileatt = $attachment; // Path to the file $fileatt_type = "application/octet-stream"; // File Type $start= strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1; $fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment $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" . $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"; // create email headers $headers .= 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); Thanks Wolfsta Similar TutorialsHi All, I don't really need help with the code, I just need to know the process... This will take place in a simple form. The user enters the payment information and checks off 'Send Receipt' option. From there, the payment data is stored in the DB. Then, I need to have a PDF generated of the receipt and finally email the tenant with confirmation and the PDF that was created. Once the data is inserted, I can use fPDF to merge the data to the PDF document I created. That part I don't understand is how to automatically save that file and attach it to an email. Ideas / suggestions? How to attach any file type to an email using php mail() It should attach any file that you select. What would be the Content-type: value? Thanks! Not sure if this relates more to PHP or Javascript/jQuery, but is there a way to attach a file to an email client (i.e Outlook), when user click on a link/button? I have a link that generates a PDF and I want it so that, when someone click on a link, it will open up their email client with the PDF already attached, and subject already fill in. I know, you can use <a href="mailto:..." but that only opens up the mail client. I also need to attach a file with a subject fill in. Is this doable with PHP or Javascript? I have a one-page responsive website template with a built-in contact email form whereby I would like to add an upload file attachment provision to the contact form. While I have been able to successfully add two fields (source, URL) to the built-in contact email form, with exception of adding the HTML to the form , modification to the contact email form's PHP files appears to be much more involved whereby I have been unable to find a barebones PHP code I can add to the existing PHP to make this work. I should also add that while I am well versed in HTML, CSS, and Javascript, I am not when it comes to PHP. In brief, I prefer not to replace the built-in contact form with different HTML and PHP for adding a contact form email file attachment. Any suggestions regarding this subject matter are appreciated. Since PHP is not listed under accepted file types for attachment to this post, I can provide download links to the contact email form PHP files from my iHost server for review if need be. The website address to view the HTML source code for the built-in contact form is https://www.seoauditspecialists.com. Apart from my having to add 'enctype=”multipart/form-data”' to the contact form's <form action> line of code, the HTML to add the 'file' field is provided below. Thank you ahead of time.
<div class="form-group"> Hi I built a really simple customer review form https://kickasssoftwear.uk/dev/reviews.html (it's only been optimised for mobile view so far) and it works using the php mail script on this page https://kickasssoftwear.uk/dev/empty2.php - the emails are being sent to me and the format of the emails is OK, and the form redirects to the empty2 page with a mailsent message in the address bar. I know I can leave that page as is and write a nice thank you message in the html - but what I really want to do is have the customers name there too, Thanks 'name' your review has been sent, but I can't get it to work - it's been 4 whole days now and I really need to eat & sleep! Please if anyone has suggestions or advice for a noob, please help. Thanks Hi all, I am quite new to PHP and MySql. I know how to upload a file a and save the path in the DB, but now I need to send an automatic email to the user when a new invoice is added to his directory. Please help. Thanks Hi, I have a form where a user selects a file to attach to the email. At the moment when you select a file it uploads from the user device. How do i change this so that a user can attach a file from a folder on the server. For example the folder name is uploadinvoice so when the user selects the browse button to attach a file it opens up the uploadinvoice folder on the server so the user can select the file from there ?
Thanks
coding i have at moment function ValidateEmail($email) { $pattern = '/^([0-9a-z]([-.\w]*[0-9a-z])*@(([0-9a-z])+([-\w]*[0-9a-z])*\.)+[a-z]{2,6})$/i'; return preg_match($pattern, $email); } if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formid']) && $_POST['formid'] == 'form1') { $mailto = $_POST['youremail']; $mailfrom = isset($_POST['myemail']) ? $_POST['myemail'] : $mailto; $subject = 'Message'; $message = 'Message'; $success_url = './test.php'; $error_url = ''; $eol = "\n"; $error = ''; $internalfields = array ("submit", "reset", "send", "filesize", "formid", "captcha_code", "recaptcha_challenge_field", "recaptcha_response_field", "g-recaptcha-response"); $boundary = md5(uniqid(time())); $header = 'From: '.$mailfrom.$eol; $header .= 'Reply-To: '.$mailfrom.$eol; $header .= 'MIME-Version: 1.0'.$eol; $header .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'"'.$eol; $header .= 'X-Mailer: PHP v'.phpversion().$eol; try { if (!ValidateEmail($mailfrom)) { $error .= "The specified email address (" . $mailfrom . ") is invalid!\n<br>"; throw new Exception($error); } $message .= $eol; foreach ($_POST as $key => $value) { if (!in_array(strtolower($key), $internalfields)) { if (!is_array($value)) { $message .= ucwords(str_replace("_", " ", $key)) . " : " . $value . $eol; } else { $message .= ucwords(str_replace("_", " ", $key)) . " : " . implode(",", $value) . $eol; } } } $body = 'This is a multi-part message in MIME format.'.$eol.$eol; $body .= '--'.$boundary.$eol; $body .= 'Content-Type: text/plain; charset=ISO-8859-1'.$eol; $body .= 'Content-Transfer-Encoding: 8bit'.$eol; $body .= $eol.stripslashes($message).$eol; if (!empty($_FILES)) { foreach ($_FILES as $key => $value) { if ($_FILES[$key]['error'] == 0) { $body .= '--'.$boundary.$eol; $body .= 'Content-Type: '.$_FILES[$key]['type'].'; name='.$_FILES[$key]['name'].$eol; $body .= 'Content-Transfer-Encoding: base64'.$eol; $body .= 'Content-Disposition: attachment; filename='.$_FILES[$key]['name'].$eol; $body .= $eol.chunk_split(base64_encode(file_get_contents($_FILES[$key]['tmp_name']))).$eol; } } } $body .= '--'.$boundary.'--'.$eol; if ($mailto != '') { mail($mailto, $subject, $body, $header); } header('Location: '.$success_url); } catch (Exception $e) { $errorcode = file_get_contents($error_url); $replace = "##error##"; $errorcode = str_replace($replace, $e->getMessage(), $errorcode); echo $errorcode; } exit;
} Everything about the email is sending except the message text does anyone know what the issue could be? here is the block of code that sends the email Thanks in advance Code: [Select] $image = "http://www.visualrealityink.com/dev/clients/arzan/snell_form/images/email.png"; echo "got to process form"; $target_path = "upload/"; $path = $target_path = $target_path . basename( $_FILES['file']['name']); $boundary = '-----=' . md5( uniqid ( rand() ) ); $message .= "Content-Type: application/msword; name=\"my attachment\"\n"; $message .= "Content-Transfer-Encoding: base64\n"; $message .= "Content-Disposition: attachment; filename=\"$path\"\n\n"; echo $path; $fp = fopen($path, 'r'); do //we loop until there is no data left { $data = fread($fp, 8192); if (strlen($data) == 0) break; $content .= $data; } while (true); $content_encode = chunk_split(base64_encode($content)); $message .= $content_encode . "\n"; $message .= "--" . $boundary . "\n"; $message .= $image . "<br />" . $_POST['name'] . "submitted a resume on our website. Please review the applications and contact the candidate if their resume is a fit for any open opportunities with the company. <br><br> Thank you. <br><br> SEI Team"; $headers = "From: \"Me\"<me@example.com>\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\""; mail('george@visualrealityink.com', 'Email with attachment from PHP', $headers, $message); I tried to add a second file upload to my previously properly functioning form, but after adding it, now when I submit the form, it submits the data twice. It appears to be submitting the file right on the first insert, but on the second insert, the second image is not inserted, but just blank. Can anyone help me figure out why? I must have done something wrong in my insert statement or second file statement. Here is the page itself which contains the form: http://midwestcreativeconsulting.com/jhrevell/add/ And below is my insert page: Code: [Select] <?php $dbhost = 'localhost'; $dbuser = 'username'; $dbpass = 'password'; $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'jhrevell_jewelry'; mysql_select_db($dbname); $name = $_POST['name']; $metal = $_POST['metal']; $desc = $_POST['desc']; $item_no = $_POST['item_no']; $cut = $_POST['cut']; $color = $_POST['color']; $carats = $_POST['carats']; $clarity = $_POST['clarity']; $size = $_POST['size']; $type = $_POST['type']; $other = $_POST['other']; $total = $_POST['total']; $certificate = $_POST['certificate']; $value = $_POST['value']; //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { //echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //echo "Type: " . $_FILES["file"]["type"] . "<br />"; //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} // IMAGE 2 // //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file2"]["error"] > 0) { echo "Return Code: " . $_FILES["file2"]["error"] . "<br />"; } else { //echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //echo "Type: " . $_FILES["file"]["type"] . "<br />"; //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file2"]["name"])) { echo $_FILES["file2"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file2"]["tmp_name"], "upload/" . $_FILES["file2"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image2 = $_FILES["file2"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } //} echo '<script language="Javascript">'; echo 'window.location="http://midwestcreativeconsulting.com/jhrevell/collections"'; echo '</script>'; ?> Can anyone see what could be causing it to insert the record twice? Having some issues getting this to work properly... I keep getting my own error message I know where it fails, but I can't seem to figure out why it fails. The test file I'm using is an MP3 file, which is why I'm here asking if anyone other than I can shed some experienced light on this :p Code: [Select] File Upload Failed! No File Exists!The file type or extension you are trying to upload is not allowed! You can only upload MP3 files to the server! My upload form looks like: <?php session_start(); define('PITCHFORK', true); if(!isset($_SESSION['USERS_AUTHENTICATED'])) { die("You must be logged in to do that"); } if(isset($_POST['upload'])) { include("config.php"); include("classes/class.media.upload.php"); $file = $_GET['file']; $upload = new Upload; $upload->doAudio($file); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>PITCHFORK Login</title> <link rel="stylesheet" href="style/login.css" type="text/css" media="all"> <meta name="robots" content="noindex,nofollow"> </head> <body> <div id="login"><h1><a title="A SpaazZ Industries Concept"></a></h1> <form name="loginform" id="loginform" action="<?php $_SERVER['PHP_SELF']; ?>" method="post"> <p> <label>File (one at a time for now)<br> <input name="file" id="user_login" class="input" size="20" tabindex="10" type="file" /> </label> </p> <p> </p> <?php if(isset($_SESSION['errMessage'])) { echo("<div id=\"login_error\"><strong>ERROR</strong>:<br />"); echo($_SESSION['errMessage']); unset($_SESSION['errMessage']); echo("</div>"); } ?> <p class="submit"> <input name="upload" id="submit" class="button-primary" value="Upload File" tabindex="100" type="submit"> </p> </form> </div> </body> </html> My Upload Class looks liks: <?php // TO DO : ERROR HANDLING // AJAX INTERFACING session_start(); define('PITCHFORK', true); class Upload { // The path to local (relivent to the user uploading - on their computer) file var $file; public function doAudio($file) { $target_path = $_SESSION['USERS_Media_Folder']."/"; // Set at login in class.users.php $flag = 0; // Safety net, if this gets to 1 at any point in the process, we don't upload. $filename = $_FILES[$file]['name']; $filesize = $_FILES[$file]['size']; $mimetype = $_FILES[$file]['type']; $filename = htmlentities($filename); $filesize = htmlentities($filesize); $mimetype = htmlentities($mimetype); $target_path = $target_path . basename( $filename ); if($filename != ""){ echo "Beginning upload process for file named: ".$filename."<br>"; echo "Filesize: ".$filesize."<br>"; echo "Type: ".$mimetype."<br><br>"; } //First generate a MD5 hash of what the new file name will be //Force a MP3 extention on the file we are uploading $hashedfilename = md5_file($filename); $hashedfilename = $hashedfilename.".mp3"; //Check for empty file if($filename == ""){ $_SESSION['errMessage'] .= "No File Exists!"; $flag = $flag + 1; } //Now we check that the file doesn't already exist. $existname = $target_path.$hashedfilename; if(file_exists($existname)) { if($flag == 0) { $_SESSION['errMessage'] .= "Your file already exists on the server! Please choose another file to upload or rename the file on your computer and try uploading it again!"; } $flag = $flag + 1; } //Whitelisted files - Only allow files with MP3 extention onto server... $whitelist = array(".mp3"); foreach ($whitelist as $ending) { if(substr($filename, -(strlen($ending))) != $ending) { $_SESSION['errMessage'] .= "The file type or extention you are trying to upload is not allowed! You can only upload MP3 files to the server!"; $flag++; } } //Now we check the filesize. If it is too big or too small then we reject it //MP3 files should be at least 1MB and no more than 6.5 MB if($filesize > 6920600) { //File is too large if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too large! Your file can be up to 6.5 MB in size only. Please upload a smaller MP3 file or encode your file with a lower bitrate."; } $flag = $flag + 1; } if($filesize < 1048600) { //File is too small if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload is too small! Your file has been marked as suspicious because our system has determined that it is too small to be a valid MP3 file. Valid MP3 files must be bigger than 1 MB and smaller than 6.5 MB."; } $flag = $flag + 1; } //Check the mimetype of the file if($mimetype != "audio/x-mp3" and $mimetype != "audio/mpeg") { if($flag == 0) { $_SESSION['errMessage'] .= "The file you are trying to upload does not contain expected data. Are you sure that the file is an MP3?"; } $flag = $flag + 1; } //Check that the file really is an MP3 file by reading the first few characters of the file $f = @fopen($_FILES[$file]['tmp_name'],'r'); $s = @fread($f,3); @fclose($f); if($s != "ID3") { if($flag == 0){ $_SESSION['errMessage'] .= "The file you are attempting to upload does not appear to be a valid MP3 file."; } $flag++; } //All checks are done, actually move the file... if($flag == 0) { if(move_uploaded_file($_FILES[$file]['tmp_name'], $target_path)) { //Change the filename to MD5 hash and FORCE a MP3 extention. if(@file_exists($target_path.$filename)) { //Rename the file to an MD5 version rename($target_path.$filename, $target_path.$hashedfilename); echo "The file ". basename( $filename ). " has been uploaded. Your file is <a href='$target_path$hashedfilename'>here</a>."; } else{ echo "There was an error uploading the file, please try again!"; } } else { echo "There was an error uploading the file, please try again!"; } } else { echo "File Upload Failed!<br>"; if($error != "") { echo $error; } } } // Close function doAudio } // Close Class audioUpload ?> files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
I've looked over it a couple times and I still get the error. Here's the code <?php require('header.php'); require('links.php'); $name = mysql_real_escape_string($_POST['file']); $url = mysql_real_escape_string($_POST['file']); $filename = $_FILES['file']['name']; $temp = $_FILES['file']['tmp_name']; $error = $_FILES['file']['error']; $sql = "insert into books set name='$name', url='$url'"; if(isset($_POST['submit'])) { if($error > 0) { die("Error uploading file! Code $error."); }else{ move_uploaded_file($temp,"/center/resources/books/".$filename); mysql_query($sql); } } ?> <form method='post' enctype='multipart/form-data'> Book Name<input type="text" name="name"></br> File<input type="file" name="file"></br> <input type="submit" name="submit" value="Upload"> </form> I have been spending the majority of this week figuring out why my files are not showing up at my upload location that I set up in my newly created simple upload form. It just seems like php doesn't like me at all. Here is what my code looks like below. Code: [Select] <?php if (move_uploaded_file($_FILES['thefile']['name'], $upload_file)) $destination = "/www/zymichost.com/m/t/l/mtlproductions/htdocs/"; $upload_file = $destination . basename($_FILES['thefile']['name']);{ echo "Your file has been uploaded successfully!"; }/* else { echo "Your file did not upload successfully. Check to make sure your file meets the requirements and then try again."; print_r($_FILES);}*/?> I have the orange marked areas commented out due to the unexpected T_ELSE error thing. What do I do to get my files to show up at my upload location when I use my upload form? Thanks! I have an excel file that has several columns with different data and I need to create a form that can upload this excel file and insert the data from the columns into its conrresponding data columns in a mysql database. I know how to create the form but I have no idea how to get the file and tell it to input each cell of data into its corresponding field in the mysql database. Does anyone know how to do this? Any help would be appreciated. Thanks, Hi, I have a form that allows a user to enter details and also to upload a image. The form works great and inserts into the database if i dont include the file input. What i would like happen is: The user enters details and selects a file The file then gets uploaded to ../images and the path is then written to bedroom1 variable The addresses and the bedroom1 variable that now holds the uploaded file path e.g. images/test.jpg is written to the database Form Code: [Select] <form action="admin.php" method="POST"> <table> <tr><td> Address 1: </td><td> <input type="text" name="address1" id="address1" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> Address 2: </td><td> <input type="text" name="address2" id="address2" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> County: </td><td> <input type="text" name="county" id="county" onfocus="selected(this)" onblur="notselected(this)"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> Bedroom 1: </td><td> <input type="file" name="bedroom1" id="bedroom1" input name="uploadedfile"> </td><td> <div id="dynamicText1"> </div> </td></tr> <tr><td> <input type="submit" name="submitaddapartment" value="Add" id="registerbutton"> </td></tr> </table </form> And the php code to add it to the database Code: [Select] <?php //get variables $submitaddapartment = $_POST['submitaddapartment']; $address1 = strip_tags($_POST['address1']); $address2 = strip_tags($_POST['address2']); $county = strip_tags($_POST['county']); $bedroom1 = strip_tags($_POST['bedroom1']); if ($submitaddapartment) //if submit button was pressed { if ($address1&&$address2&&$county&&$bedroom1&&) //if fields arn't blank { include 'dbase.php'; //connect to database if ((($_FILES["bedroom1"]["type"] == "image/gif") || ($_FILES["bedroom1"]["type"] == "image/jpg") || ($_FILES["bedroom1"]["type"] == "image/pjpeg")) && ($_FILES["bedroom1"]["size"] < 20000000)) { if ($_FILES["bedroom1"]["error"] > 0) { echo "Return Code: " . $_FILES["bedroom1"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["bedroom1"]["name"] . "<br />"; echo "Type: " . $_FILES["bedroom1"]["type"] . "<br />"; echo "Size: " . ($_FILES["bedroom1"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["bedroom1"]["tmp_name"] . "<br />"; if (file_exists("../images/" . $_FILES["bedroom1"]["name"])) { echo $_FILES["bedroom1"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["bedroom1"]["tmp_name"], "/" . $_FILES["bedroom1"]["name"]); echo "Stored in: " . "../images/" . $_FILES["bedroom1"]["name"]; $bedroom1=".'images/.' $_FILES["bedroom1"]["name"]"; } } } else { echo "Invalid file"; } mysql_query ("INSERT INTO user VALUES(NULL,'$address1','$address2','$county','$bedroom1')"); } else { } } ?> Any help would be greatly appreciated. Thanks Fred I'm trying to add a file size limit to my upload form-code (below) I want to let users select and upload a file. The select form and upload sritp work when they are on different pages, but I want them on the same page with the upload script executing only if the form has been submitted. Here the upload form <!--select the file --> <form enctype="multipart/form-data" action="manage_files.php" method="POST">Please choose a file to upload: <input name="uploaded" type="file" /><input type="submit" value="Upload" /></form> ... and here's the upload code... <!--upload the file --> <?php if (isset($_POST['submit'])) { $target = "safes/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition //if ($uploaded_size > 350000) //{ //echo "Your file is too large.<br>"; //$ok=0; //} //if (!($uploaded_type=="application/zip")) { //echo "You may only upload ZIP files.<br>"; //$ok=0; //} //Here we check that $ok was not set to 0 by an error if ($ok==0) { Echo "Sorry your file was not uploaded"; } //If everything is ok we try to upload it else { if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "Sorry, there was a problem uploading your file."; } } } ?> What am I missing? Thanks for any help! Hi, This is the code I made to show the problem: $useragent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12 ( .NET CLR 3.5.30729)"; $timeout = 10 ; $cookie = tempnam ("/tmp", "CURLCOOKIE"); $post = array('_method'=>"put", 'authenticity_token'=>' zcvcxfsdfvxcv', 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg" ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_USERAGENT, $useragent); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:')); curl_setopt($ch, CURLOPT_URL, "http://localhost/test.php"); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie ); curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $ch, CURLOPT_ENCODING, "" ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_AUTOREFERER, true ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); # required for https urls curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout ); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $html = curl_exec($ch); curl_close($ch); Now this link used above: http://localhost/test.php has this code: print_r($_POST); print_r($_FILES); It simply prints whats in post and files. So the above code displays this on screen: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image] => Array ( [name] => Array ( [a] => Girl-Next-Door-movie-f01.jpg ) [type] => Array ( [a] => image/jpeg ) [tmp_name] => Array ( [a] => /tmp/phppLJPQV ) [error] => Array ( [a] => 0 ) [size] => Array ( [a] => 55377 ) ) ) but we need to modify the code so that it should display this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) Meaning, it is taking this(profile_image[a]) as an array when we are defining $post because that's how curl recognizes that we want to upload only a file or an array of files on server by http post. So, basically the problem is the name of the input field that is defined as an array (profile_image[a]) on the web page that we are trying to mock. If this(profile_image[a]) was this (profile_image_a)(without []) on that webpage, then it would not have been a problem. So, if you understand, this is basically a syntax problem. I do not know how stop curl from reading 'profile_image[a]' as an array here 'profile_image[a]'=>"@Girl-Next-Door-movie-f01.jpg. I need curl to read 'profile_image[a]' as an string and not array. I have to use [], otherwise I will not be able to mock the webpage as the name will change. It will give error. I hope I explained the problem and also gave you a way to test if you have a solution. Again, if your code starts displaying this: Code: [Select] Array ( [_method] => put [authenticity_token] => zcvcxfsdfvxcv ) Array ( [profile_image[a]] => Array ( [name] => Girl-Next-Door-movie-f01.jpg [type] => image/jpeg [tmp_name] => /tmp/phppLJPQV [error] => 0 [size] => 55377 ) ) ,then we have a solution. Thanks for helping in advance. Regards, Manoj Hi Have got my form working for all standard bits. Just need to add the functionality for people to upload photos. I copied and modified the form from a site and there is a section that I think is redundant it still works when I comment it out can you clarify for me: Code: [Select] // validation expected data exists /* if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['telephone']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } */ Below is the full code for the form: Code: [Select] <?php if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "asdfasdf@asdfasdf.com"; $email_subject = "adsfasdf asdfasdf Application Form"; function died($error) { // your error code can go here ?> <title>asdfas asdfasd</title> <style type="text/css"> body { background-color: #000; text-align: center; } body,td,th { color: #FFF; font-family: Arial, Helvetica, sans-serif; font-size: 24px; } </style> </head> <body link="#FFFFFF" onLoad="setTimeout('history.back()',10000)"> <p><img src="../images/logo.png" width="326" height="144" alt="asdfasdf" longdesc="http://www.adsfasdf.com" /><br /> </p> <br /> <p>We are very sorry, but there were error(s) found with the form you submitted.</p> <p>Please fix the following errors:</p> <hr /> <br /> <?php echo $error; ?> <hr /> <br /> <p>Click back to fix your error(s) or you will be taken back to the form automatically in 10 seconds...</p> <h6> </h6> <h6>© asdfasdf 2012</h6> </body> </html> <?php die(); } // validation expected data exists /* if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['telephone']) || !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } */ $first_name = $_POST['first_name']; // required $last_name = $_POST['last_name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['telephone']; // not required $comments = $_POST['comments']; // required $age = $_POST['age']; $city = $_POST['city']; $state = $_POST['state']; $height_feet = $_POST['height_feet']; $height_inches = $_POST['height_inches']; $error_message = ""; $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$first_name)) { $error_message .= 'First Name: This is not a valid name.<br /><br />'; } if(!preg_match($string_exp,$last_name)) { $error_message .= 'Last Name: This is not a valid last name.<br /><br />'; } $age_exp = "/^(1[89]|[2-9][0-9])$/"; if(!preg_match($age_exp,$age)) { $error_message .= 'Age: You need to be at least 18+ to apply.<br /><br />'; } $phone_exp = "/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/"; if(!preg_match($phone_exp,$telephone)) { $error_message .= 'Phone: eg 646 555 1234 or 646-555-1234 or (646) 555 1234<br /><br />'; } $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if(!preg_match($email_exp,$email_from)) { $error_message .= 'Email: Your address is not invalid eg yourname@emaildomain.com<br /><br />'; } if(strlen($comments) < 2) { $error_message .= 'Comments: Please leave a breif message explaining your interest and if you have any previous experience etc.<br /><br />'; } if(strlen($error_message) > 0) { died($error_message); } $email_message = "Form details below:\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "First Name:"."\t".clean_string($first_name)."\n"; $email_message .= "Last Name:"."\t".clean_string($last_name)."\n"; $email_message .= "Age:"."\t".clean_string($age)."\n"; $email_message .= "Height:"."\t".clean_string($height_feet).'ft ' . clean_string($height_inches).'in'."\n"; $email_message .= "City:"."\t".clean_string($city)."\n"; $email_message .= "State:"."\t".clean_string($state)."\n"; $email_message .= "Email:"."\t".clean_string($email_from)."\n"; $email_message .= "Telephone:"."\t".clean_string($telephone)."\n"; $email_message .= "Comments:"."\t".clean_string($comments)."\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?> <!-- include your own success html here --> <title>adsfas asdfasdf</title> <style type="text/css"> body { background-color: #000; text-align: center; } body,td,th { color: #FFF; font-family: Arial, Helvetica, sans-serif; font-size: 24px; } </style> </head> <body link="#FFFFFF" onLoad="setTimeout('history.back()',10000)"> <p><img src="../images/logo.png" width="326" height="144" alt="asdfasdf" longdesc="http://www.asdfasdf.com" /><br /> </p> <p>Thank your for applying to asdf adsf. We will be in touch with you very soon.</p> <p>You will be redirected back to the site in 10 seconds...</p> <h6> </h6> <h6>© adsfdasf 2012</h6> </body> </html> <?php } ?> Here is the html form: Code: [Select] <form id="form2" action="./php/joinus.php" method="post" enctype="multipart/form-data"> <fieldset> <div class="wrapper"> <div class="fleft col"> <label class="first_name"> <span class="text-form">Name:</span> <input name="first_name" type="text" value=""> </label> <label class="age"> <span class="text-form">Age:</span> <input name="age" type="tel" value=""> </label> <label class="city"> <span class="text-form">City:</span> <input name="city" type="text" value=""> </label> <label class="telephone"> <span class="text-form">Phone:</span> <input name="telephone" type="tel" value=""> </label> </div> <div class="fleft col2"> <label class="last_name"> <span class="text-form">Last Name:</span> <input name="last_name" type="text" value=""> </label> <span id="validate_height"> <label><span class="text-form">Height:</span> <select style="width:109px;" name="height_feet"> <option value="" selected="selected">Feet</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> </select> <select style="width:109px;" name="height_inches"> <option value="" selected="selected">Inches</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <option value="11">11</option> </select> </label> </span> <label class="state"> <span class="text-form">State:</span> <select name="state"> <option value="" selected="selected">Select a State</option> <option value="Alabama">Alabama</option> <option value="Alaska">Alaska</option> <option value="Arizona">Arizona</option> <option value="Arkansas">Arkansas</option> <option value="California">California</option> <option value="Colorado">Colorado</option> <option value="Connecticut">Connecticut</option> <option value="Delaware">Delaware</option> <option value="District Of Columbia">District Of Columbia</option> <option value="Florida">Florida</option> <option value="Georgia">Georgia</option> <option value="Hawaii">Hawaii</option> <option value="Idaho">Idaho</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Iowa">Iowa</option> <option value="Kansas">Kansas</option> <option value="Kentucky">Kentucky</option> <option value="Louisiana">Louisiana</option> <option value="Maine">Maine</option> <option value="Maryland">Maryland</option> <option value="Massachusetts">Massachusetts</option> <option value="Michigan">Michigan</option> <option value="Minnesota">Minnesota</option> <option value="Mississippi">Mississippi</option> <option value="Missouri">Missouri</option> <option value="Montana">Montana</option> <option value="Nebraska">Nebraska</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="New Jersey">New Jersey</option> <option value="New Mexico">New Mexico</option> <option value="New York">New York</option> <option value="North Carolina">North Carolina</option> <option value="North Dakota">North Dakota</option> <option value="Ohio">Ohio</option> <option value="Oklahoma">Oklahoma</option> <option value="Oregon">Oregon</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Rhode Island">Rhode Island</option> <option value="South Carolina">South Carolina</option> <option value="South Dakota">South Dakota</option> <option value="Tennessee">Tennessee</option> <option value="Texas">Texas</option> <option value="Utah">Utah</option> <option value="Vermont">Vermont</option> <option value="Virginia">Virginia</option> <option value="Washington">Washington</option> <option value="West Virginia">West Virginia</option> <option value="Wisconsin">Wisconsin</option> <option value="Wyoming">Wyoming</option> </select> </label> <label class="email"> <span class="text-form">E-mail:</span> <input name="email" type="text" value=""> </label> </div> </div> <label class="message"> <span class="text-form">Comments:</span> <textarea name="comments"></textarea> </label> <label> <span class="text-form2">Attach a photo:</span> <input id="photo" name="file[]" type="file" class="fl" > </label> <label> <span class="text-form2">Attach a photo:</span> <input id="photo" name="file[]" type="file" class="fl" > </label> <label> <span class="text-form2">Attach a photo:</span> <input id="photo" name="file[]" type="file" class="fl" > </label> <div class="but"><a class="link1 link-color2" data-type="submit" onClick="document.getElementById('form2').submit()">Submit</a></div> </fieldset> </form> From what I've been reading you need to tell the php to put it to a temporary file from the submit.. then move it to the file name and then somehow include that file name in the php email back. So maybe a url and its private or htaccess? or does it get included as attachment in the mail? Im not sure if i should be using 'id' or 'name' in the html form etc and how to tie it together. Any help or guides much appreciated. Thanks Wolfsta I am attempting to get my email form with file attachment to work. Apparently the file is not reaching getting to the validation portion of the page I have switched $_FILES['X'] on line 203 from file to fakefile as they are labeled in the form also I am employing css hacks to change the input file upload field to have a custom button example -> http://visualrealityink.com/dev/clients/arzan/snell_form_final/form.php here is my code I appreciate any help Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #form_container{ display:block; position:absolute; width:610px; min-height:450px; background:#f8f8f8; padding: 5px 5px 5px 5px; font-family:Arial, Helvetica, sans-serif; font-size:14px; } #form { min-height:450px; width:100%; background:#ececec; padding:0 0 0 0; } #formheader { background:url(images/form2_08.png) no-repeat #2f2f2f; margin:0 0 0 0; padding:0 0 0 0; width:631; height:30px;} form{margin:35px 0 0 35px;} fieldset div { margin:0.3em 0; clear:both; } label { float:left; width:10em; text-align:left; margin-right:1em; font-family:Arial, Helvetica, sans-serif; font-size:14px; } input { padding:0.15em; margin:0 0 0 -110px; width:300px; background:url(images/inputbg.png) no-repeat; border:0px solid #ddd; background:#fafafa; -moz-border-radius:0.4em; -khtml-border-radius:0.4em; } .bg2{background:url(images/inputbg.png) no-repeat; height:28px; line-height:28px;} fieldset { border:0px solid #ddd; padding:0 0.5em 0.5em; margin:0 0 0 -100px; } #details{font-size:10px;} #logo{background:url(images/form2_11.png) no-repeat; width:189px; height:238px; margin:-200px 0 0 400px; position:absolute;} #submit{margin:14px 0 0 -5px; border:none; position:absolute; cursor:pointer; cursor:hand;} #reset{border:none; margin:14px 0 0 115px; position:absolute; cursor:pointer; cursor:hand; } #divinputfile{ background:url(images/form2_27.png) no-repeat 100% 1px; height:43px; line-height:43px; width:340px; }#divinputfile #filepc{ opacity: 0.0; -moz-opacity: 0.0; filter: alpha(opacity=00); font-size:18px; margin:0 0 0 0; cursor:hand; cursor:pointer; } #fakeinputfile{ margin-top:-28px; } #fakeinputfile #fakefilepc{ background:url(images/inputbg2.png) no-repeat; style:none; width:240px; height:28px; line-height:28px; border:0; margin:5px 0 0 0; font-size:18px; font-family:Arial; } button { cursor: hand; cursor: pointer; padding: 0px; margin: 0 0 0 0; } a.link_button{ cursor: hand; cursor: pointer; } .fileupload{ margin:0 0 0 50px; } input[type="file"] { cursor: pointer; } .error{font-size:9px; font-family:Arial, Helvetica, sans-serif; color:#F00; } .error ul { text-decoration: none; list-style: none; } .error li { color: #F00;} .captcha_form { margin: 0 0 0 -45px; width:235px; } #captchaimage{ padding:0 0 10px 0;} .small { font-size:9px;} </style> </head> <body> <?php if ($_POST['_submit_check']) { // If validate_form( ) returns errors, pass them to show_form( ) if ($form_errors = validate_form()) { show_form($form_errors); } else { // The submitted data is valid, so process it process_form(); } } else { // The form wasn't submitted, so display show_form(); } function show_form($errors = '') { // If the form is submitted, get defaults from submitted parameters if ($_POST['_submit_check']) { $defaults = $_POST; } else { // Otherwise, set our own defaults: medium size and yes to delivery $defaults = array('IssueDate' => '','ExpiryDate' => ''); } if ($errors) { $error_text = 'You need to correct the following errors:'; $error_text .= '<br /><ul>'; $error_text .= implode('<li>',$errors); $error_text .= '</li></ul>'; } else { // No errors? Then $error_text is blank $error_text = ''; } include 'formhelpers.php' ?> <div id="form_container"> <div id="form"> <br /> <div id="formheader"> </div> <form method="POST" action="<?php print $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data"> <span class="error"> <?php print $error_text ?> </span> <input type="hidden" name="_submit_check" value="1"/> <div> <label for="name">Name: </label> <?php input_text('name', $defaults) ?> </div> <div> <label for="email">Email:</label> <?php input_text('email', $defaults) ?> </div> <div> Attach Resume: <span class="small">(1MB : PDF : DOC : DOCX : TXT)</span> </div> <div> <!--<input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> <label for="userfile"></label> <input type="file" name="userfile" id="userfile"/> </div>--> <div id="divinputfile"> <input name="file" type="file" size="30" id="filepc" onchange="document.getElementById('fakefilepc').value = this.value;"/> <div id="fakeinputfile"> <input name="fakefile" type="text" class="link_button" id="fakefilepc" /> </div> </div> <div id="captchaimage"><img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /></div> <div><label for="email"><a style="text-decoration: none" href="#" onclick="document.getElementById('captcha').src = 'securimage/securimage_show.php?' + Math.random(); return false">New Captcha: </a></label> <input type="text" name="captcha_code" class="captcha_form" size="10" maxlength="6" /> </div> <button type="submit" value="submit" id="submit" ><img src="images/form2_33.png" /></button> <button type="reset" value="reset" id="reset" ><img src="images/form2_37.png" /></button> </form> </div> <div id="logo"></div> </div> </div> <?php } function validate_form() { $errors = array( ); // name is required if ($_POST['name'] == "") { $errors[ ] = 'Please enter your name.'; } if (! strlen(trim($_POST['email']))) { $errors[ ] = 'Please enter your Email.'; } if (! preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $_POST['email'])) { $errors[ ] = 'Please enter a valid e-mail address'; } $filename=$_FILES['file']['name']; //For size if($_FILES["file"]["size"]>1000000) //1 mb { $errors[ ] = "File size should be less than 1MB"; } // for extention $ext = end(explode('.', $filename)); if($ext=='doc' || $ext=='txt' || $ext=='pdf' || $ext=='docx' ) { echo "write the code to upload file"; $max_allowed_file_size = 1024; // size in KB $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 //copy the temp. uploaded file to uploads folder $upload_folder = 'upload/'; $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; $tmp_path = $_FILES["file"]["tmp_name"]; if(is_uploaded_file($tmp_path)) { if(!copy($tmp_path,$path_of_uploaded_file)){ echo 'error while copying the uploaded file'; die(); } } } else { $errors[ ] = "Only doc or pdf or txt file is allowed: $filename "; } return $errors; } function process_form() { $image = "http://www.visualrealityink.com/dev/clients/arzan/snell_form/images/email.png"; include_once('Mail.php'); include_once('Mail_Mime/mime.php'); $to = 'george@visualrealityink.com'; $text = $image . "<br />" . $values['name'] . "submitted a resume on our website. Please review the applications and contact the candidate if their resume is a fit for any open opportunities with the company. <br><br> Thank you. <br><br> SEI Team"; $message=new Mail_mime(); $message=setTXTBody($text); $message=addAttachment($path_of_uploaded_file); $body = $message->get(); $extraheaders = array("From"=>$formValues['email'], "Subject"=>$subject, "Reply-To"=>$formValues['email']); $headers = $message->headers($extraheaders); $mail = Mail::factory("mail"); $mail->send($to, $headers, $body); echo "email sent"; } ?> </body> </html> |