Image Upload with auto folder creation

This script will upload photos to a folder and then create a new folder when there are 100 (unless otherwise specified) images in that folder.

[php]<?php

/*
** Created by Michael Dahlke **
** [email protected] **

* This may be used for any purpose you need it for 
	-- no permission is required nor wanted
	-- this message must remain intact
*

*/

//------------------------ Begin the image upload process ------------------------\
if(isset($_POST[‘uploadImage’])){

$directory = "images/uploaded/";			// The path where images are uploaded to
define("MAX_FILES_IN_FOLDER", "100");		// Number of images allowed in a single folder

define ("MAX_SIZE","1000");

// This is not my function I just like it
function getExtension($str) {
	$i = strrpos($str,".");
	
	if (!$i) { 
		return ""; 
	}
	
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	
	return $ext;
}
 
// Make sure file is an image
if (($_FILES["image"]["type"] != NULL)
	&& ($_FILES["image"]["type"] != "image/gif")
 	&& ($_FILES["image"]["type"] != "image/png")
	&& ($_FILES["image"]["type"] != "image/jpeg")
	&& ($_FILES["image"]["type"] != "image/jpg")
	&& ($_FILES["image"]["type"] != "image/pjpeg")){
	 
	 echo "<script type='text/javascript'>";
			echo "var ok = confirm('The image is not the correct format. Image must be jpg, png, or gif.');";
			echo "if(ok){history.go(-1);}";
			echo "</script>";
			echo "
				<noscript>
					<div style='margin-top:100px; text-align:center;'>
						Image is not the correct format!<br />
						<a href='select_state.php'>Try Again?</a>
						<br />
						<a href='index.php'>Go Home</a>
					</div>
				</noscript>
			";
	 exit();
 }
 
// If it is continue
$image = $_FILES['image']['name'];
$uploadedfile = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];

// Change the extension to lower case 
if($image) {
	$filename = stripslashes($_FILES['image']['name']);
	
	$extension = getExtension($filename);
	$extension = strtolower($extension);
		
	// Get image size
	$size = filesize($_FILES['image']['tmp_name']);
	
	// Check to see if it's too big
	if ($size > MAX_SIZE*2048) {
		echo "<script type='text/javascript'>";
		echo "var ok = confirm('Image is too large! Please shrink it and try again.');";
		echo "if(ok){history.go(-1);}";
		echo "</script>";
		echo "
			<noscript>
				<div style='margin-top:100px; text-align:center;'>
					Your image is too large!<br />
					<a href='select_state.php'>Try Again?</a>
					<br />
					<a href='index.php'>Go Home</a>
				</div>
			</noscript>
		";
		exit();
	}
	
	// Check image type and then create jpeg of it
	if($extension == "jpg" || $extension == "jpeg" || $extension == "pjpeg") {
		$uploadedfile = $_FILES['image']['tmp_name'];
			$src = imagecreatefromjpeg($uploadedfile);
	}
	else if($extension == "png") {
		$uploadedfile = $_FILES['image']['tmp_name'];
		$src = imagecreatefrompng($uploadedfile);
	}
	else {
		$src = imagecreatefromgif($uploadedfile);
	}
	
	// Percentages used to change image size	
	$percentHalf = 0.5;
	$percentQuarter = 0.25;
	
	list($width,$height) = getimagesize($uploadedfile);
	
	// Original
	$newWidth = $width;
	$newHeight = ($height / $width) * $newWidth;
	$tmp = imagecreatetruecolor($newWidth,$newHeight);
		
	// 1/2 the size
	$halfWidth = $width * $percentHalf;
	$halfHeight = ($height / $width) * $halfWidth;
	$tmp1 = imagecreatetruecolor($halfWidth,$halfHeight);
	
	// 1/4 of the size
	$quarterWidth = $width * $percentQuarter;
	$quarterHeight = ($height / $width) * $quarterWidth;
	$tmp2 = imagecreatetruecolor($quarterHeight,$quarterHeight);
	
	// Copy the images with the new $width & $height
	imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$width,$height);
				
	/*
		**	  Creating the file path to the images	  **
		
		This will count the number of folder in the directory,
		to get the correct folder to enter,
		then count the number of images in that folder
		and when there are 100 images inside that folder
		a new folder is created with the next number in line
	*/
	$glob  = glob( realpath( $directory ) . '/*' );					
	
	$sub_directories = array_filter( $glob, 'is_dir' );				
	$sub_directories_count = count($sub_directories);				// Counts the directories in the file path
	
	$sub_directory = $sub_directories_count;						// The count of the directories is going to be the name
																	// of our sub folder
	$fileCount = count(glob($directory.$sub_directory."*/*"));		// Count the number of files in the sub directory
	
	if($fileCount == 0){											// If there are no sub directories one will be created
		$directory .= "1/";
		
		mkdir($directory, 0777);
	}
	elseif($fileCount >= MAX_FILES_IN_FOLDER){						// When there are 100 files in that sub directory we create a new on
		$sub_directories_count++;									// We then add 1 to the old sub directory (it is a number)
		$newSubDirectory = $directory.$sub_directories_count;		// The new sub directory will be the old directory + 1
			
		mkdir($newSubDirectory."/", 0777);							// We then create the a new sub directory
		
		$directory = $newSubDirectory."/";
	}
	else {															// If there are not 100 files in that folder yet we continue
		$directory .= $sub_directories_count."/";
	}
	
	// Here is the new directory!
	$filePath = $directory;
	
	//Replace spaces in the title name and give it a different name
	$file_title = str_replace(" ", "_", $filename);
	// Remove the exension in the title
	$file_title = str_replace(".".$extension, "", $file_title);
	
	// Create a filename that won't be repeated
	$fileName = rand()."_".$file_title.".jpg";
	
	// Send the Images to the correct place
	imagejpeg($tmp,$filePath.$fileName,20);
	
	// Destroy temporary images
	imagedestroy($src);
	imagedestroy($tmp);
}

//------------------------ End the image upload process ------------------------\

/*
If you are going to insert the information
into a MySQL database just un-comment the
query below ( you may have to change some
of the values to adapt it to your table )
*/

/*
// Insert values into database
if(isset($_POST[‘uploadImage’]));{
$sql = “INSERT INTO posting (fileName, filePath,type, size) VALUES (’$fileName’, ‘$filePath’,’$fileType’, ‘$fileSize’, )”;

	// Execute the query
	$result = mysql_query($sql);
	
	// If successful
	if($result){ 
		echo 'Upload Successfull!';
	}
	else {
		echo die('ERROR: '. mysql_error());
	}
}

*/
}
?>

Image Upload
<form action="" method="post" enctype="multipart/form-data">
    <fieldset style="width:350px;">
        <input type="file" name="image"/>
        <input type="submit" name="uploadImage"/>
    </fieldset>
</form>

<br />
<br />

<?php
	error_reporting(0); // Remove this during testing so you can see any errors there might be
	
    $height = $height * 0.5;
    $width = $width * 0.5;
    
	echo "<img src='$filePath$fileName' height='$height' width='$width'/><br />";
    
	if($filePath != ""){
        echo "<br />Path to image: " .$filePath.$fileName;
    }
?>
[/php]

You may also find the zipped file here…

http://www.dahlkecomputers.com/wallpapers.php

Sponsor our Newsletter | Privacy Policy | Terms of Service