I am writing an image management script in php. All of the php code regarding the image management works just fine. The problem is the script fails to render the small amount of html at the top which includes an animated loading gif.
Depending on the number of images being managed, it can take some time so I would like the html at the top to render. I have tried to place it in a function and call the function after the html but the script goes right to the image processing.
This page is being called into an Iframe from another page in the Iframe.
<?php
$level = '../../';
include('class.upload.php');
$folder = $_REQUEST['folder'];
# render success page
echo '<html><body>';
echo '<h3 style="color: red">Processing...</h3>';
echo 'This might take awhile... Your patience is much appreciated.';
echo '<br><br><br><div style="text-align: center"><img src="ajaxloader.gif"></div>';
echo '</body></html>';
$icon = $_REQUEST['icon'];
$thumb = $_REQUEST['thumb'];
$small = $_REQUEST['small'];
$medium = $_REQUEST['medium'];
$large = $_REQUEST['large'];
$xlarge = $_REQUEST['xlarge'];
foreach(glob('images/temp/*') as $image) {
if($icon >= 1){copy($image, 'images/100/' . basename($image));}
if($thumb >= 1){copy($image, 'images/150/' . basename($image));}
if($small >= 1){copy($image, 'images/320/' . basename($image));}
if($medium >= 1){copy($image, 'images/640/' . basename($image));}
if($large >= 1){copy($image, 'images/960/' . basename($image));}
if($xlarge >= 1){copy($image, 'images/1280/' . basename($image));}
}
# xlarge folder
$startdir= 'images/1280/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){
list($width, $height) = getimagesize($startdir.$image_file);
if($width >= 1280){
$handle = new upload($startdir.$image_file);
if ($handle->uploaded) {
$handle->file_name_body_add = '_large';
$handle->image_resize = true;
$handle->image_x = 1280;
$handle->image_ratio_y = true;
$handle->process($folder.'/1280/');
if ($handle->processed) {$handle->clean();}
else {echo 'error : ' . $handle->error;}
}
}
}
# large folder
$startdir= 'images/960/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){
list($width, $height) = getimagesize($startdir.$image_file);
if($width >= 960){
$handle = new upload($startdir.$image_file);
if ($handle->uploaded) {
$handle->file_name_body_add = '_large';
$handle->image_resize = true;
$handle->image_x = 960;
$handle->image_ratio_y = true;
$handle->process($folder.'/960/');
if ($handle->processed) {$handle->clean();}
else {echo 'error : ' . $handle->error;}
}
}
}
# medium folder
$startdir= 'images/640/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){
list($width, $height) = getimagesize($startdir.$image_file);
if($width >= 640){
$handle = new upload($startdir.$image_file);
if ($handle->uploaded) {
$handle->file_name_body_add = '_large';
$handle->image_resize = true;
$handle->image_x = 640;
$handle->image_ratio_y = true;
$handle->process($folder.'/640/');
if ($handle->processed) {$handle->clean();}
else {echo 'error : ' . $handle->error;}
}
}
}
# small folder
$startdir= 'images/320/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){
list($width, $height) = getimagesize($startdir.$image_file);
if($width >= 320){
$handle = new upload($startdir.$image_file);
if ($handle->uploaded) {
$handle->file_name_body_add = '_large';
$handle->image_resize = true;
$handle->image_x = 320;
$handle->image_ratio_y = true;
$handle->process($folder.'/320/');
if ($handle->processed) {$handle->clean();}
else {echo 'error : ' . $handle->error;}
}
}
}
# thumb folder
$startdir= 'images/150/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){
list($width, $height) = getimagesize($startdir.$image_file);
if($width >= 150){
$handle = new upload($startdir.$image_file);
if ($handle->uploaded) {
$handle->file_name_body_add = '_large';
$handle->image_resize = true;
$handle->image_x = 150;
$handle->image_ratio_y = true;
$handle->process($folder.'/150/');
if ($handle->processed) {$handle->clean();}
else {echo 'error : ' . $handle->error;}
}
}
}
# icon folder
$startdir= 'images/100/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){
list($width, $height) = getimagesize($startdir.$image_file);
if($width >= 100){
$handle = new upload($startdir.$image_file);
if ($handle->uploaded) {
$handle->file_name_body_add = '_large';
$handle->image_resize = true;
$handle->image_x = 100;
$handle->image_ratio_y = true;
$handle->process($folder.'/100/');
if ($handle->processed) {$handle->clean();}
else {echo 'error : ' . $handle->error;}
}
}
}
# unlink temp folder images
$startdir= 'images/temp/';
$dir="$startdir$subdir";$array_dir=array();$array_file=array();if(is_dir($dir)){if($dh=opendir($dir)){while(($file=readdir($dh))!==false){$filename=$file;$filetype=filetype($dir.$file);if($filename==".."OR$filename=="."){echo"";}else{if($filetype=="file"){$array_file[]=$filename;}elseif($filetype=="dir"){$array_dir[]=$filename;}}}closedir($dh);}}sort($array_dir);
foreach ($array_file as $image_file){unlink($startdir.$image_file);}
echo '<Script language="javascript">window.location="success.php"</script>';
?
>
Any assistance is much appreciated,
Pete
Related
I am trying to upload an image in a folder using the move_uploaded_file() function. The image usually is a JPG.
The problem is that the moving process somehow affects the image quality. To me mor eprecises, the colors are not the same between the file that i want to upload and the uploaded file.
So far i think the problem lies withing the move_uploaded_file() function, as the colors of the temp file are correct.
Here is my code and the images before and after the upload(the top one is before uploading and the bottom one ois after upload).
This kind of behaviour isn't accepted as the results need to be print ready.
if ($this->request->is('post')) {
if (!$this->request->data['TplElement']['file']) {
$tplElementImage['TplElementImage']['original_id'] = 0;
$tplElementImage['TplElementImage']['filepath'] = NULL;
$tplElementImage['TplElementImage']['filepath_hires'] = NULL;
$this->TplElementImage->save($tplElementImage);
}
else {
//create the directory
$path = APP.WEBROOT_DIR.DS.'uploads'.DS.'templates'.DS.$tplElement['TplElement']['tpl_asset_page_id'].DS.$tplElementImage['TplElementImage']['tpl_element_id'].DS.$elementID;
if ($this->make_path($path.DS.'dummy.txt')) {
$tplElementImage['TplElementImage']['original_file_name'] = $this->request->data['TplElement']['file']['name'];
$filename = session_id().'_'.time().'_'.$tplElementImage['TplElementImage']['original_file_name'];
if ($this->request->data['TplElement']['file']['size'] > 0) {
if(move_uploaded_file($this->request->data['TplElement']['file']['tmp_name'], $path.DS.$filename)) {
$tplElementImage['TplElementImage']['filepath'] = '/uploads' . '/' . 'templates' . '/' . $tplElement['TplElement']['tpl_asset_page_id'] . '/' . $tplElementImage['TplElementImage']['tpl_element_id'] . '/' . $elementID . '/' . $filename;
$imageSize = getimagesize($path . DS . $filename);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$zoom = 1;
$imageWidthMm = $imageWidth * 25.4 / 200;
$imageHeightMm = $imageHeight * 25.4 / 200;
$inBlockImageHeight = $imageHeight * $blockWidth / $imageWidth;
$inBlockImageWidth = $imageWidth * $blockHeight / $imageHeight;
if ($inBlockImageHeight < $blockHeight || $inBlockImageWidth < $blockWidth) {
$zoom = max($blockHeight / $imageHeightMm, $blockWidth / $imageWidthMm);
}
if ($zoom > 1) {
$this->Session->setFlash(__('Image too small'));
$this->redirect('/tpl_asset_pages/edit/' . $tplElement['TplElement']['tpl_asset_page_id']);
return;
}
$tplElementImage['TplElementImage']['zoom'] = $zoom;
$tplElementImage['TplElementImage']['original_width'] = $imageWidth;
$tplElementImage['TplElementImage']['original_height'] = $imageHeight;
$tplElementImage['TplElementImage']['top'] = 0;
$tplElementImage['TplElementImage']['left'] = 0;
$tplElementImage['TplElementImage']['original_id'] = 0;
$tplElementImage['TplElementImage']['filepath_hires'] = NULL;
$tplElementImage['TplElementImage']['max_zoom_value'] = $this->ElementImage->GetMaxZoom($imageWidth, $imageHeight, $blockWidth, $blockHeight);
if ($this->TplElementImage->save($tplElementImage)) {
$this->Session->setFlash(__('File successfully saved'));
} else {
$this->Session->setFlash("Unable to save data");
}
}else{
$this->Session->setFlash("Unable to move file");
}
}
else {
if ($this->request->data['TplElement']['file']['size'] > 0) {
$this->Session->setFlash("Unable to save uploaded file");
}
else {
$tplElementImage['TplElementImage']['filepath'] = NULL;
$this->TplElementImage->save($tplElementImage);
$this->Session->setFlash("Unable to save uploaded file");
}
}
}
else {
$this->Session->setFlash('Unable to create folder');
}
}
$this->redirect('/tpl_asset_pages/edit/'.$tplElement['TplElement']['tpl_asset_page_id']);
}
The problem has been fixed using Imagick to write the file.
$img = new Imagick($this->request->data['TplElement']['file']['tmp_name']);
$img->setImageFormat(substr(strrchr($tplElementImage['TplElementImage']['original_file_name'],'.'),1));
//stuff
if($img->writeImage($path.DS.$filename)) {
//stuff
}
//stuff
I'm using class.upload.php for images. Resizing works correctly with name and extension into the folder, but i have a problem storing the name into mysql database. There's no file extension (.jpg, .gif etc)... why? how can i resolve the problem?
Thanks
/* ========== SCRIPT UPLOAD MULTI IMAGES ========== */
include('class.upload.php');
$dir_dest="../../images/gallery/";
$files = array();
foreach ($_FILES['fleImage'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new Upload($file);
if ($handle->uploaded) {
$mainame = $handle->file_dst_name;
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_big = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_big;
$handle->image_resize = true;
$handle->image_x = 460;
$handle->image_ratio_y = true;
// $handle->image_y = 400;
$handle->Process($dir_dest);
//Thumbnail
$db_name = str_replace(" ","_",$mainame);
$image1 = md5(rand() * time()) . ".$db_name";
$parts = explode(".",$image1);
$extension = end($parts);
$result_small = str_replace("." . $extension,"",$image1);
$handle->file_new_name_body = $result_small;
$handle->image_resize = true;
$handle->image_x = 180;
$handle->image_ratio_y = true;
// $handle->image_y = 120;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
header("Location: index.php"); //echo 'image resized';
$handle->clean();
$query_img="INSERT into tbl_images (file_name, pd_image, pd_thumbnail) VALUES('$nome','$result_big', '$result_small')";
$result2 = dbQuery($query_img);
} else {
echo 'error : ' . $handle->error;
}
}
}
// END SCRIPT UPLOAD MULTI IMAGES
header("Location: index.php");
}
You are removing the extension with this code
$result_big = str_replace("." . $extension,"",$image1);
I dont know why you do that. anyway you can add it back by adding following line after the $handle->file_new_name_body = $result_big;
$handle->file_new_name_ext = $extension;
You have replaced the extention with empty string here using str_replace
$result_small = str_replace("." . $extension,"",$image1);
and here
$result_big = str_replace("." . $extension,"",$image1);
update below lines just add .$extension at the end
$handle->file_new_name_body = $result_big.$extension;
and
$handle->file_new_name_body = $result_small.$extension;
just change query like this
$query_img="INSERT into tbl_images (
file_name,
pd_image,
pd_thumbnail
) VALUES (
'$nome',
'{$result_big}.{$extension}',
'{$result_small}.{$extension}')";
I will suggest you to have same filename for pd_image and pd_thumbnail, just prefix thumb with thumb_ that will make your life easier in front end.
this way you can access any image thumbnail just by prefixing it with thumb_ with pd_image and you don't have to store pd_thumbnail in database.
I'm trying to crop an image when it has been uploaded. So far I've only managed to resize it but if an image is a rectangular shape then the image is squashed which doesn't look nice. I'm trying to get coding that I can use with the function that I currently have to resize. The ones that I'm seeing I have to change my function and I'm hoping not to do that.
Here is my function
function createThumbnail($filename) {
global $_SITE_FOLDER;
//require 'config.php';
$final_width_of_image = 82;
$height = 85;
$path_to_image_directory = $_SITE_FOLDER.'portfolio_images/';
$path_to_thumbs_directory = $_SITE_FOLDER.'portfolio_images/thumbs/';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
//$ny = $height;
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
Here is my function.
<?php
function crop($file_input, $file_output, $crop = 'square',$percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
echo 'Unable to get the length and width of the image';
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
echo 'Incorrect file format';
return;
}
if ($crop == 'square') {
$min = $w_i;
if ($w_i > $h_i) $min = $h_i;
$w_o = $h_o = $min;
} else {
list($x_o, $y_o, $w_o, $h_o) = $crop;
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
$x_o *= $w_i / 100;
$y_o *= $h_i / 100;
}
if ($w_o < 0) $w_o += $w_i;
$w_o -= $x_o;
if ($h_o < 0) $h_o += $h_i;
$h_o -= $y_o;
}
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopy($img_o, $img, 0, 0, $x_o, $y_o, $w_o, $h_o);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
And you can call like this
crop($file_input, $file_output, $crop = 'square',$percent = false);
And also resize function if you need.
<?php
function resize($file_input, $file_output, $w_o, $h_o, $percent = false) {
list($w_i, $h_i, $type) = getimagesize($file_input);
if (!$w_i || !$h_i) {
return;
}
$types = array('','gif','jpeg','png');
$ext = $types[$type];
if ($ext) {
$func = 'imagecreatefrom'.$ext;
$img = $func($file_input);
} else {
return;
}
if ($percent) {
$w_o *= $w_i / 100;
$h_o *= $h_i / 100;
}
if (!$h_o) $h_o = $w_o/($w_i/$h_i);
if (!$w_o) $w_o = $h_o/($h_i/$w_i);
$img_o = imagecreatetruecolor($w_o, $h_o);
imagecopyresampled($img_o, $img, 0, 0, 0, 0, $w_o, $h_o, $w_i, $h_i);
if ($type == 2) {
return imagejpeg($img_o,$file_output,100);
} else {
$func = 'image'.$ext;
return $func($img_o,$file_output);
}
}
?>
resize($file_input, $file_output, $w_o, $h_o, $percent = false);
You can use SimpleImage class found here SimpleImage
[edit] Updated version with many more features here SimleImage Updated
I use this when resizing various images to a smaller thumbnail size while maintaining aspect ratio and exact image size output. I fill the blank area with a colour that suits the background for where the image will be placed, this class supports cropping. Explore the methods cutFromCenter and maxareafill.
For example in your code you would not need to imagecreatefromjpeg() you would simply;
Include the class include('SimpleImage.php');
then;
$im = new SimpleImage();
$im->load($path_to_image_directory . $filename);
$im->maxareafill($output_width,$output_height, 0,0,0); // rgb
$im->save($path_to_image_directory . $filename);
I use this class daily and find it very versatile.
<?
$start = $_GET[start] ? $_GET[start] : 0 ;
$sortby = $_COOKIE[sortby] ? $_COOKIE[sortby] : "name" ;
if($_GET[sortby]){
$sortby = $_GET[sortby];
setcookie("sortby", $_GET[sortby], time()+86400 );
header("location: index.php");
}
$od = opendir("./");
while($file = readdir($od)){
if( eregi("\.(gif|jpe?g|png)$", $file) ){
$file2 = rawurlencode($file);
$img_arr[$file2] = $file;
$img_arr_filesize[$file2] = filesize($file);
$img_arr_filemtime[$file2] = filemtime($file);
list($imagex, $imagey, $type, $attr) = getimagesize($file);
$img_arr_sizexy[$file2] = $imagex."x".$imagey;
}
}
asort($img_arr);
asort($img_arr_filesize);
asort($img_arr_filemtime);
switch($sortby){
case "time":
$img_arr_final = $img_arr_filemtime;
break;
case "size":
$img_arr_final = $img_arr_filesize;
break;
case "name":
$img_arr_final = $img_arr;
break;
}
$total_images = count($img_arr_final);
foreach($img_arr_final as $k=>$v){
$i++;
if($i < $start+1) continue;
if($i > $start + $pp) break;
$img_name = strlen($img_arr[$k]) > 18 ? substr($img_arr[$k],0,16)."..." :$img_arr[$k];
$alt = $img_arr[$k] . " -|- Last modified: " . date("Y-m-d H:i:s", $img_arr_filemtime[$k]) . " ";
$imgl .= "<div class=\"img_thumb\"><img src=\"index.php?thumb=$k\" alt=\"$alt\" title=\"$alt\" /><p title=\"".$img_arr[$k]."\"><strong>".$img_name. "</strong><br /><span class=\"mini\">".$img_arr_sizexy[$k].", ".round(($img_arr_filesize[$k]/1024))." KB</span></p></div>";
}
for($p=0; $p*$pp < $total_images ; $p++){
$active = ($p*$pp) == $start ? "active" : "" ;
$page_htmo .= "".($p+1)." ";
}
$arr_sortby = array("name"=>"Name", "size"=>"Size", "time"=>"Time");
foreach($arr_sortby as $k=>$v){
if($sortby == $k){
$sortby_html[] = "<strong>$v</strong>";
} else {
$sortby_html[] = "$v";
}
}
$sortby_htmo = implode(" | ", $sortby_html);
function make_thumbnail($updir, $img){
global $thumb_width, $thumb_height;
$thumbnail_width = $thumb_width ? $thumb_width : 120;
$thumbnail_height = $thumb_height ? $thumb_height : 80;
$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"; $imgx = "gif"; }
if($arr_image_details[2]==2) { $imgt = "ImageJPEG"; $imgcreatefrom = "ImageCreateFromJPEG"; $imgx = "jpeg"; }
if($arr_image_details[2]==3) { $imgt = "ImagePNG"; $imgcreatefrom = "ImageCreateFromPNG"; $imgx = "png"; }
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);
header("Content-Type: image/jpeg"); imagejpeg($new_image, NULL, 80);
}
}
if($_GET['thumb']) {
if( in_array($_GET['thumb'], $img_arr) ) make_thumbnail("./", $_GET['thumb']); // against file inclusion
exit();
}
?>
This is a gallery generator script, but it only shows me the pics when they are in the same directory as the script is in, how could I modify it to allow other scripts.
I've tried many tweaks but, nothing works.
It's almost certainly a file permissions issue as you're trying to open the root directory.
$od = opendir("./");
It will work for the directory that the script is in as the script will have permissions to access that directory.
I don't recommend giving PHP permission to access the root folder (even only in read mode) as it is a huge security risk, as theoretically someone could read your passwords file.
Instead you should use a non-root directory to hold the images you want to generate a gallery for and only give read permission to that, i.e.
mkdir /var/images
chmod a+r /var/images
I am using class.upload.php and I have the code all working except I want to extend the my script to work with multiple file uploads I read the documentation on the website and was able to figure it out. However I need my image files output like m_1234_1, m_1234_3, m_1234_4 and so on... How does one make it so that $handle->file_new_name_body = $new_name; starts with $new_name.'1' and continues adding 1 to every iteration?
<?php
$id = $_GET['id'];
if(isset($_POST['submit'])) {
// define variables
$new_name = 'm_'.$id.'_';
$thumb_name = 't_'.$id.'_';
$ext = 'jpg';
$upload_path = 'images/uploads/'.$id.'/'; // will not work with /images/
$full_src = $upload_path.$new_name.'.'.$ext;
// end define variables
$files = array();
foreach ($_FILES['userfile'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
foreach ($files as $file) {
$handle = new upload($_FILES['userfile']);
if ($handle->uploaded) {
// save uploaded image 458 x 332
$handle->file_new_name_body = $new_name;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 95;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 458;
$handle->image_y = 332;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
mysql_select_db($db);
mysql_query("UPDATE projects SET last_modified=NOW(), project_image_1 = '".$full_src."' WHERE id = $id") or die(mysql_error());
} else {
echo '<div class="ec-messages messages-error">';
echo 'Error: ' . $handle->error;
echo '</div>';
}
// create thumbnail 104 x 76
$handle->file_new_name_body = $thumb_name;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 90;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 104;
$handle->image_y = 76;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
echo '<div class="ec-messages messages-success">Image successfully uploaded and added to database (thumnails created)<br>Redirecting to projects main...</div><br><img src="'.$full_src.'" class="display-image">';
echo "<script>setTimeout(\"location.href='projects.php?msg=insert';\",2000);</script>";
include('Templates/footer_exit.php');
$handle->clean();
exit;
} else {
// no error here, error will be handled by the first script
}
}
}
}
?>
UPDATED (now working):
<?php
$id = $_GET['id'];
if(isset($_POST['submit'])) {
// define variables
$ext = 'jpg';
$upload_path = 'images/uploads/'.$id.'/'; // will not work with /images/
// end define variables
$files = array();
foreach ($_FILES['userfile'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
$counter = 1;
foreach ($files as $file) {
//$append = rand(100,99999);
$new_name = 'm_'.$id;
$thumb_name = 't_'.$id;
$handle = new upload($file);
if ($handle->uploaded) {
// save uploaded image 458 x 332
$count = $counter++;
$nn = sprintf("%s_%d", $new_name, $count);
$full_src = $upload_path.$nn.'.'.$ext;
$handle->file_new_name_body = $nn;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 95;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 458;
$handle->image_y = 332;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
mysql_select_db($db);
mysql_query("UPDATE projects SET last_modified=NOW(), project_image_".$count." = '".$full_src."' WHERE id = $id") or die(mysql_error());
} else {
echo '<div class="ec-messages messages-error">';
echo 'Error: ' . $handle->error;
echo '</div>';
}
// create thumbnail 104 x 76
$tn = sprintf("%s_%d", $thumb_name, $count);
$handle->file_new_name_body = $tn;
$handle->image_convert = $ext;
$handle->allowed = array('image/*');
$handle->jpeg_quality = 90;
$handle->image_resize = true;
$handle->image_ratio_crop = true;
$handle->image_x = 104;
$handle->image_y = 76;
$handle->file_overwrite = true;
$handle->auto_create_dir = true;
$handle->process($upload_path);
if ($handle->processed) {
echo 'Done!';
/*
echo '<div class="ec-messages messages-success">Image successfully uploaded and added to database (thumnails created)<br>Redirecting to projects main...</div><br><img src="'.$full_src.'" class="display-image">';
echo "<script>setTimeout(\"location.href='projects.php?msg=insert';\",2000);</script>";
include('Templates/footer_exit.php');
$handle->clean();
exit;
*/
} else {
// no error here, error will be handled by the first script
}
}
}
}
?>
You might define
$new_name = 'm_'.$id.'_';
$counter = 1; // File counter
at the beginning, and replace that line with
$handle->file_new_name_body = sprintf("%s.%d", $new_name, $counter++);
so that 'file' would become 'file.1.jpg', and so on.