...

View Full Version : Alteration of existing image upload code...



greens85
03-01-2010, 03:34 PM
Hi All,

I have some code that currently allows me to upload an image it will store the original and resize it and dump the thumb in a different directory. What I'm trying to do is alter this slightly so that each image uploaded can be associated with a certain user account, and also to give the image a random file name...

My existing code is:


<?php

if (isset($_FILES["newPicture"])){

$newPicture = $_FILES['newPicture']['name'];

$neworiginalfilename = 'img.jpg';
$newdynamicfilename = 'img.jpg';

if (!preg_match('/jpg|jpeg/',$newPicture)){
die ("Error: Your uploaded file must in JPG format. Other file types are not allowed<br /> Your file must not exceed 2mb in size.");
}

$path = $_SERVER['DOCUMENT_ROOT'];
$target_folder = "/images/dynamicimages/originalimages/"; // Picture Folder
$dir = $path . $target_folder;
if (!is_dir($dir)){ //check to see if directory exists. If not, create it.
$dir = explode('/', $target_folder);
foreach ($dir as $sub_dir){
$path .= '/' . $sub_dir;
if (!is_dir($path)){
if (!mkdir($path, 0777)){
die('<strong>Error:</strong> Directory does not exist and was unable to be created.');
}
}
}
}
$path = $_SERVER['DOCUMENT_ROOT'];
$target_folder = "/images/dynamicimages/originalimages/$neworiginalfilename"; //Re-define Pic Folder after creation
$target_path = $path.$target_folder.basename($_FILES['newPicture']['']);

if(move_uploaded_file($_FILES['newPicture']['tmp_name'], $target_path)) {

$im=ImageCreateFromJPEG($target_path);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$n_width= 251; // Fix the width of the thumb nail images
$n_height = 188; // Fix the height of the thumbnail images
//$n_height= $height * ($n_width/$width);
$newimage=imagecreatetruecolor($n_width,$n_height);
imagecopyresampled($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);


$thumb_target_folder = "/images/dynamicimages/"; //Set Thumbnail Folder
$path = $_SERVER['DOCUMENT_ROOT'];
$dir = $path . $thumb_target_folder;
if (!is_dir($dir)){
$dir = explode('/', $thumb_target_folder);
foreach ($dir as $sub_dir){
$path .= '/' . $sub_dir;
if (!is_dir($path)){ //check to see if directory exists. If not, create it.
if (!mkdir($path, 0777)){
die('<strong>Error:</strong> Directory does not exist and was unable to be created.');
}
}
}
}
$path = $_SERVER['DOCUMENT_ROOT'];
$thumb_target_folder = "/images/dynamicimages/$newdynamicfilename"; //Re-define Thumbnail folder after creation
$tsrc= $path.$thumb_target_folder.basename($_FILES['newPicture']['']); // Path where thumbnail image will be stored
ImageJpeg($newimage,$tsrc);
chmod("$tsrc",0777);
chmod("$target_path",0777);
$message = "The file ".basename($_FILES['newPicture']['name'])." has been uploaded!<br><br>";
}

else{
die("There was an error uploading the file, please try again!");
}

}
?>
<br/>
<br/>
<?php echo ('Your image has been uploaded to our server, you will be redirected to the administrative front in 5 seconds'); ?>

Will this be easy to adapt? and if not does anyone know of any good tutorials that will allow me to upload, resize and store an image with a random file name and associate it with a user account?

many thanks,

greens85

MattF
03-01-2010, 04:48 PM
Add a directory in the parent image dir for each user id and add the user id to the path. i.e:



$basedir = '/images/dynamicimages/'.$userid.'/';
$thumbs = $basedir.'thumbs/';



p.s: That is just an example and you will have to adapt it to your code, (or better yet, adapt your code to it).

greens85
03-01-2010, 05:14 PM
Add a directory in the parent image dir for each user id and add the user id to the path. i.e:



$basedir = '/images/dynamicimages/'.$userid.'/';
$thumbs = $basedir.'thumbs/';



p.s: That is just an example and you will have to adapt it to your code, (or better yet, adapt your code to it).

So is the use of a field in a database not needed?

Such as adding a field to the user records lets say called... image.

Then once they upload the image, it is given a random file name which is added to that users record and also added into the image directory... then can be called out through the path from the database?

Hopefully that makes even a little bit of sense!

thanks

MattF
03-01-2010, 05:36 PM
So is the use of a field in a database not needed?

Such as adding a field to the user records lets say called... image.

If it was necessary, I would have mentioned so. You have all images in specific directories. Each directory can only belong to one user. You don't need a DB to tell you what matches whom.




Then once they upload the image, it is given a random file name which is added to that users record and also added into the image directory... then can be called out through the path from the database?

Hopefully that makes even a little bit of sense!

It made perfect sense first time around. Take the time to actually inspect your code, and then inspect the code I posted, and from there it's merely a minor leap to see where the alterations need making.

greens85
03-02-2010, 11:22 AM
Add a directory in the parent image dir for each user id and add the user id to the path. i.e:



$basedir = '/images/dynamicimages/'.$userid.'/';
$thumbs = $basedir.'thumbs/';


p.s: That is just an example and you will have to adapt it to your code, (or better yet, adapt your code to it).

Sorry Matt, not quite getting this so apologies...

Are you saying to create a directory for each user I will have

e.g.

images/dynamicimages/user1/
images/dynamicimages/user2/
images/dynamicimages/user3/

etc?

or are you saying that I can store each users image in the same directory under a unique identifier...

e.g.

images/dynamicimages/1738573.jpg (user 1's image)
images/dynamicimages/5975745.gif (user 2's image)
images/dynamicimages/0293473.png (user 3's image)

Sorry for the lack of understanding...

MattF
03-02-2010, 02:20 PM
Sorry Matt, not quite getting this so apologies...

Are you saying to create a directory for each user I will have

e.g.

images/dynamicimages/user1/
images/dynamicimages/user2/
images/dynamicimages/user3/

etc?

Yes.



or are you saying that I can store each users image in the same directory under a unique identifier...

e.g.

images/dynamicimages/1738573.jpg (user 1's image)
images/dynamicimages/5975745.gif (user 2's image)
images/dynamicimages/0293473.png (user 3's image)


You could do it this way, (by prepending the userid, for example), but I've personally never likes the idea. I like to keep info separated, hence the directory per user method. The former is a cleaner approach, in my opinion.

greens85
03-02-2010, 04:03 PM
Yes.
You could do it this way, (by prepending the userid, for example), but I've personally never likes the idea. I like to keep info separated, hence the directory per user method. The former is a cleaner approach, in my opinion.

Hi Matt,

While waiting for your advice I kept trying different methods and managed to get it working this way (with a tutorial from a site I might add)...


<?php
session_start();
//Check if the session is valid, if not return them to the login page
if(!session_is_registered("candidate_username")){
header("location:../processcandidatelogin.php");
}
//Include the connection to the database
include ("dbconnection.php");

//Query the database for all details of the candidate
$query = "SELECT * FROM edworld_candidates WHERE uname='$_SESSION[candidate_username]'";
$result = mysql_query($query) or die (mysql_error());
$row = mysql_fetch_array($result);

$id = $row['id'];

//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","2048");

//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}

//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file,
//otherwise we will do more tests
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
$query = "UPDATE edworld_candidates SET image = '$image_name' WHERE id = '$id'";
$result = mysql_query($query) or die (mysql_error());

if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}

//If no errors registred, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>

While i fully appreciate this may not be the best way of doing things, it does work! I just need a tiny bit of customization to get it to do exactly what I want for now... then I can address this again later.

How possible is it for me to resize the original image and keep the image in proportion then save it in a different directory called thumbs?

Also how will this affect images that are sent either portrait or landscape?

many thanks,

greens85



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum