Return to Snippet

Revision: 23923
at February 16, 2010 15:59 by vagrantradio

Initial Code
<!-- The javascript, put in head or above last body tag on same page as the form -->
<script type="text/javascript" src="../scripts/ajaxupload.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var upload = new Ajax_upload('#userfile', {
		//upload script
		action: 'upload.php',
		onSubmit : function(file, extension){
		//get the input values
		//show loading animation
		var name = $("input#name").val();
		var email = $("input#email").val();
		var company = $("input#company").val();
		var userfile = $("input#userfile").val();
		var image = $("input:checked").val();
		var message = $("textarea#message").val();
		//validate form
		  $(":input").css("border", "1px solid #aaa");
		if (name == "") {
			$("input#name").css("border", "2px solid #900").focus();
			$("#errors").show().text("Please enter your name");
			return false;
		} else if (email == "") {
			$("input#email").css("border", "2px solid #900").focus();
			$("#errors").show().text("Please enter an email address");
			return false;
		} else if (company == "") {
			$("input#company").css("border", "2px solid #900").focus();
			$("#errors").show().text("Please enter a company");
			return false;
		if (! (extension && /^(jpg|png|jpeg|gif|zip|xls|xlsx|csv|txt|tif|tiff|pdf|doc|eps)$/.test(extension))){
       // extension is not allowed
			 $("<span class='error'>Error: Not a valid file extension</span>").appendTo("#file_holder #errormes");
			// cancel upload
       return false;
			} else {
			  // get rid of error
			upload.setData({'name': name, 'image': image, 'message': message, 'email': email, 'company': company, 'file': file});
		//show loading div
		onComplete : function(file, response){
		//hide the laoding animation
		//add display:block to sucess message
		$(".success").css("display", "block");
		//find the div in the iFrame	
		var oBody = $(".iframe").contents().find("div");
		//add the iFrame to the errormes td
		$(oBody).appendTo("#file_holder #errormes");
<!-- The form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
  <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>
  <td id="errors"></td>
  <td>Full Name: </td> 
  <td><input name="name" id="name" type="text" size="33" maxlength="40" /></td>
	<td>Email: </td>
  <td><input name="email" id="email" type="text" size="33" maxlength="40" /></td>
  <td>Company: </td>
  <td><input name="company" id="company" type="text" size="33" maxlength="40" /></td>
  <td>Message: </td>
  <td><textarea rows="2" cols="25" class="text" id="message" name="message" maxlength="240"></textarea></td>
  <td>Is this an image file?</td>
  <td><input name="image" type="checkbox" id="image" value="image" /> (Includes images in zip and rar files)</td>
  <td>Choose file(s) to upload: </td>
	<td><input id="userfile" class="input" type="file" name="userfile" /></td>
  <td colspan="2"><div id="loading">Loading, please wait.. <img src="/images/ajax-loader.gif" alt="Loading"></div></td>
  <td id="errormes" colspan="2"></td>
  <style type="text/css">
	#file_holder {display:block;}
  <td><input type="submit" value="submit" class="button2" /></td>
<?php //The uploader, put in separate upload.php file ?>
$max_filesize = 10000000; // Maximum filesize in BYTES.
$allowed_filetypes = array('.jpg','.jpeg','.gif','.png'); // These will be the types of file that will pass the validation.
	 $filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
	 $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
	 $file_strip = str_replace(" ","_",$filename); //Strip out spaces in filenameextension).
$cookie = $_COOKIE['remote_user'];//puts upload in logged in users folder by name else promts them to log in
		if($cookie == "") {
		echo "Cookie has expired, please log back in and try your upload again.";
		} else {
		$upload_path = '/nfs/www/'. $cookie .'/'; 
   // Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize) {
      die('<div class="error">The file you attempted to upload is too large.</div>');
 // Check if the filetype is allowed, if not DIE and inform the user.
	if(!in_array($ext,$allowed_filetypes)) {
	 		die('<div class="error">The file you attempted to upload is not allowed.</div>');
   // Check if we can upload to the specified path, if not DIE and inform the user.
   if(!is_writable($upload_path)) {
      die('<div class="error">You cannot upload to the /'. $cookie .'/ folder. The permissions must be changed.</div>');
	 if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $file_strip)) {
        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.
				 //post the form info
				$name = $_POST['name']; 
				$email = $_POST['email'];
				$company = $_POST['company'];
				$image = $_POST['image'];
				$message = $_POST['message'];
				//Send the mail specifics
				$headers .= "MIME-Version: 1.0
				$headers .= "Content-type: text/html; charset=iso-8859-1
				$headers .= "From: [email protected]
				if ($image == "image") { 
				$headers .= "CC: [email protected]
  			$sendto = "you@yourdomain";
				$subject = "$name uploaded a file to yourdomain";
				$message = "Name: $name<br />Email: <a href=\"mailto:$email\">$email</a><br />Company: $company<br />File name: <a href=\"$cookie/$file_strip\">$file_strip</a><br /><br />Message: $message";
				// send the email
				mail($sendto, $subject, $message, $headers);
      } else {
         echo '<div class="error">'. $file_strip .' was not uploaded.  Please try again.</div>'; // It failed :(.

Initial URL

Initial Description
Uses ajax upload from Complete working script with front and back end validation. Enjoy.

Initial Title

Initial Tags

Initial Language