How to upload files using Codeigniter? - codeigniter

I use this strange code to upload files:
if (!empty($_FILES['file']['name']) && count(array_filter($_FILES['file']['name'])) > 0) {
$filesCount = count($_FILES['file']['name']);
for ($i = 0; $i < $filesCount; $i++) {
$_FILES['file']['name'] = $_FILES['file']['name'][$i];
$_FILES['file']['type'] = $_FILES['file']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['file']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['file']['error'][$i];
$_FILES['file']['size'] = $_FILES['file']['size'][$i];
/* File upload configuration */
$uploadPath = 'uploads/reviews/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
/* $config['max_size'] = '100'; */
/* $config['max_width'] = '1024'; */
/* $config['max_height'] = '768'; */
/* Load and initialize upload library */
$this->load->library('upload', $config);
$this->upload->initialize($config);
/* Upload file to server */
if ($this->upload->do_upload('file')) {
/* Uploaded file data */
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['uploaded_on'] = date("Y-m-d H:i:s");
} else {
}
}
}
But I wonder why it rewrites a $_FILES and why I get error on line:
`$_FILES['file']['error'] = $_FILES['file']['error'][$i];`
Error is:
Message: Trying to access array offset on value of type int

You're getting the error because you're looping over an array and modifying that same array within the loop.
$_FILES['file']['error'][$i] is an integer, so in the first iteration of the loop $_FILES['file']['error'] becomes an integer.
In the second iteration of the loop, when you try to access $_FILES['file']['error'][$i], it is trying to treat the integer that is now at $_FILES['file']['error'] as an array and get element [$i], which is impossible.
(You're not getting this error on $_FILES['file']['name'][$i], $_FILES['file']['type'][$i] and $_FILES['file']['tmp_name'][$i] because the file name, type and tmp_name are string values.
And when you try to treat a string value as an array, it will get the character at position [$i]. Which probably isn't what you were looking for either, but it does not give an error.)
The solution is to copy the $_FILES array and loop over the copy while assigning the values back to the $_FILES array, as in the accepted answer here: https://stackoverflow.com/a/11539061/3960296

Related

Creating thumbnails of multiple images?

I am uploading max 5 images and i want to create the thumbnails of those 5 images i am successful in uploading and saving image name in database but can't able to make thumbnails.
//controller
$files = $_FILES;
$cpt = count($_FILES['uploadfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name']; //success till here now inserting in database and creating thumbnails
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
var_dump($images);
#$form['picture1']=$images[0];
#$form['picture2']=$images[1];
#$form['picture3']=$images[2];
#$form['picture4']=$images[3];
#$form['picture5']=$images[4];
//
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = LARGEPATH; //give the path to upload the image in folder
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
$config['overwrite'] = FALSE;
return $config;
}
now i want as 5 images are uploaded in folder at the same time thumbnails of those 5 images are created.
You can use CodeIgniter's Image Manipulation Class for thumbnails creation: check CodeIgniter 3 manual
i found my solution :
private function _makeThumb($source, $filename, $num = 5)
{
$config2['image_library'] = 'gd2';
$config2['source_image'] = $source;
$config2['new_image'] = THUMBPATH.$filename;
$config2['create_thumb'] = TRUE;
$config2['maintain_ratio'] = TRUE;
$config2['width'] = 75;
$config2['height'] = 50;
return $config2;
}
then i can call this function in a loop to create a thumnails

access folder outside CodeIgniter

I've been to trying to upload images using code igniter and it works perfectly when the upload folder is just outside of application folder. But my problem is when I try to access folder which is outside whole code igniter folder it is throwing me a error. How to access the folder outside the code igniter folder? I tried $_SERVER['DOCUMENT_ROOT']. But it dint help.
$name = $_POST['name'];
$id = $_POST['id'];
if (isset($_FILES['upload']['name'])) {
// total files //
$count = count($_FILES['upload']['name']);
// all uploads //
$uploads = $_FILES['upload'];
for ($i = 0; $i < $count; $i++) {
if ($uploads['error'][$i] == 0) {
$firstimage = $uploads['name'][$i];
$secondimage = $uploads['name'][$i];
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
$config2['image_library'] = 'gd2';
$config2['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config2['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/thumbnail/'.$uploads['name'][$i];
$config2['maintain_ratio'] = FALSE;
$config2['create_thumb'] = TRUE;
$config2['thumb_marker'] = '_thumb';
$config2['width'] = 75;
$config2['height'] = 50;
$config2['overwrite'] = TRUE;
$this->image_lib->initialize($config2);
$this->load->library('image_lib',$config2);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
$config3['image_library'] = 'gd2';
$config3['source_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i];
$config3['new_image'] = $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/resize/'.$uploads['name'][$i];
$config3['maintain_ratio'] = FALSE;
$config3['create_thumb'] = TRUE;
$config3['thumb_marker'] = '_thumb';
$config3['width'] = 470;
$config3['height'] = 470;
$config3['overwrite'] = TRUE;
$this->image_lib->initialize($config3);
$this->load->library('image_lib',$config3);
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
}
}
$this->load->view('head');
$data = array(
'name' => $name,
'id' => $id
);
After discussing in comments, the problem is likely the move_uploaded_file() function is trying to move the file to a directory that doesn't exist yet.
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);
Before the file can be moved the folder needs to be created. If $id is new, it has probably not been created yet. So...
if (!is_dir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id)) {
mkdir($_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id);
}
move_uploaded_file($uploads['tmp_name'][$i], $_SERVER['DOCUMENT_ROOT'].'tuition/tuitionimage/'.$id.'/'.$uploads['name'][$i]);

How resize image in Joomla?

I try use this:
$image = new JImage();
$image->loadFile($item->logo);
$image->resize('208', '125');
$properties = JImage::getImageFileProperties($item->logo);
echo $image->toFile(JPATH_CACHE . DS . $item->logo, $properties->type);
But not work =\ any idea?
Try this out:
// Set the path to the file
$file = '/Absolute/Path/To/File';
// Instantiate our JImage object
$image = new JImage($file);
// Get the file's properties
$properties = JImage::getImageFileProperties($file);
// Declare the size of our new image
$width = 100;
$height = 100;
// Resize the file as a new object
$resizedImage = $image->resize($width, $height, true);
// Determine the MIME of the original file to get the proper type for output
$mime = $properties->mime;
if ($mime == 'image/jpeg')
{
$type = IMAGETYPE_JPEG;
}
elseif ($mime == 'image/png')
{
$type = IMAGETYPE_PNG;
}
elseif ($mime == 'image/gif')
{
$type = IMAGETYPE_GIF;
}
// Store the resized image to a new file
$resizedImage->toFile('/Absolute/Path/To/New/File', $type);

Differentiating between video and image upload in CodeIgniter

I can upload either of image or video from my file. I've set the configuration file for image as follows :
$config['upload_path'] = './docs/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200';
$config['max_width'] = '250';
$config['max_height'] = '250';
$config['file_name'] = md5(rand().time());
$this -> load -> library('upload', $config);
But when I'll upload video, this configuration will not work as I need to be able to upload much bigger size file ( video ). Is there any way after submitting to find out what I've uploaded ( img/video ) and based on that I can enable the configuration file.
The configuration for video is as follows :
$configVideo['upload_path'] = './docs/';
$configVideo['max_size'] = '50240';
$configVideo['allowed_types'] = 'avi|flv|wmv|mp3|wma';
$configVideo['overwrite'] = FALSE;
$configVideo['remove_spaces'] = TRUE;
$video_name = $date.$_FILES['video']['name'];
$configVideo['file_name'] = $video_name;
$this->load->library('upload', $configVideo);
$this->upload->initialize($configVideo);
You can use $_FILES to find out the type first.
untested
$type = $_FILES['userfile']['type'];
switch ($type) {
case 'gif':
case 'jpg':
case 'png':
// do img config setup
break;
case 'avi':
case 'flv':
case 'wmv':
case 'mp3':
case 'wma':
// do video config
break;
}
Or if you use different names for the files in the form then why not try;
[updated]
$config['upload_path'] = './docs/';
if (is_array($_FILES) && isset($_FILES['image']['name'])) {
// is an image
$config['upload_path'] = './docs/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200';
$config['max_width'] = '250';
$config['max_height'] = '250';
$config['file_name'] = md5(rand().time());
} elseif (is_array($_FILES) && isset($_FILES['video']['name'])) {
// is a video
$config['max_size'] = '50240';
$config['allowed_types'] = 'avi|flv|wmv|mp3|wma';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$video_name = $date.$_FILES['video']['name'];
$config['file_name'] = $video_name;
}
$this->load->library('upload', $config);
$this->upload->initialize($config);

CodeIgniter Upload and Resize Problem

I have spent days trying to make this work based on the examples in the documentation but I am missing something or I am just STUPID!
I have a CMS application where users upload an image for display in a very fixed layout. We do not want to limit the file size of the uploaded image but would rather "process" it after it arrives.
The image needs to be 615px wide but some of the images uploaded directly from digital cameras are 2500X2000 and bigger so this is CRITICAL.
I pieced together the code from the manual and the image is successfully being uploaded to a folder within the CMS app. However, the image is NOT being resized.
If I ever get it to re-size, my plan is to present the image to the user for cropping using jCrop (the final image HAS to be 615X275 and it probably has to be cropped for height after resizing) and then use codeigniter to FTP the image to their site's amenities folder using the original name.
I will appreciate any help in this matter!
Here's my code:
function do_feature_upload() {
$imageName = $this->uri->segment(3);
//echo $imageName;
// Where the file is going to be placed
$config['upload_path'] = "./uploads/".$_SESSION['dbPropNumber'];
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '0';
$config['file_name'] = $imageName.'.jpg';
$config['overwrite'] = 'TRUE';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$error['propertyDropdown'] = $_SESSION['propertyDropdown'];
$error['username'] = $_SESSION['username'];
$error['dbPropNumber'] = $_SESSION['dbPropNumber'];
$error['propertyName'] = $this->content->getPropertyName($_SESSION['dbPropNumber']);
$this->load->view('upload_AmenityImage', $error);
} else {
$image_data = $this->upload->data();
$origWidth = $image_data['image_width'];
$origHeight = $image_data['image_height'];
$newWidth = 615;
$newHeight = $newWidth*$origHeight/$origWidth;
$resize = array(
'image_library'=>'gd2',
'source_image'=>base_url().'uploads/'.$_SESSION['dbPropNumber'].'/'.$imageName.'.jpg',
'new_image'=>base_url().'uploads/'.$_SESSION['dbPropNumber'].'/'.$imageName.'1.jpg',
'create_thumb' => FALSE,
'maintain_ratio'=>FALSE,
'width'=>$newWidth,
'height'=>$newHeight
);
$this->load->library('image_lib',$resize);
$this->image_lib->resize();
$data = array('upload_data' => $this->upload->data());
$data['propertyDropdown'] = $_SESSION['propertyDropdown'];
$data['username'] = $_SESSION['username'];
$data['dbPropNumber'] = $_SESSION['dbPropNumber'];
$data['propertyName'] = $this->content->getPropertyName($_SESSION['dbPropNumber']);
//Present jCrop option after image is resized
// FTP to final destination
$this->load->view('upload_success', $data);
} // end if
} // end function
I'm not entirely sure what's going wrong with your code, but here's a model function I wrote for resizing images to fit an exact target height and target width. Read through it and see if you can't figure out the solution.
$this->prefix is a property in my class that I use so I don't have to keep writing out the directory of the file. It looks like this:
$this->prefix = FCPATH.'uploads'.DIRECTORY_SEPARATOR;
Image resizer
/**
* Resizes an image to fit exact dimensions
*
* #param string filename
* #param int target_width
* #param int target_height
*
* #return array('success' ? null : 'error')
*/
function resizeImageToDimensions($filename, $target_width=700, $target_height=399)
{
$file_type = $this->getFileType($this->prefix.$filename);
if (!$file_type || $file_type != 'image')
return array('success'=>false, 'error'=>"This file doesn't exist or isn't an image");
$this->load->library('image_lib');
list($width, $height) = getimagesize($this->prefix.$filename);
$current_ratio = $width/$height;
$target_ratio = $target_width/$target_height;
$config['source_image'] = $this->prefix.$filename;
if ($current_ratio > $target_ratio)
{
//resize first to height, maintain ratio
$config['height'] = $target_height;
$config['width'] = $target_height * $current_ratio;
$this->image_lib->initialize($config);
if (!$this->image_lib->resize())
return array('success'=>false, 'error'=>"There was an error while resizing this image");
//then crop off width
$config['width'] = $target_width;
$config['maintain_ratio'] = false;
$this->image_lib->initialize($config);
if ($this->image_lib->crop())
return array('success'=>true);
else
return array('success'=>false, 'error'=>"There was an error while cropping this image");
}
else if ($current_ratio < $target_ratio)
{
//resize first to width, maintain ratio
$config['width'] = $target_width;
$config['height'] = $target_width / $current_ratio;
$this->image_lib->initialize($config);
if (!$this->image_lib->resize())
return array('success'=>false, 'error'=>"There was an error while resizing this image");
//then crop off height
$config['height'] = $target_height;
$config['maintain_ratio'] = false;
$this->image_lib->initialize($config);
if ($this->image_lib->crop())
return array('success'=>true);
else
return array('success'=>false, 'error'=>"There was an error while cropping this image");
}
else {
$config['width'] = $target_width;
$config['height'] = $target_height;
$this->image_lib->initialize($config);
if ($this->image_lib->resize())
return array('success'=>true);
else
return array('success'=>false, 'error'=>"There was an error while resizing this image");
}
}
I had the same problem a few months back and sadly, I wasn't able to figure it out. I've posted the same question here and in CodeIgniter's forums but no one could help me.
I ended up using timthumb script, which is great, but nowhere near ideal :(
So, if you're in a rush, I'd strongly recommend using timthumb. If you have some time to invest on it, I wish you the best and please, share!

Resources