UPLOAD FILE TO SERVER AND SEND MAIL


/ Published in: PHP
Save to your folder(s)

Uses ajax upload from http://valums.com/ajax-upload/. Complete working script with front and back end validation. Enjoy.


Copy this code and paste it in your HTML
  1. <!-- The javascript, put in head or above last body tag on same page as the form -->
  2. <script type="text/javascript" src="../scripts/ajaxupload.js"></script>
  3. <script type="text/javascript">
  4. $(document).ready(function() {
  5. var upload = new Ajax_upload('#userfile', {
  6. //upload script
  7. action: 'upload.php',
  8. onSubmit : function(file, extension){
  9. //get the input values
  10. $('.error').hide()
  11. //show loading animation
  12. $("#loading").show();
  13. var name = $("input#name").val();
  14. var email = $("input#email").val();
  15. var company = $("input#company").val();
  16. var userfile = $("input#userfile").val();
  17. var image = $("input:checked").val();
  18. var message = $("textarea#message").val();
  19. //validate form
  20. $(":input").css("border", "1px solid #aaa");
  21. $("#errors").hide();
  22. if (name == "") {
  23. $("input#name").css("border", "2px solid #900").focus();
  24. $("#errors").show().text("Please enter your name");
  25. return false;
  26. } else if (email == "") {
  27. $("input#email").css("border", "2px solid #900").focus();
  28. $("#errors").show().text("Please enter an email address");
  29. return false;
  30. } else if (company == "") {
  31. $("input#company").css("border", "2px solid #900").focus();
  32. $("#errors").show().text("Please enter a company");
  33. return false;
  34. }
  35. if (! (extension && /^(jpg|png|jpeg|gif|zip|xls|xlsx|csv|txt|tif|tiff|pdf|doc|eps)$/.test(extension))){
  36. // extension is not allowed
  37. $("#loading").hide();
  38. $("<span class='error'>Error: Not a valid file extension</span>").appendTo("#file_holder #errormes");
  39. // cancel upload
  40. return false;
  41. } else {
  42. // get rid of error
  43. $('.error').hide();
  44. }
  45. upload.setData({'name': name, 'image': image, 'message': message, 'email': email, 'company': company, 'file': file});
  46. //show loading div
  47. $("#file_title").show();
  48. },
  49. onComplete : function(file, response){
  50. //hide the laoding animation
  51. $("#loading").hide();
  52. //add display:block to sucess message
  53. $(".success").css("display", "block");
  54. //find the div in the iFrame
  55. var oBody = $(".iframe").contents().find("div");
  56. //add the iFrame to the errormes td
  57. $(oBody).appendTo("#file_holder #errormes");
  58. }
  59. });
  60. });
  61. </script>
  62.  
  63. <!-- The form -->
  64. <form action="upload.php" method="post" enctype="multipart/form-data">
  65. <table>
  66. <tr>
  67. <td class="strong" colspan="2">Please Enter your name, email address and company below.<br /> All fields are required, message is optional. All files should be under 10mb.</td>
  68. </tr>
  69. <tr>
  70. <td>&nbsp;</td>
  71. <td>&nbsp;</td>
  72. </tr>
  73. <tr>
  74. <td></td>
  75. <td id="errors"></td>
  76. </tr>
  77. <tr>
  78. <td>Full Name: </td>
  79. <td><input name="name" id="name" type="text" size="33" maxlength="40" /></td>
  80. </tr>
  81. <tr>
  82. <td>Email: </td>
  83. <td><input name="email" id="email" type="text" size="33" maxlength="40" /></td>
  84. </tr>
  85. <tr>
  86. <td>Company: </td>
  87. <td><input name="company" id="company" type="text" size="33" maxlength="40" /></td>
  88. </tr>
  89. <tr>
  90. <td>Message: </td>
  91. <td><textarea rows="2" cols="25" class="text" id="message" name="message" maxlength="240"></textarea></td>
  92. </tr>
  93. <tr>
  94. <td>Is this an image file?</td>
  95. <td><input name="image" type="checkbox" id="image" value="image" /> (Includes images in zip and rar files)</td>
  96. </tr>
  97. <tr>
  98. <td>Choose file(s) to upload: </td>
  99. <td><input id="userfile" class="input" type="file" name="userfile" /></td>
  100. </tr>
  101. <tr>
  102. <td colspan="2"><div id="loading">Loading, please wait.. <img src="/images/ajax-loader.gif" alt="Loading"></div></td>
  103. </tr>
  104. <tr>
  105. <td id="errormes" colspan="2"></td>
  106. </tr>
  107. <noscript>
  108. <style type="text/css">
  109. #file_holder {display:block;}
  110. </style>
  111. <tr>
  112. <td>&nbsp;</td>
  113. <td><input type="submit" value="submit" class="button2" /></td>
  114. </tr>
  115. </noscript>
  116. </table>
  117. </form>
  118.  
  119. <?php //The uploader, put in separate upload.php file ?>
  120. <?php
  121.  
  122. $max_filesize = 10000000; // Maximum filesize in BYTES.
  123. $allowed_filetypes = array('.jpg','.jpeg','.gif','.png'); // These will be the types of file that will pass the validation.
  124. $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
  125. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
  126. $file_strip = str_replace(" ","_",$filename); //Strip out spaces in filenameextension).
  127. $cookie = $_COOKIE['remote_user'];//puts upload in logged in users folder by name else promts them to log in
  128. if($cookie == "") {
  129. echo "Cookie has expired, please log back in and try your upload again.";
  130. } else {
  131. $upload_path = '/nfs/www/yourdomain.com/uploads/'. $cookie .'/';
  132. }
  133. // Now check the filesize, if it is too large then DIE and inform the user.
  134. if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
  135. die('<div class="error">The file you attempted to upload is too large.</div>');
  136. }
  137. // Check if the filetype is allowed, if not DIE and inform the user.
  138. if(!in_array($ext,$allowed_filetypes)) {
  139. die('<div class="error">The file you attempted to upload is not allowed.</div>');
  140. }
  141. // Check if we can upload to the specified path, if not DIE and inform the user.
  142. if(!is_writable($upload_path)) {
  143. die('<div class="error">You cannot upload to the /'. $cookie .'/ folder. The permissions must be changed.</div>');
  144. }
  145. if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $file_strip)) {
  146. echo '<div class="success">'. $file_strip .' uploaded successfully, view it <a href="/uploads/'. $cookie .'/'. $file_strip . '" title="Your File" target="_blank">here</a>.</div>'; // It worked.
  147. //post the form info
  148. $name = $_POST['name'];
  149. $email = $_POST['email'];
  150. $company = $_POST['company'];
  151. $image = $_POST['image'];
  152. $message = $_POST['message'];
  153. //Send the mail specifics
  154. $headers .= "MIME-Version: 1.0
  155. ";
  156. $headers .= "Content-type: text/html; charset=iso-8859-1
  157. ";
  158. $headers .= "From: [email protected]
  159. ";
  160. if ($image == "image") {
  161. $headers .= "CC: [email protected]
  162. ";
  163. }
  164. $sendto = "you@yourdomain";
  165. $subject = "$name uploaded a file to yourdomain";
  166. $message = "Name: $name<br />Email: <a href=\"mailto:$email\">$email</a><br />Company: $company<br />File name: <a href=\"http://www.yourdomain.com/uploads/$cookie/$file_strip\">$file_strip</a><br /><br />Message: $message";
  167. // send the email
  168. mail($sendto, $subject, $message, $headers);
  169. } else {
  170. echo '<div class="error">'. $file_strip .' was not uploaded. Please try again.</div>'; // It failed :(.
  171. }
  172. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.