Codeigniter File Upload Permit Only For Images not For Others - php

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'];
}
}
}

Related

An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter

The following php pdf to image code with imagick in codeigniter framework has a problem in the controller, imagick cannot read my file pdf.
error:
[codeigniter] An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter.
controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('files');
}
function index(){
$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result();
$data = array();
if($this->input->post('submitForm') && !empty($_FILES['upload_Files']['name'])){
$filesCount = count($_FILES['upload_Files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['upload_File']['name'] = $_FILES['upload_Files']['name'][$i];
$_FILES['upload_File']['type'] = $_FILES['upload_Files']['type'][$i];
$_FILES['upload_File']['tmp_name'] = $_FILES['upload_Files']['tmp_name'][$i];
$_FILES['upload_File']['error'] = $_FILES['upload_Files']['error'][$i];
$_FILES['upload_File']['size'] = $_FILES['upload_Files']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('upload_File')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->files->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
$this->load->helper('url');
$ImageName = $_FILES['upload_File']['name'];
$loc = base_url().$uploadPath.$ImageName;
echo $ImageName;
echo $loc;
$im = new imagick($loc);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < 1; $i++) {
$url = $loc.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage("uploads/files/img/".($i+1).'-'.$ImageName.'.jpg');
}
}
for($i = 0; $i<1;$i++) {
$img = "uploads/files/img/".($i+1).'-'.$ImageName.'.jpg';
$display .= "<img src='$img' title='Page-$i' /><br>";
}
$message = "PDF converted to JPEG sucessfully!!";
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
}
}
Solved
Is Correct Code
$ImageName= $fileData['file_name'];
$loc = realpath(APPPATH.'../uploads/files/').'/'.$ImageName;
Or you can just do
$loc = $fileData['full_path'];
This will work (tested):
//$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result(); // same at bottom??
$message = '';
$display = '';
if ($this->input->post('submitForm') && !empty($_FILES['userfile']['name'])) {
$uploadPath = FCPATH . 'uploads/files/';
if (!is_dir($uploadPath) && mkdir($uploadPath, DIR_WRITE_MODE, true) == false) {
show_error('Folder cannot be made!');
}
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
// change input field to <input type="file" name="userfile">
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('statusMsg', $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$uploadData['file_name'] = $fileData['file_name'];
$uploadData['created'] = date("Y-m-d H:i:s");
$uploadData['modified'] = date("Y-m-d H:i:s");
$insert = $this->files->insert($uploadData);
$insert = true;
if (!$insert) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', 'Database error. Please try again');
} else {
$this->session->set_flashdata('statusMsg', 'Files uploaded successfully.');
if ($fileData['file_ext'] == '.pdf') {
try {
$newPath = $uploadPath . 'img/';
if (!is_dir($newPath) && mkdir($newPath, DIR_WRITE_MODE, true) == false) {
throw new Exception('Folder cannot be made!');
}
$ImageName = $fileData['raw_name'];
$loc = $fileData['full_path'];
$im = new Imagick($loc);
$pdfPageCount = $im->getNumberImages();
if ($pdfPageCount > 0) {
for ($i = 0; $i < $pdfPageCount; $i++) {
$url = $loc . '[' . $i . ']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage($newPath . ($i + 1) . '-' . $ImageName . '.jpg');
$img = base_url("uploads/files/img/" . ($i + 1) . '-' . $ImageName . '.jpg');
$display .= "<img src='$img' title='Page-$i' /><br>";
}
echo $display; // debugging
$this->session->set_flashdata('statusMsg', "PDF converted to JPEG(s) sucessfully!");
}
} catch (Exception $e) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', $e->getMessage());
}
} else {
echo 'not a pdf'; // debugging only
}
}
}
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
Please note the input file field should now look like this:
<input type="file" name="userfile" />
You will also have to revise:
$this->files->insert($uploadData) function

Uploading multiple images in codeigniter not working

I want to upload my images array in codeigniter. The names of images are name = standimages[]. This is my controller
$config['upload_path'] = './uploads/individual_stands/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$config['overwrite'] = FALSE;
echo $this->upload_images($config, $_FILES, 'standimages');
And my function
function upload_images($config, $files, $name) {
if (!file_exists($config['upload_path'])) {
mkdir($config['upload_path'], 0777, true);
}
$filesCount = count($files[$name]['name']);
for ($i = 0; $i < $filesCount; $i++) {
$files['userFile']['name'] = $files[$name]['name'][$i];
$files['userFile']['type'] = $files[$name]['type'][$i];
$files['userFile']['tmp_name'] = $files[$name]['tmp_name'][$i];
$files['userFile']['error'] = $files[$name]['error'][$i];
$files['userFile']['size'] = $files[$name]['size'][$i];
pre($files);
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload($files['userFile'])) {
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if (!empty($uploadData)) {
//Insert file information into the database
$insert = $this->file->insert($uploadData);
return $statusMsg = $insert ? 'Files uploaded successfully.' : 'Some problem occurred, please try again.';
}
}
Any idea why my images are not being uploaded?
You must send input name to do_upload function:
if ($this->upload->do_upload($name) {
You can check this like as it is working for me.
Set your messages according to that.
if(!empty($_FILES['gallery_image']['name'][0]))
{
$j = 0;
for ($i = 0; $i < count($_FILES['gallery_image']['name']); $i++)
{
$target_path = 'images/gallery_images/';
if(!file_exists($target_path))
{
mkdir($target_path);
}
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['gallery_image']['name'][$i]));
$file_extension = end($ext);
$target_path = $target_path .$ext[0].'_'.time(). "." . $ext[count($ext) - 1];
$j = $j + 1;
if (in_array(strtolower($file_extension), $validextensions))
{
if (move_uploaded_file($_FILES['gallery_image']['tmp_name'][$i], $target_path))
{
$insert_img_query = "INSERT INTO event_gallery (image, event_id) VALUES ('".$ext[0].'_'.time(). "." . $ext[count($ext) - 1]."','".$edited_id."')";
$result = mysqli_query($con,$insert_img_query);
}
else
{
header('Location:index.php'); //Redirect your page as per your requirement.
exit();
}
}
else
{
header('Location:index.php'); //Redirect your page as per your requirement.
exit();
}
}
}
Try to change your code like this:
It convert array of files in single files at a time
$_FILES['userFile']['name'] = $_FILES['userFiles']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['userFiles']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['userFiles']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['userFiles']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['userFiles']['size'][$i];
And pass file name like this :
$this->upload->do_upload('userFile');
Maybe do_upload function can't understand data in $files array for moving file in folder
Hope this helps you
change do_upload function parameter with file input name
if ($this->upload->do_upload($name)) {

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

error in upload form

hello i copyed 1 upload file source code with upload progress bar
its work if i delete foreach and make 1 file for upload
but i want have 5 file field in my form
this is my code now:
$upload_directory = "$fUllp/";
//5M
$allowsize = 5242880;
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
if($s <= $allowsize){
$filename = explode('.',$n);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($t,$allow)){
if (move_uploaded_file($tmp, $upload_directory . $filename)) {
//insert db
//img full
$fullurl = $siteurl.'/'.$upload_directory.$filename;
//for sql
$fullurlsq = '/'.$upload_directory.$filename;
$fullurlsqt = '/'.$upload_directory.'t/'.$filename;
//img resize
$image = new SimpleImage();
$image->load($upload_directory.'/'.$filename);
$image->resizeToHeight(100);
$image->resizeToWidth(100);
$image->save($upload_directory.'/t/'.$filename);
//img koochik
$imgt = $upload_directory.'/t/'.$filename;
mysql_query("insert into up_guest(name,name_t,type,time,ip) values('$fullurlsq','$fullurlsqt','$filetype',$time,'$ip')");
print '<br><div class="system-message"><ul class="index_info"><li>توضیح: <span>فایل با موفقیت آپلود شد<bR /><div class="thumb_img">';
print "<img src=\"$imgt\"></div>";
//tbl1
print '<table border="0" width="100%" cellspacing="0" cellpadding="0" class="up_box_input"><tbody><tr><td class="btitle">لینک تصویر کوچک</td><td class="all_box_link"><textarea readonly="readonly" rows="2" cols="40" class="up_input" tabindex="1" onclick="this.select();">';
print "[url=$siteurl/][img]$imgt [/img][/url]</textarea></td></tr></tbody></table>";
//tbl2
print 'echo file detaid for user';
}//file upload she
else{
echo '<div class="site_error_msg">cant up</div>';
}
}//age allow bood un file
else{
echo '<div class="site_error_msg">extention not allowed</div>';
}
}//if noghte vasatesh nabood
else{
echo '<div class="site_error_msg">you not must have . in file name</div>';
}
}//if sizesh mojaz bood
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
but
its run else in first IF
i mean
if(in_array($t,$allow)){
and run this else
else{
echo '<div class="site_error_msg">uploaded file is more than 5 MB</div>';
}//end my code
so its must something wrong with
these lines and its set file name size incorect
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
ok find my nooblish problem ! i must inter my file size and name under For like this
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
$t = $file['type'];
$tmp = $file['tmp_name'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
$ss = $s[$i];
$tmpp = $tmp[$i];
$nn = $n[$i];
$tt = $t[$i];
if($ss <= $allowsize){
$filename = explode('.',$nn);
$filetype = $filename[1];
if(!isset($filename[2])){
$glast = mysql_query("select id from up_guest order by id desc limit 1");
$flast = mysql_fetch_array($glast);
if($flast['id'] == '' or $flast['id'] <= 0){
$flast = 1;
}
else{
$flast = $flast['id'] + 1;
}
$time = time();
$filename = $flast.'.'.$filename[1];
if(in_array($tt,$allow)){
thank you all :D

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