Jump to content

SwfUpload Custom save location with cookies


papillonstudios

Recommended Posts

I am creating a photo ordering script that uploads files to our server then we download and print them(similar ti walmart) and for every time you visit the upload page it creates a cookie with a reference number that is used later while uploading files to create a hierarchy that allows me and the staff to easily organize what photos are printed in what size.

 

the hierarchy is this:

uploads/[referenceNumber]/[photoSize]/[photoQuantity]/[the photos]

 

I am using SwfUpload as my file upload script and I need to change the location of $save_path

 

The problem Im having is when creating the folders for the upload path using the cookies. I can do this:

die($_COOKIE['photoSize']);

and it will output the photo size.

 

but won't create the directory. and the photos are uploaded to uploads/ instead

 

heres all my code

*NOTE some of the code below is being load from within another file that has all the connection info, etc. and some files are broken up into other files like wordpress does with header.php, footer.php etc,*

 

header.php

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Print Photos Online | D & I Photo</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<!--[if gte IE 9]>
  <style type="text/css">
    .gradient {
       filter: none;
    }
  </style>
<![endif]-->
<link href="default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="swfupload/swfupload.js"></script>
<script type="text/javascript" src="js/swfupload.queue.js"></script>
<script type="text/javascript" src="js/fileprogress.js"></script>
<script type="text/javascript" src="js/handlers.js"></script>
<script type="text/javascript">
	var upload1, upload2;

	window.onload = function() {
		upload1 = new SWFUpload({
			// Backend Settings
			upload_url: "upload.php",
			post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},

			// File Upload Settings
			file_size_limit : "102400",	// 100MB
			file_types : "*.*",
			file_types_description : "All Files",
			file_upload_limit : "10",
			file_queue_limit : "0",

			// Event Handler Settings (all my handlers are in the Handler.js file)
			file_dialog_start_handler : fileDialogStart,
			file_queued_handler : fileQueued,
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,

			// Button Settings
			button_image_url : "XPButtonUploadText_61x22.png",
			button_placeholder_id : "spanButtonPlaceholder1",
			button_width: 61,
			button_height: 22,

			// Flash Settings
			flash_url : "swfupload/swfupload.swf",


			custom_settings : {
				progressTarget : "fsUploadProgress1",
				cancelButtonId : "btnCancel1"
			},

			// Debug Settings
			debug: false
		});

		upload2 = new SWFUpload({
			// Backend Settings
			upload_url: "upload.php",
			post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},

			// File Upload Settings
			file_size_limit : "200",	// 200 kb
			file_types : "*.jpg;*.gif;*.png",
			file_types_description : "Image Files",
			file_upload_limit : "1000",
			file_queue_limit : "5",

			// Event Handler Settings (all my handlers are in the Handler.js file)
			file_dialog_start_handler : fileDialogStart,
			file_queued_handler : fileQueued,
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,

			// Button Settings
			button_image_url : "XPButtonUploadText_61x22.png",
			button_placeholder_id : "spanButtonPlaceholder2",
			button_width: 61,
			button_height: 22,

			// Flash Settings
			flash_url : "swfupload/swfupload.swf",

			swfupload_element_id : "flashUI2",		// Setting from graceful degradation plugin
			degraded_element_id : "degradedUI2",	// Setting from graceful degradation plugin

			custom_settings : {
				progressTarget : "fsUploadProgress2",
				cancelButtonId : "btnCancel2"
			},

			// Debug Settings
			debug: false
		});

     }
</script>
</head>
<body>

<div id="navigation">
	<ul>
		<?=fx_list_pages();?>
	</ul>

	<div style="clear: both;"></div>

</div>

<div id="header">
	<A href="<?=SITE_URL?>" ><img id="logo" src="images/logo.png" border="0" alt="Logo" /></a>
</div>

<div id="promo" class="gradient">
	<h2>Digital Photos from 19 Cents!</h2>
</div>

<div id="wrapper">

	<div id="sidebar">
		<? get_sidebar(); ?>
	</div>

	<div id="content">

 

orderphotos.php(Internally loaded)

<?php
if (!isset($_GET['step'])) {
$step = 1;
}
else {
$step = $_GET['step'];

}

if ($step == 1) {
	if (!isset($_COOKIE['referenceNumber'])) {
		$referenceNum = 0 . 0 . mt_rand(10000, 99999);

		$query = mysql_query("SELECT * FROM `reference` WHERE referenceNumber='$referenceNum'");

		if (($query = mysql_num_rows($query)) > 0) {

			$validNum = 0;

			while ($validNum = 0) {
				$referenceNum = 0 . 0 . mt_rand(10000, 99999);

				$query = mysql_query("SELECT * FROM `reference` WHERE referenceNumber='$referenceNum'");

				if (($query = mysql_num_rows($query)) > 0) {
					$validNum = 0;
				}
				else {
					$validNum = 1;
				}

			}	
		}


		$_SESSION['referenceNumber'] = $referenceNum;
		//setcookie("referenceNumber", $referenceNum);
		$path = 'uploads/' . $referenceNum;
		mkdir($path, 0755);
	}
	echo '<h2>What size of photos are you ordering?</h2>';
    	?>
		<form id="orderForm" action="<?=the_permalink()?>&step=2" method="post">
			<table>
				<tr>
					<td>
						<select name="size">
							<optgroup label="Single Sizes">
								<option value="4x6">4x6</option>
								<option value="5x7">5x7</option>
								<option value="8x10">8x10</option>
								<option value="11x14">11x14</option>
								<option value="16x20">16x20</option>
							</optgroup> 
						</select>
					</td>
				</tr>
				<tr>
					<td><input type="submit" name="step1" value="Continue->" /></td>
				</tr>
			</table>
		</form>
	<?php
}
else if ($step == 2) {
	echo '<h3>How many ' . $_POST['size'] . ' photos do you want each photo you are uploading?</h3>';
	?>
		<form id="orderForm" action="<?=the_permalink()?>&step=3" method="post">
			<input type="hidden" name="size" value="<?=$_POST['size']?>" />
			<table>
				<tr>
					<td><input type="text" name="quanity" /></td>
				</tr>
				<tr>
					<td><input type="submit" name="step1" value="Continue->" /></td>
				</tr>
			</table>
		</form>
	<?php
}
else if ($step == 3) {
		$_SESSION['photoSize'] = $_POST['size'];
		$_SESSION['photoQuantity'] = $_POST['quanity'];

		print($_SESSION['photoQuantity']);
		//setcookie("photoSize", $_POST['size']);
		//setcookie("photoQuanity", $_POST['quanity']);

		if (count($_FILES)) {
    	    	// Handle degraded form uploads here.  Degraded form uploads are POSTed to index.php.  SWFUpload uploads
    	    	// are POSTed to upload.php
    	    }
	?>
		<div id="main">
			<div id="content">
				<h2>Upload Your Photos Online!</h2>
				<form id="form1" action="index.php" method="post" enctype="multipart/form-data">
					<p>Use the form below to upload your photos for printing.</p>
					<table>
						<tr valign="top">
							<td>
								<div>
									<div class="fieldset flash" id="fsUploadProgress1">
										<span class="legend">Your Files To Be Uploaded</span>
									</div>
									<div style="padding-left: 5px;">
										<span id="spanButtonPlaceholder1"></span>
										<input id="btnCancel1" type="button" value="Cancel Uploads" onclick="cancelQueue(upload1);" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" />
										<br />
									</div>
								</div>
							</td>
						</tr>
					</table>
				</form>
			</div>
		</div>
	<?php
}
else if ($step = 4) {
	if (!isset($_POST['sendMail'])) {
	?>
	<h2 id="formHeading">We need to verify your information!</h2>
	<form action="<?=the_permalink()?>" method="post" id="orderForm" />
		<table>
			<tr>
				<td>First Name</td>
				<td>Last Name</td>
			</tr>
			<tr>
				<td><input type="text" name="firstName" value="<?=$_SESSION['first_name']?>" /></td>
				<td><input type="text" name="lastName" value="<?=$_SESSION['last_name']?>" /></td>
			</tr>
			<tr>
				<td>Email</td>
			</tr>
			<tr>
				<td><input type="text" name="email" value="<?=$_SESSION['email']?>" /></td>
			</tr>
			<tr>
				<td>Phone</td>
			</tr>
			<tr>
				<td><input type="text" name="phone" value="<?=$_SESSION['homePhone']?>" /></td>
			</tr>
			<tr>
				<td><input type="submit" name="sendMail" value="Place Order!" /></td>
			</tr>

		</table>
	</form>
	<?php
	}
	else {

		$to = 'mail@someurl.com';
		$subject = 'You have a new Photo Order!';
		$message = 'You have an order from ' . $_POST['firstName'] . ' ' . $_POST['lastName'] . '. 
		The reference number is: ' . $_COOKIE['referenceNumber'] . '! All Photos are in place on the server!
		Their email is ' . $_POST['email'] . '
		and their Phone Number is ' . $_POST['phone'];
		$headers = "From: email@someurl.com \r\n";

		if (mail($to,$subject,$message, $headers)) {

			$to2 = $_POST['email'];
			$subject2 = 'You order has been placed!';
			$message2 = 'Thank You for ordering photos from D&I Photo. Your order number is: ' . $_COOKIE['referenceNumber'] . '.
			If you have any question please call [PhoneNumber] for Listowel
			or [PhoneNumber] for Fergus';
			$headers2 = 'From: email@someurl.com \r\n';

			if (mail($to2,$subject2,$message2, $headers2)) {
			    	setcookie("referenceNumber", "", time() - 3600);
			    	setcookie("photoSize", "", time() - 3600);
			    	setcookie("photoQuanity", "", time() - 3600);
			}

			echo 'You order has been placed!';
			echo '<a href="index.php?action=page&paged=2" class="button">Place a new Order!</a>';
		}
		else {
			echo 'Something went wrong please email <a href="mailto:mail@someurl.com">Tech Support</a>';
		}
	}

}
?>

 

upload.php(The Upload Handler)

<?php

include('config.php');

// Code for Session Cookie workaround
if (isset($_POST["PHPSESSID"])) {
	session_id($_POST["PHPSESSID"]);
} else if (isset($_GET["PHPSESSID"])) {
	session_id($_GET["PHPSESSID"]);
}

session_start();

// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
	header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
	echo "POST exceeded maximum allowed size.";
	exit(0);
}

// Settings

$save_path = "uploads/" . $_COOKIE['referenceNumber'] . '/' . $_COOKIE['photoSize'];

mkdir($save_path, 0755);
$save_path = "uploads/" . $_COOKIE['referenceNumber'] . '/' . $_COOKIE['photoSize'] . '/' . $_COOKIE['photoQuanity']. '/';
mkdir($save_path, 0755);
//die($save_path);
$upload_name = "Filedata";
$max_file_size_in_bytes = 2147483647;				// 2GB in bytes
$extension_whitelist = array("jpg", "gif", "png");	// Allowed file extensions
$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';				// Characters allowed in the file name (in a Regular Expression format)

// Other variables	
$MAX_FILENAME_LENGTH = 260;
$file_name = "";
$file_extension = "";
$uploadErrors = array(
        0=>"There is no error, the file uploaded with 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"
);


// Validate the upload
if (!isset($_FILES[$upload_name])) {
	HandleError("No upload found in \$_FILES for " . $upload_name);
	exit(0);
} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
	HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
	exit(0);
} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
	HandleError("Upload failed is_uploaded_file test.");
	exit(0);
} else if (!isset($_FILES[$upload_name]['name'])) {
	HandleError("File has no name.");
	exit(0);
}

// Validate the file size (Warning: the largest files supported by this code is 2GB)
$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
if (!$file_size || $file_size > $max_file_size_in_bytes) {
	HandleError("File exceeds the maximum allowed size");
	exit(0);
}

if ($file_size <= 0) {
	HandleError("File size outside allowed lower bound");
	exit(0);
}


// Validate file name (for our purposes we'll just remove invalid characters)
$file_name = preg_replace('/[^'.$valid_chars_regex.']|\.+$/i', "", basename($_FILES[$upload_name]['name']));
if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
	HandleError("Invalid file name");
	exit(0);
}


// Validate that we won't over-write an existing file
if (file_exists($save_path . $file_name)) {
	HandleError("File with this name already exists");
	exit(0);
}

// Validate file extension
$path_info = pathinfo($_FILES[$upload_name]['name']);
$file_extension = $path_info["extension"];
$is_valid_extension = false;
foreach ($extension_whitelist as $extension) {
	if (strcasecmp($file_extension, $extension) == 0) {
		$is_valid_extension = true;
		break;
	}
}
if (!$is_valid_extension) {
	HandleError("Invalid file extension");
	exit(0);
}

// Validate file contents (extension and mime-type can't be trusted)
/*
	Validating the file contents is OS and web server configuration dependant.  Also, it may not be reliable.
	See the comments on this page: http://us2.php.net/fileinfo

	Also see http://72.14.253.104/search?q=cache:3YGZfcnKDrYJ:www.scanit.be/uploads/php-file-upload.pdf+php+file+command&hl=en&ct=clnk&cd=8&gl=us&client=firefox-a
	 which describes how a PHP script can be embedded within a GIF image file.

	Therefore, no sample code will be provided here.  Research the issue, decide how much security is
	 needed, and implement a solution that meets the needs.
*/


// Process the file
/*
	At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
	 could be done such as creating an entry in a database or generating a thumbnail.

	Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
	been saved.
*/
if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
	HandleError("File could not be saved.");
	exit(0);
}

exit(0);


/* Handles the error output. This error message will be sent to the uploadSuccess event handler.  The event handler
will have to check for any error messages and react as needed. */
function HandleError($message) {
echo $message;
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.