...

View Full Version : Image upload, change directory path



myfayt
09-13-2011, 11:01 PM
So this image uploader successfully uploads images to my website, but it's putting them in the same directory as the script is running from. I want it in the next folder named "pimages" which stands for Profile Images.

maindirectory/pimages/file.jpg

Also is there any way of changing the file name to a unique name? right now it keeps the same exact file name, and that is going to cause problems, I need a random but unique salt name.

Thanks


$upload_image_limit = 1; // How many images you want to upload at once?
$upload_dir = ""; // default script location, use relative or absolute path
$enable_thumbnails = 1 ; // set 0 to disable thumbnail creation

##################### THUMBNAIL CREATER FROM GIF / JPG / PNG

function make_thumbnails($updir, $img){

$thumbnail_width = 150;
$thumbnail_height = 150;
$thumb_preword = "thumb_";

$arr_image_details = GetImageSize("$updir"."$img");
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];

if( $original_width > $original_height ){
$new_width = $thumbnail_width;
$new_height = intval($original_height*$new_width/$original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width*$new_height/$original_height);
}

$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);



if($arr_image_details[2]==1) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; }
if($arr_image_details[2]==2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; }
if($arr_image_details[2]==3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; }


if( $imgt ) {
$old_image = $imgcreatefrom("$updir"."$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imageCopyResized($new_image,$old_image,$dest_x,
$dest_y,0,0,$new_width,$new_height,$original_width,$original_height);
$imgt($new_image,"$updir"."$thumb_preword"."$img");
}

}









################################# UPLOAD IMAGES

foreach($_FILES as $k => $v){

$img_type = "";

### $htmo .= "$k => $v<hr />"; ### print_r($_FILES);

if( !$_FILES[$k]['error'] && preg_match("#^image/#i", $_FILES[$k]['type']) && $_FILES[$k]['size'] < 500000){

$img_type = ($_FILES[$k]['type'] == "image/jpeg") ? ".jpg" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/gif") ? ".gif" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/png") ? ".png" : $img_type ;

$img_rname = $_FILES[$k]['name'];
$img_path = $upload_dir.$img_rname;

copy( $_FILES[$k]['tmp_name'], $img_path );
if($enable_thumbnails) make_thumbnails($upload_dir, $img_rname);
$feedback .= "Image and thumbnail created $img_rname<br />";

}
}


$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />

</form>
';
$page .= "$htmo";

BluePanther
09-13-2011, 11:11 PM
So this image uploader successfully uploads images to my website, but it's putting them in the same directory as the script is running from. I want it in the next folder named "pimages" which stands for Profile Images.

maindirectory/pimages/file.jpg

The part you're looking for is:


$upload_dir = $_SERVER['DOCUMENT_ROOT']."/pimages/"; // default script location, use relative or absolute path

That should change your upload directory to something like /var/www/pimages/ or where ever this script is executing.



Also is there any way of changing the file name to a unique name? right now it keeps the same exact file name, and that is going to cause problems, I need a random but unique salt name.

Thanks

Yes, but be mindful of the implications. If you start assigning random names, you'll have to keep track of the filenames some way, whether by SQL or using scandir() to output a full folder. Whatever you do, you'll have to make a change to the $img_rname variable before the copy() statement. Be mindful about file extensions when editing, refer to this post: http://www.codingforums.com/showthread.php?t=237619

myfayt
09-13-2011, 11:19 PM
I tried doing this


$upload_dir = "/pimages"; // default script location, use relative or absolute path

and it didn't change the path.

As for the unique name, it would be stored in the database, and extracted to show in profiles. Meaning like h98hr3gf74gt7.jpg would be in a field name of something like "image1" in the database, and on the users profile, it'd extract their image 1 to display.

BluePanther
09-14-2011, 12:47 AM
Storing them in the mysql is acceptable. So, all you need to do is generate a random name (could just be filename.rand().extension?) and then assign it to the database on copy success (after the copy function).

As for your upload dir, changing $upload_dir to /pimages will mean your uploades files will stay in the same directory, but be called pimagesfilename.jpg. You need to add a / at the end of it (notice my example has it). It's because you're concatenating the image name right onto the upload_dir variable.

myfayt
09-14-2011, 01:15 AM
Ok so this should work?


$upload_dir = "/pimages/"; // default script location, use relative or absolute path

Also I can't figure out which variable is the file name, I am assuming it's $img?
I've only used RAND for numbers, and I hear MT_RAND is better. But how would letters be added? Or do I do a strlen of 7 numbers?

BluePanther
09-14-2011, 01:22 AM
Random letters can be done in a few ways.


$alphabet = array( 'a','b',...,'z' );
$letter = $alphabet[rand(0,25)];

// or
$alphabet = 'abcdefghijklmnopqrstuvwxyz';
$letter = substr($alphabet, rand(0,25), 1);

You could just put one of those in a for loop appending a string with the random letters, then add that string to the filename (which is down by copy() btw - $img_rname). Using mt_rand() is SUPPOSED to give a better random number, but I don't really think there's a noticable difference. rand() does fine, and is faster.

And yes, that path should work.

myfayt
09-14-2011, 03:39 AM
Makes sense, would something like this work?



$alphabet = 'abcdefghijklmnopqrstuvwxyz';
$letter = substr($alphabet, rand(0,25), 1);
copy( $_FILES[$k]['tmp_name']$letter, $img_path );

BluePanther
09-14-2011, 04:19 AM
Makes sense, would something like this work?



$alphabet = 'abcdefghijklmnopqrstuvwxyz';
$letter = substr($alphabet, rand(0,25), 1);
copy( $_FILES[$k]['tmp_name']$letter, $img_path );

No. It's copy(source, destination). So, changing the source will mean your code will not find the image. On top of that, to concatenate strings (append one string onto another) you need to use the . operator. Proper use would be $var.$letter

But, remember what I said in a previous reply - you'll need to account for file extension when renaming your file. You can choose your prefered method in the thread I linked you to in post #4.

myfayt
09-14-2011, 04:36 PM
I gotcha, so basically like this?


copy( $_FILES[$k]['tmp_name'], $img_path );
$alphabet = 'abcdefghijklmnopqrstuvwxyz';
$letter = substr($alphabet, rand(0,25), 1);
$newname = $_FILES[$k][$letter][$img_type];
//Store $newname into database

BluePanther
09-14-2011, 08:45 PM
I gotcha, so basically like this?


copy( $_FILES[$k]['tmp_name'], $img_path );
$alphabet = 'abcdefghijklmnopqrstuvwxyz';
$letter = substr($alphabet, rand(0,25), 1);
$newname = $_FILES[$k][$letter][$img_type];
//Store $newname into database


No. Did you even look at the post I referred you to? :P

$_FILES[$k]['name'] is the filename.extension (imagename.jpg). So, you need to decide what you want to do to the filename to randomise it, and then create it following the post I linked you to before.

myfayt
09-14-2011, 11:19 PM
I am trying my best, I am brand new to dealing with files. So bare with me.


$img_rname = $_FILES[$k]['name'];
$img_path = $upload_dir.$img_rname;

That is what I need to change, right?

myfayt
09-15-2011, 06:59 PM
I need to bump this because I still haven't gotten a fix yet.

BluePanther
09-15-2011, 07:39 PM
I keep telling you to check out the post I've linked you to, so I'll just post it in here.


// Get the name of the file (including file extension).
$file12 = $_FILES['site_url']['name'];

$file12 = preg_replace('/\s/', '_', $file12);

// Find extension position
$position = strrpos($file12, '.');
$filename = substr($file12,0,$position).$rand.substr($file12,$position);

So, change your code to this:


$rand = rand(conditions);
$img_rname = $_FILES[$k]['name'];
$position = strrpos($img_rname, '.');
$img_rname = substr($img_rname,0,$position).$rand.substr($img_rname,$position);
$img_path = $upload_dir.$img_rname;

myfayt
09-15-2011, 07:45 PM
There was no link to anything in post #4

BluePanther
09-15-2011, 07:47 PM
It was actually post #2 I linked it to you in, so apologies for not telling you the right one. Regardless, you should have read it in post 2 anyway.

myfayt
09-15-2011, 09:57 PM
Warning: copy(/pimages/businessray261370.jpg) [function.copy]: failed to open stream: No such file or directory in /home2/rodgameo/public_html/profiles.php on line 193

Warning: getimagesize(/pimages/businessray261370.jpg) [function.getimagesize]: failed to open stream: No such file or directory in /home2/rodgameo/public_html/profiles.php on line 132

Warning: Division by zero in /home2/rodgameo/public_html/profiles.php on line 141



$upload_image_limit = 1; // How many images you want to upload at once?
$upload_dir = "/pimages/"; // default script location, use relative or absolute path
$enable_thumbnails = 1 ; // set 0 to disable thumbnail creation

##################### THUMBNAIL CREATER FROM GIF / JPG / PNG

function make_thumbnails($updir, $img){

$thumbnail_width = 150;
$thumbnail_height = 150;
$thumb_preword = "thumb_";

$arr_image_details = GetImageSize("$updir"."$img");
$original_width = $arr_image_details[0];
$original_height = $arr_image_details[1];

if( $original_width > $original_height ){
$new_width = $thumbnail_width;
$new_height = intval($original_height*$new_width/$original_width);
} else {
$new_height = $thumbnail_height;
$new_width = intval($original_width*$new_height/$original_height);
}

$dest_x = intval(($thumbnail_width - $new_width) / 2);
$dest_y = intval(($thumbnail_height - $new_height) / 2);



if($arr_image_details[2]==1) { $imgt = "ImageGIF"; $imgcreatefrom = "ImageCreateFromGIF"; }
if($arr_image_details[2]==2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; }
if($arr_image_details[2]==3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; }


if( $imgt ) {
$old_image = $imgcreatefrom("$updir"."$img");
$new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
imageCopyResized($new_image,$old_image,$dest_x,
$dest_y,0,0,$new_width,$new_height,$original_width,$original_height);
$imgt($new_image,"$updir"."$thumb_preword"."$img");
}

}









################################# UPLOAD IMAGES

foreach($_FILES as $k => $v){

$img_type = "";

### $htmo .= "$k => $v<hr />"; ### print_r($_FILES);

if( !$_FILES[$k]['error'] && preg_match("#^image/#i", $_FILES[$k]['type']) && $_FILES[$k]['size'] < 500000){

$img_type = ($_FILES[$k]['type'] == "image/jpeg") ? ".jpg" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/gif") ? ".gif" : $img_type ;
$img_type = ($_FILES[$k]['type'] == "image/png") ? ".png" : $img_type ;


$rand = rand(1,1000000);
$img_rname = $_FILES[$k]['name'];
$position = strrpos($img_rname, '.');
$img_rname = substr($img_rname,0,$position).$rand.substr($img_rname,$position);
$img_path = $upload_dir.$img_rname;

copy( $_FILES[$k]['tmp_name'], $img_path );
if($enable_thumbnails) make_thumbnails($upload_dir, $img_rname);
$feedback .= "Image and thumbnail created $img_rname<br />";

}
}


$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />

</form>
';
$page .= "$htmo";

Chris Hick
09-15-2011, 11:26 PM
Let me know if this works. ^_^


<?php
if (isset($_POST['submit'])) {
// Define application constants
define('MM_UPLOADPATH', 'pimages/');
define('MM_MAXFILESIZE', 32768); // 32 KB
define('MM_MAXIMGWIDTH', 120); // 120 pixels
define('MM_MAXIMGHEIGHT', 120); // 120 pixels
$new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name']));
$new_picture_type = $_FILES['new_picture']['type'];
$new_picture_size = $_FILES['new_picture']['size'];
list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']);
$error = false;
// Validate and move the uploaded picture file, if necessary
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {

}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
@unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
@unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
if (!$error) {
if (!empty($new_picture)) {
// Set up query here to update database.
}
// Perform the query now and confirm it to the user.
// Confirm success with the user
echo '<p>Your picture has been successfully uploaded.</p>';
}
else {
echo '<p class="error">You must have something to upload.</p>';
}
}
}
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" />
<fieldset>
<label for="new_picture">Picture:</label>
<input type="file" id="new_picture" name="new_picture" />
</fieldset>
<input type="submit" value="Save Profile" name="submit" />
</form>

myfayt
09-16-2011, 01:29 AM
Chris, it didn't work, it says successful but has an error too.


Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /home2/rodgameo/public_html/profiles.php on line 126

Your picture has been successfully uploaded.


if (isset($_POST['submit'])) {
// Define application constants
define('MM_UPLOADPATH', 'pimages/');
define('MM_MAXFILESIZE', 500000); // 500 KB
define('MM_MAXIMGWIDTH', 400); // 400 pixels
define('MM_MAXIMGHEIGHT', 400); // 400 pixels
$new_picture = mysqli_real_escape_string($dbc, trim($_FILES['new_picture']['name']));
$new_picture_type = $_FILES['new_picture']['type'];
$new_picture_size = $_FILES['new_picture']['size'];
list($new_picture_width, $new_picture_height) = getimagesize($_FILES['new_picture']['tmp_name']);
$error = false;
// Validate and move the uploaded picture file, if necessary
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {

}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
@unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
@unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
if (!$error) {
if (!empty($new_picture)) {
// Set up query here to update database.
}
// Perform the query now and confirm it to the user.
// Confirm success with the user
echo '<p>Your picture has been successfully uploaded.</p>';
}
else {
echo '<p class="error">You must have something to upload.</p>';
}
}

$page .= "
<form enctype='multipart/form-data' method='post' action=\"profiles.php?x=profile:$id\">
<input type='hidden' name=\"MAX_FILE_SIZE\" value=\"{MM_MAXFILESIZE}\" />
<fieldset>
<label for='new_picture'>Picture:</label>
<input type='file' id='new_picture' name='new_picture' />
</fieldset>
<input type='submit' value='Save Profile' name='submit' />
</form>";

Chris Hick
09-16-2011, 07:54 AM
Ah, that's because you need to establish the database connection with the variable $dbc. You can change it to mysql instead of mysqli.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum