Solved

php upload file understanding

Posted on 2010-08-25
5
251 Views
Last Modified: 2012-05-10
I'm trying to figure out the below upload script that I'm using with SWFUpload.  I don't see where it's actually storing the files in the directory.  The reason why I want to figure this out is that I want to resize the image files before they're stored in the directory, any ideas on how to access the collection of files.  This is a multi-file upload script.  It does upload the files, so I know its working.

<?php
	#	SWFUpload Email Notify
		# SWFUpload upload.php with simple file saving and email reporting
		# by Eric Pecoraro ( eric dot pecoraro at shepard dot com )
		# ***USE AT YOUR OWN RISK***  ***NO WARRENTIES EXPRESSED OR IMPLIED***
		# THIS SCRIPT WAS *NOT* WRITTEN FOR SECURITY, BUT RATHER AS SIMPLE PHP UPLOAD IMPLEMENTATION.
		# FEEL FREE TO USE/CHANGE/MODIFY/REDISTRIBUTE. Please notify me with improvements.
		# Developed as sample to be used in conjunction with SWFUpload (http://www.swfupload.org)
		# ABSTRACT
		# Saves SWFUpload uploaded files to a directory and intelligently reports on the process via email. 
		# SIMPLE SETUP, UP & RUNNING IN A FEW MINUTES
		# 1. Replace the original "upload.php" files from the SWFUpload v2.1.0 package with this file.
		# 2. Assign your email address to $upload_notify_email below.
		# 3. Create a PHP writable "uploads" directory as follows: swfupload/demos/uploads
	#	Setup SWFUpload Email Notify
	#	---------------	
		$upload_email_reporting = true ; 	// true or false (false turns email reporting off)
		$upload_notify_email = 'test@gmail.com' ;  	// enter your valid email address
		$upload_directory = '/home/swfupload/uploads' ; // leave blank for default
		# DEFINING $upload_directory
		# Must point to a PHP writable directory
		# See http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html for dealing with PHP permissions
		/*
		The default directory for this script is set to "uploads" directory 
		in the same directory as the index.php of the SWFUpload demo files:
			# SWFUpload v2.1.0 Beta.zip (SWFUpload package)
				# swfupload/demos/uploads
		This 'uploads' directory may not exist with the SWFUploads package and may need created (with PHP write permissions).
		In any case, this script will send an email message concerning the status of the upload directory.
		*/
	#	PHP Email Configuration Test
	#	---------------	
		# Set to "true" to test if your server's PHP mail() function configuration works, by attempting to upload one file.
		# A simple email will be sent per upload attempt, letting you know PHP's mail() funciton is working.
		$test_php_mail_config = false ; // true or false
	#	---------------
	#	NO MODIFICATIONS REQUIRED BELOW THIS LINE
	#	---------------
	#	CREATE DEFAULT UPLOAD DIRECTY LOCATION
	#	---------------	
		If ( !$upload_directory ) {
			$upload_directory = 'uploads' ; 
			$parent_dir = array_pop(explode(DIRECTORY_SEPARATOR, dirname(__FILE__)));
			$upload_directory = substr(dirname(__FILE__), 0, strlen(dirname(__FILE__)) - strlen($parent_dir) ) . $upload_directory ; 
		}
	#	---------------	
	#	EMAIL TESTS
		If ( !$upload_notify_email ) {
			$upload_email_reporting = false ;
		}
		# Sends one email per SWFUpload attempt. 
		if ( $test_php_mail_config == true ) {
			send_mail("SWFUpload Email Test: SUCCESS!",'Be sure to set $test_php_mail_config back to false so that SWFUpload Email Notify reporting is turned on.'); 
			$upload_email_reporting = false ;
		}
	#	---------------	
	#	TEST UPLOAD DIRECTORY
		If ( !file_exists($upload_directory) ) {	
			$msg = "The assigned SWFUpload directory, \"$upload_directory\" does not exist."; 
			send_mail("SWFUpload Directory Not Found: $upload_directory",$msg);
			$upload_email_reporting = false ;
		}
		if ( $upload_email_reporting == true ) {
			$uploadfile = $upload_directory. DIRECTORY_SEPARATOR . basename($_FILES['Filedata']['name']);   
			if ( !is_writable($upload_directory) ) {
				$msg = "The directory, \"$upload_directory\" is not writable by PHP. Permissions must be changed to upload files."; 
				send_mail("SWFUpload Directory Unwritable: $upload_directory",$msg);
				$upload_directory_writable = false ;
			} else {
				$upload_directory_writable = true ;
			}
		}
	// Work-around for setting up a session because Flash Player doesn't send the cookies
	if (isset($_POST["PHPSESSID"])) {
		session_id($_POST["PHPSESSID"]);
	}
	session_start();
	if ( !isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
		#	---------------	
		#	UPLOAD FAILURE REPORT
			if ( $upload_email_reporting == true ) {
				switch ($_FILES['Filedata']["error"]) {	
					case 1: $error_msg = 'File exceeded maximum server upload size of '.ini_get('upload_max_filesize').'.'; break;
					case 2: $error_msg = 'File exceeded maximum file size.'; break;
					case 3: $error_msg = 'File only partially uploaded.'; break;
					case 4: $error_msg = 'No file uploaded.'; break; 
				}
				send_mail("SWFUpload Failure: ".$_FILES["Filedata"]["name"],'PHP Error: '.$error_msg."\n\n".'Save Path: '.$uploadfile."\n\n".'$_FILES data: '."\n".print_r($_FILES,true)); 
			}
		echo "There was a problem with the upload";
		exit(0);
	} else {
		#	---------------	
		#	COPY UPLOAD SUCCESS/FAILURE REPORT
			if ( $upload_email_reporting == true AND $upload_directory_writable == true ) {
				if ( move_uploaded_file( $_FILES['Filedata']['tmp_name'] , $uploadfile ) ) {
				 send_mail("SWFUpload File Saved: ".$_FILES["Filedata"]["name"],'Save Path: '.$uploadfile."\n\n".'$_FILES data: '."\n".print_r($_FILES,true)); 
				}else{
				 send_mail("SWFUpload File Not Saved: ".$_FILES["Filedata"]["name"],'Save Path: '.$uploadfile."\n\n".'$_FILES data: '."\n".print_r($_FILES,true)); 
				}
			}
		echo "Flash requires that we output something or it won't fire the uploadSuccess event";
	}
	#	---------------	
	#	MAIL FUNCTION
		function send_mail($subject="Email Notify",$message="") { 
			global $upload_notify_email ; 
			$from = 'SWFUpload@mailinator.com' ; 
			$return_path = '-f '.$from ;
			mail($upload_notify_email,$subject,$message,"From: $from\nX-Mailer: PHP/ . $phpversion()");
		}
?>

Open in new window

0
Comment
Question by:cgray1223
  • 2
  • 2
5 Comments
 
LVL 5

Expert Comment

by:wmadrid1
ID: 33528104
The script is generating some error?
Check the files in the path
/home/swfupload/uploads
0
 

Author Comment

by:cgray1223
ID: 33528163
no the files are there.  I want to augment the script so that I have access to the files coming in.  I don't see where the script is accessing the files and then storing them.  I want to take the original file and create a resized image out of it and then store the new file.
0
 
LVL 1

Expert Comment

by:shaziashaikh
ID: 33528296
The script stores the files under /home/swfupload/uploads directory. Please see that you have directory created under /home as 'swfupload' and under 'swfupload' directory you have created the directory named 'uploads'. The script search for path on the server as /home/swfupload/uploads  and if this path is not exists then it will not store the files. Please create the directory structure as defined in the script or change the path in the $upload_directory variable.
0
 

Author Comment

by:cgray1223
ID: 33528337
I'm not sure we're on the same page.  I want to have access to the files programatically in the same php script that I pasted above so that I can take the incoming files and create the images in php and re-save them.  The directory is getting created and the files are there so that is not the issue.
0
 
LVL 5

Accepted Solution

by:
wmadrid1 earned 500 total points
ID: 33528371
Try the code below
To get working this code, the GD module must be enabled to can resize the image

there is a new function wich get a file and resize it, with the new width and height
if width or height is set to 0 (zero), then the function will mantain the aspect ratio

This is the code, where the function is called:
      //HERE IS THE CALL
      $newHeight = 100;
      $$newWidth = 100;
      resizeImage ($uploadfile, $uploadfile, $newHeight, $newWidth);

the var $uploadfile has the path of the file, the 2 first arguments are source and destination

<?php
        #       SWFUpload Email Notify
                # SWFUpload upload.php with simple file saving and email reporting
                # by Eric Pecoraro ( eric dot pecoraro at shepard dot com )
                # ***USE AT YOUR OWN RISK***  ***NO WARRENTIES EXPRESSED OR IMPLIED***
                # THIS SCRIPT WAS *NOT* WRITTEN FOR SECURITY, BUT RATHER AS SIMPLE PHP UPLOAD IMPLEMENTATION.
                # FEEL FREE TO USE/CHANGE/MODIFY/REDISTRIBUTE. Please notify me with improvements.
                # Developed as sample to be used in conjunction with SWFUpload (http://www.swfupload.org)
                # ABSTRACT
                # Saves SWFUpload uploaded files to a directory and intelligently reports on the process via email. 
                # SIMPLE SETUP, UP & RUNNING IN A FEW MINUTES
                # 1. Replace the original "upload.php" files from the SWFUpload v2.1.0 package with this file.
                # 2. Assign your email address to $upload_notify_email below.
                # 3. Create a PHP writable "uploads" directory as follows: swfupload/demos/uploads
        #       Setup SWFUpload Email Notify
        #       --------------- 
                $upload_email_reporting = true ;        // true or false (false turns email reporting off)
                $upload_notify_email = 'test@gmail.com' ;       // enter your valid email address
                $upload_directory = '/home/swfupload/uploads' ; // leave blank for default
                # DEFINING $upload_directory
                # Must point to a PHP writable directory
                # See http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html for dealing with PHP permissions
                /*
                The default directory for this script is set to "uploads" directory 
                in the same directory as the index.php of the SWFUpload demo files:
                        # SWFUpload v2.1.0 Beta.zip (SWFUpload package)
                                # swfupload/demos/uploads
                This 'uploads' directory may not exist with the SWFUploads package and may need created (with PHP write permissions).
                In any case, this script will send an email message concerning the status of the upload directory.
                */
        #       PHP Email Configuration Test
        #       --------------- 
                # Set to "true" to test if your server's PHP mail() function configuration works, by attempting to upload one file.
                # A simple email will be sent per upload attempt, letting you know PHP's mail() funciton is working.
                $test_php_mail_config = false ; // true or false
        #       ---------------
        #       NO MODIFICATIONS REQUIRED BELOW THIS LINE
        #       ---------------
        #       CREATE DEFAULT UPLOAD DIRECTY LOCATION
        #       --------------- 
                If ( !$upload_directory ) {
                        $upload_directory = 'uploads' ; 
                        $parent_dir = array_pop(explode(DIRECTORY_SEPARATOR, dirname(__FILE__)));
                        $upload_directory = substr(dirname(__FILE__), 0, strlen(dirname(__FILE__)) - strlen($parent_dir) ) . $upload_directory ; 
                }
        #       --------------- 
        #       EMAIL TESTS
                If ( !$upload_notify_email ) {
                        $upload_email_reporting = false ;
                }
                # Sends one email per SWFUpload attempt. 
                if ( $test_php_mail_config == true ) {
                        send_mail("SWFUpload Email Test: SUCCESS!",'Be sure to set $test_php_mail_config back to false so that SWFUpload Email Notify reporting is turned on.'); 
                        $upload_email_reporting = false ;
                }
        #       --------------- 
        #       TEST UPLOAD DIRECTORY
                If ( !file_exists($upload_directory) ) {        
                        $msg = "The assigned SWFUpload directory, \"$upload_directory\" does not exist."; 
                        send_mail("SWFUpload Directory Not Found: $upload_directory",$msg);
                        $upload_email_reporting = false ;
                }
                if ( $upload_email_reporting == true ) {
                        $uploadfile = $upload_directory. DIRECTORY_SEPARATOR . basename($_FILES['Filedata']['name']);   
                        if ( !is_writable($upload_directory) ) {
                                $msg = "The directory, \"$upload_directory\" is not writable by PHP. Permissions must be changed to upload files."; 
                                send_mail("SWFUpload Directory Unwritable: $upload_directory",$msg);
                                $upload_directory_writable = false ;
                        } else {
                                $upload_directory_writable = true ;
                        }
                }
        // Work-around for setting up a session because Flash Player doesn't send the cookies
        if (isset($_POST["PHPSESSID"])) {
                session_id($_POST["PHPSESSID"]);
        }
        session_start();
        if ( !isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
                #       --------------- 
                #       UPLOAD FAILURE REPORT
                        if ( $upload_email_reporting == true ) {
                                switch ($_FILES['Filedata']["error"]) { 
                                        case 1: $error_msg = 'File exceeded maximum server upload size of '.ini_get('upload_max_filesize').'.'; break;
                                        case 2: $error_msg = 'File exceeded maximum file size.'; break;
                                        case 3: $error_msg = 'File only partially uploaded.'; break;
                                        case 4: $error_msg = 'No file uploaded.'; break; 
                                }
                                send_mail("SWFUpload Failure: ".$_FILES["Filedata"]["name"],'PHP Error: '.$error_msg."\n\n".'Save Path: '.$uploadfile."\n\n".'$_FILES data: '."\n".print_r($_FILES,true)); 
                        }
                echo "There was a problem with the upload";
                exit(0);
        } else {
                #       --------------- 
                #       COPY UPLOAD SUCCESS/FAILURE REPORT
                        if ( $upload_email_reporting == true AND $upload_directory_writable == true ) {
                                if ( move_uploaded_file( $_FILES['Filedata']['tmp_name'] , $uploadfile ) ) {

				//HERE IS THE CALL
				$newHeight = 100;
				$$newWidth = 100;
				resizeImage ($uploadfile, $uploadfile, $newHeight, $newWidth);

					
                                 send_mail("SWFUpload File Saved: ".$_FILES["Filedata"]["name"],'Save Path: '.$uploadfile."\n\n".'$_FILES data: '."\n".print_r($_FILES,true)); 
                                }else{
                                 send_mail("SWFUpload File Not Saved: ".$_FILES["Filedata"]["name"],'Save Path: '.$uploadfile."\n\n".'$_FILES data: '."\n".print_r($_FILES,true)); 
                                }
                        }
                echo "Flash requires that we output something or it won't fire the uploadSuccess event";
        }
        #       --------------- 
        #       MAIL FUNCTION
                function send_mail($subject="Email Notify",$message="") { 
                        global $upload_notify_email ; 
                        $from = 'SWFUpload@mailinator.com' ; 
                        $return_path = '-f '.$from ;
                        mail($upload_notify_email,$subject,$message,"From: $from\nX-Mailer: PHP/ . $phpversion()");
                }


	function resizeImage ($src, $dest, $newHeight, $newWidth) 
	{ 
		if ( $dest ) 
			fopen($dest, "w") || die("Imposible crear Previa $dest. Chequear permisos del directorio!"); 
		$imgInfo = getimagesize($src); $width = $imgInfo[0]; $height = $imgInfo[1]; 
	    $file_type = $imgInfo[2]; 
    	if ( $newHeight || $newWidth ) 
			if ( $newHeight && $newWidth ) 
			{ 
				$width = $newWidth; 
				$height = $newHeight; 
			}
			else 
				if ( $newWidth == "0" ) 
				{ 
					$ratio = (intval(($width / $newHeight) * 100)) / 100;  
					$width = (intval(($width / $ratio) * 100)) / 100; 
					$height = (intval(($height / $ratio) * 100)) / 100; 
				} 
				else
				{ 
					$ratio = (intval(($width / $newWidth) * 100)) / 100; 
					$width = (intval(($width / $ratio) * 100)) / 100; 
					$height = (intval(($height / $ratio) * 100)) / 100; 
				} 
		$destimg=ImageCreateTrueColor($width,$height); 
		switch ($file_type) 
		{ 
			case 1: 
				$srcimg = imagecreatefromgif($src); 
				if (function_exists(ImageGIF)) 
					$imgType = "gif"; 
				else
					$imgType = "jpeg"; 
			break; 
			case 2: 
				$srcimg = imagecreatefromjpeg($src); 
				$imgType = "jpeg";   
			break; 
			case 3: 
				$srcimg = imagecreatefrompng($src); 
				$imgType = "png"; 
			break; 
			default: 
			break; 
		} 
		ImageCopyResized($destimg,$srcimg,0,0,0,0,$width,$height,ImageSX($srcimg),ImageSY($srcimg)); 
		if ( !$dest ) { header ("Content-type: image/$imgType"); } 
		switch ($file_type) 
		{ 
			case 1: 
				if (function_exists(ImageGIF)) 
					if ( $dest) { imagegif ($destimg, $dest); } else { imagegif($destimg); } 
				else 
					if ( $dest) { imagejpeg ($destimg, $dest); } else { imagejpeg($destimg); } 
			break; 
			case 2: 
				if ( $dest) { imagejpeg ($destimg, $dest); } else { imagejpeg($destimg); } 
			break; 
			case 3: 
				if ( $dest) { imagepng ($destimg, $dest); } else { imagepng($destimg); } 
			break; 
			default: 
			break; 
		} 
		imagedestroy ($srcimg); 
		imagedestroy ($destimg); 
	} 

?>

Open in new window

0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now