Upload file in PHP? - php

When I upload an image file to the host, why the file repeat filename extension again ? I check the filename in the host is like test.jpg.jpg
Here is the code:
$uploadPath = "../../upload/Image/";
$handle = new Upload($_FILES['pic'], 'zh_TW');
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
$filename = $pic;
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
$handle->file_new_name_body = $filename;
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 212;
$handle->image_ratio_fill = true;
$handle->allowed = array('image/*');
$handle->file_overwrite = true;
$handle->process($uploadPath);
if($handle->processed){
$handle->file_dst_name = $filename;
}
else{
echo "<script>";
echo "alert('$handle->error');";
echo "history.back();";
echo "</script>";
die;
}
}
else{
$filename = $_POST['currentPic'];
}

Base on your conditions. you can just get the name onle part by explode function.
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
//$filename = $pic;
$filename = explode(".",$pic)[0];
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
This is so you dont need to modify your class, also if you modify your class you will get trouble on the "ELSE" side of your condition that will cause additional spending time where to get the extension.

Related

Codeigniter File Upload Permit Only For Images not For Others

I have to file upload operation consecutive, first for images like gif|jpg|jpeg|png|svg and the second psd|rar|zip|doc|word|txt|xlsx|pdf
First one is working just fine, i can upload all images but the second, i can not upload any of these types but when i try to upload image on second segment it works.
if (isset($_FILES['content_images']['name'])) {
$count_files = count($_FILES['content_images']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->load->library("upload", $config_images);
if (!$this->upload->do_upload('image')) {
echo $this->upload->display_errors();
exit;
} else {
$data = $this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if (isset($_FILES['content_files']['name'])) {
$count_files=count($_FILES['content_files']['name']);
for ($i = 0; $i < $count_files; $i++) {
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->load->library("upload",$config_files);
if (!$this->upload->do_upload('file')) {
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
} else {
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}
I found the solution
For help :
You should load the library at the top for 1 time only, and then u should initialize it inside 'if condition'.
When you load upload library and config array inside first condition, when you pass to second condition upload library had already loaded and uses the first condition's config array.
$this->load->library("upload");
if(isset($_FILES['content_images']['name'])){
$count_files=count($_FILES['content_images']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['image']['name'] = $_FILES['content_images']['name'][$i];
$_FILES['image']['type'] = $_FILES['content_images']['type'][$i];
$_FILES['image']['tmp_name'] = $_FILES['content_images']['tmp_name'][$i];
$_FILES['image']['error'] = $_FILES['content_images']['error'][$i];
$_FILES['image']['size'] = $_FILES['content_images']['size'][$i];
$config_images['upload_path'] = "./public/site/images/contents";
$config_images['allowed_types'] = 'gif|jpg|jpeg|png|svg';
$config_images['max_size'] = 5000;
$config_images['max_width'] = 7680;
$config_images['max_height'] = 4320;
$this->upload->initialize($config_images);
if(!$this->upload->do_upload('image')){
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_images[] = "public/site/images/contents/".$data['file_name'];
}
}
}
if(isset($_FILES['content_files']['name'])){
$count_files=count($_FILES['content_files']['name']);
for($i = 0;$i<$count_files;$i++){
$_FILES['file']['name'] = $_FILES['content_files']['name'][$i];
$_FILES['file']['type'] = $_FILES['content_files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['content_files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['content_files']['error'][$i];
$_FILES['file']['size'] = $_FILES['content_files']['size'][$i];
$config_files['upload_path'] = "./public/site/files/contents";
$config_files['allowed_types'] = 'psd|rar|zip|doc|word|txt|xlsx|pdf';
$config_files['max_size'] = 5000;
$config_files['max_width'] = 7680;
$config_files['max_height'] = 4320;
$this->upload->initialize($config_files);
if(!$this->upload->do_upload('file')){
foreach($path_images as $p){
unlink($p);
}
echo $this->upload->display_errors();
exit;
}else{
$data=$this->upload->data();
$path_files[] = "public/site/files/contents/".$data['file_name'];
}
}
}

PHP read lines not working on some computers but works on most

So im reading an CSV file and splitting it apart to get email,name,last name, however this outputs differently on different computers in my platform, let's say when I upload the same file it reads 38 lines and save them. However in 2 specific computers it reads only 1.
Before I was reading only TEMP file, but now im saving it to a directory and reading from there, however the problem is still here, I compared the file size and is the same even the content.
Is this a PHP bug ?
<?php
global $user;
if(isset($_POST['submit'])) {
if ($_FILES['file']['tmp_name']) {
$nome = $_POST['nome'];
$file = $_FILES['file']['tmp_name'];
$user->criarLista($nome, $file);
} else {
$user->mensagem(1, "Não existe nenhum ficheiro");
}
}
?>
public function criarLista($nome,$file){
// ADDED TO SAVE THE FILE IN THE SYSTEM AND READ FROM IT
if(file_exists("uploads/lista.txt")){ unlink("uploads/lista.txt"); }
move_uploaded_file($file, "uploads/lista.txt");
$file = file_get_contents("uploads/lista.txt");
$user = $this->user;
$get = $this->connect->query("SELECT * FROM users WHERE email = '$user'");
$fetch = $get->fetch_array(MYSQLI_ASSOC);
$user_id = $fetch['id'];
if($insert = $this->connect->prepare("INSERT INTO lista(user_id,nome) VALUES(?,?)")){
$insert->bind_param("is", $user_id,$nome);
$insert->execute();
$list_id = $insert->insert_id;
$file = preg_replace('#\\x1b[[][^A-Za-z]*[A-Za-z]#', '', $file);
$file = strip_tags($file);
$lines = file("uploads/lista.txt");
$emails = array();
$fnames = array();
$lnames = array();
$linha = 0;
foreach($lines as $line) {
if($linha == 0){
}else{
echo $Linha."</br>";
if (strpos($line, ',') !== false) {
$arr = explode(",", $line);
// Email \ FNAME | LAST
$emailx = trim($arr[0]);
$emailx = trim(preg_replace("/[\\n\\r]+/", "", $emailx));
array_push($emails,$emailx);
if(isset($arr[1])){
$fname = trim($arr[1]);
$fname = str_replace('"','',$fname);
array_push($fnames,$fname);
}
if(isset($arr[2])){
$lname = trim($arr[2]);
array_push($lnames,$lname);
}
}else{
array_push($emails,trim($line));
}
}
$linha++;
}
array_map('trim', $emails);
array_map('trim', $fnames);
array_map('trim', $lnames);
$emails = implode(",",$emails);
$fnames = implode(",",$fnames);
$lnames = implode(",",$lnames);
if($insert_list = $this->connect->prepare("INSERT INTO listas(lista_id,email,primeiro_nome,ultimo_nome) VALUES(?,?,?,?)")){
$insert_list->bind_param("isss", $list_id,$emails,$fnames,$lnames);
$insert_list->execute();
$this->mensagem(2,"Lista adicionada com sucesso");
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}else{
echo
'
<div class="alert alert-danger">
Erro: '.$this->connect->error.'
</div>
';
}
}
FIXED this adding this on top of the function :
ini_set('auto_detect_line_endings',true);
I am not sure this is an 'answer' to what is going on, though it is what I had to do to fix an issue with a Mac user sending files.
What I found was that, every time he did an upload, it would send a .zip file, not just the file (like the PCs did). I did not have other Mac users to test against, so, again, I can't say this is exactly the issue you have, but I trust it will at least help in your search.
Note that I had to chop a lot of code out of this (where I was doing various other functions with the database, etc.), so this may not run directly, but I think I closed all the 'ifs' and such - or you can figure it out (if not, let me know and I'll go through it again).
Hope this helps!
$save_file = basename($_FILES["fileToUpload"]["name"]);
$zipfile='maps/'.$save_file; // location of a temp location (stops double uploads)
$alert_upload_file_exists = "Uploaded file exists!";
$alert_upload_successful = "UPLOAD SUCCESSFUL";
$action_failed_text = "Action FAILED";
if(file_exists($zipfile) && (empty($_GET['overwrite']) || $_GET['overwrite'] == 'false'))
die($alert_upload_file_exists);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $zipfile))
{
// I found this mac to be sending a .zip file, not a standard one..... :(
$uploadOk = 0;
$mac_file = 0;
if($basename = basename($_FILES["fileToUpload"]["name"],".zip"))
{
$zip = new ZipArchive;
if($zip->open($zipfile) === true){
// echo "basename is $basename<BR>";
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
// look for the file we really want (in our case, any sort of img file)
if($fileinfo['basename'] == $basename . '.png' || $fileinfo['basename'] == $basename . '.jpg' || $fileinfo['basename'] == $basename . '.gif') {
$imgfile = $_GET['loc_data_id'].".".$fileinfo['extension'];
$files[]=$fileinfo['basename'];
// echo "file added to the list <BR>";
}
// echo "filename is $filename, basename is ->".$fileinfo['basename']."<- fileinfo = ";print_r($fileinfo);
// CHECK TO SEE IF THIS WAS THE 'WEIRD' MAC FILE
if($fileinfo['basename'] == "__MACOSX")
$mac_file = 1;
// echo "mac_file is $mac_file ";
}
if(($imglist = array_keys(array_flip(preg_grep('/^.*\.(jpg|jpeg|png|gif)$/i',$files))))
{
// echo "imglist = ";print_r($imglist);
// echo "files = ";print_r($files);
foreach($files as $key => $value)
{
if ($imglist[0]==$value) {$file = $imgfile;}
$upgrade += file_exists('maps/'.$file);
// echo "imgfile is $imgfile, file is $file upgrade is $upgrade and value is ".$basename."/".$value." ............";
// more 'FUNNY BUSINESS' to work the Mac file....
if($mac_file){
$extracted = $zip->extractTo('maps/',$basename."/".$value);
rename("maps/$basename/$value","maps/$file");
}
else {
$extracted = $zip->extractTo('maps/',$value);
rename("maps/$value","maps/$file");
}
}
// AND A BIT MORE.....
if($mac_file){
rmdir ("maps/$basename");
}
$zip->close();
$imgcount=0;$mapcount=0;$uploadOk=1;
$html = file_get_html('maps/'.$mapfile);
$imgck = strpos($html,'<img ');
if(($imgck===false) || $imgck<>0) {
$uploadOk += 2;
}
// echo "uploadOk is $uploadOk<br>";
if($uploadOk==1)
{
$mapname = pathinfo('maps/'.$mapfile);
// echo "mapfile is $mapfile, mapname = ";print_r($mapname);
}
}
else $uploadOk += 20;
}
}
if($uploadOk==1) echo basename($_FILES["fileToUpload"]["name"])." ".$alert_upload_successful;
else echo $action_failed_text . " ".$uploadOk;
// delete the original .zip file (and any that are in the 'maps/' folder)
array_map('unlink', glob("maps/*.zip"));
}
else
{
echo "Sorry, there was an error uploading your file.";
echo "temp name is " . $_FILES["fileToUpload"]["tmp_name"]. " save file is ". $save_file."<br>";
}

Stripping Filename in PHP

I'm building a version control system in PHP. I almost have a fully working system and am currently adding features. My code below renames a file as "filename_Ver 0.01" and increments by .01 if the user selects a minor revision from the html selectbox. If it's a major revision, the file gets renamed as filename_Ver 1 and increments by 1 for each major version. If I combine both, let's say a major and a minor revision I end up with a file named "filename_Ver 1.01.ext"
Displaying the filename in a PHP table is easy enough but I'd like to optionally just display the version number say in a seperate table field called "Version". How would I strip that from the filename so I can add that to the database? I know I'd have to do something within the while loop to get what I want out. $file = $dr.$fName.'_'.'Ver '.$i.$ext; I want it to display something like the following:
FileName | Version
test_Ver 0.1 | 0.1
test_Ver 0.2 | 0.2
test_Ver 1 | 1
test_Ver 1.1 | 1.1
function update_file_name_major($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 1;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i++;
}
return $file;
}
function get_file_name_major_latest($file)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = substr($file,0,($dir+1));
$arr = explode('/',$file);
$fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext));
$exist = FALSE;
$i = 1;
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file)){
$exist = TRUE;
return $i;
}
$i++;
}
return 0;
}
function update_file_name_minor($file, $latest_major = 0)
{
$pos = strrpos($file,'.');
$ext = substr($file,$pos);
$dir = strrpos($file,'/');
$dr = str_replace(end(explode("/",$file)), '', $file);
$arr = explode('/',$file);
$fName = current(explode(".",end(explode("/",$file))));
$exist = FALSE;
$i = (float) $latest_major. '.01';
while(!$exist)
{
$file = $dr.$fName.'_'.'Ver '.$i.$ext;
if(!file_exists($file))
$exist = TRUE;
$i += 0.01;
}
return $file;
}
if ( isset( $_POST['addfile'] ) ) {
// variables
define('UPLOAD_DIR', 'repository/');
$fileName = $_FILES['file'];
$file_type = $_FILES['file']['type'];
$projectname=$_POST['projectname'];
$comments=$_POST['comments'];
if($_POST['rev_type'] == 'Minor') {
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$latest_major = 0;
if(update_file_name_major(UPLOAD_DIR.$fileName['name']) != UPLOAD_DIR.$fileName['name']){
$latest_major = get_file_name_major_latest(UPLOAD_DIR.$fileName['name']);
--$latest_major;
}
$updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name'], $latest_major);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
include 'db.php';
$updatedFileName2 = update_file_name_minor($fileName['name'], $latest_major);
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created)
VALUES ('$updatedFileName2', '$file_type','$projectname','$comments', NOW())");
echo "You have successfully uploaded and renamed the file as a minor revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
elseif($_POST['rev_type'] == 'Major') {
// check for which action should be taken if file already exist
if(file_exists(UPLOAD_DIR . $fileName['name']))
{
$updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']);
move_uploaded_file($fileName['tmp_name'], $updatedFileName);
include 'db.php';
$updatedFileName2 = update_file_name_major($fileName['name']);
$add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created)
VALUES ('$updatedFileName2', '$file_type','$projectname','$comments', NOW())");
echo "You have successfully uploaded and renamed the file as a major revision.";
}
else
{
move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']);
echo "You have successfully uploaded the file.";
}
}
} //main if

class.upload.php and file extension missing

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.

Dynamic file name with multiple image upload

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.

Categories