How can I catch Codeigniter multiple file upload error? - php

I'm using Codeigniter for uploading files. It's working fine when I meet the file requirements. The problem is, I want to display the errors if ever there is one, but my page only refreshes when there is an error. Here is my code (I only got the code from the web and revised it):
foreach($_FILES['userfile'] as $key=>$val)
{
$i = 1;
foreach($val as $v)
{
$field_name = "file_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}
$err = 0;
$i=0;
// Unset the useless one ;)
unset($_FILES['userfile']);
$config['file_name'] = time();
$config['upload_path'] = './uploads/events';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '200000';
$this->load->library('upload',$config);
foreach($_FILES as $field_name => $file)
{
if ($this->upload->do_upload($field_name))
{
$upload_data = $this->upload->data(); //UPLOAD FILES TO FOLDER
$this->Upload_items->files($upload_data['file_name']); //WRITE TO DATABASE;
}else{
echo $this->upload->display_errors();
}
$i++;
if(($i==$ctr)&&($err==0)){
$this->Upload_items->event(); //WRITE TO MULTIMEDIA TABLE
}
}
The functions to write to the database are not yet done, btw.
EDIT: The error for allowed_types is displaying, but the error for exceeding file size is not.

$config ['upload_path'] = 'upload/Main_category_product/';
$path = $config ['upload_path'];
$config ['allowed_types'] = 'gif|jpg|jpeg|png';
$config ['max_size'] = '1024';
$config ['max_width'] = '1920';
$config ['max_height'] = '1280';
$this->load->library ( 'upload', $config );
foreach ( $_FILES as $key => $value ) {
if (! empty ( $value ['tmp_name'] ) && $value ['size'] > 0) {
if (! $this->upload->do_upload ( $key )) {
$errors = $this->upload->display_errors ();
flashMsg ( $errors );
} else {
// Code After Files Upload Success GOES HERE
}
}
}
Using the FlashMSG function send the messages right time to the users. OR collect all messages in a array and display in the end.

Related

php copy file for each filename in array

I am trying to move all the files in my array from one directory to another.
I have done some research and are using the php Copy() function.
here is my code so far:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = print_r($myArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
for($i = 0;$i < count($finalArray);$i++){
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);}
}
Anyone see where I'm going wrong?
Thanks in advance!
This is the unlink ive been attempting to use.
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
}
// Delete all successfully-copied files
foreach ( $delete as $file ) {
unlink( $sourcePath.$file );
}
My Final Working Code
the code below moves images in comma seperated array to new folder and removes them from current folder
$finalArray = explode(',', $filenameArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
}
}
copyFiles( $finalArray, $sourcePath, $savePath);
function removeFiles($finalArray,$sourcePath) {
foreach ($finalArray as $file){
if (!unlink($sourcePath.$file)) {
echo "Failed to remove image";
}
}
}
removeFiles( $finalArray, $sourcePath);
In your code you are not calling the copyFile function. Try this:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
function mvFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!rename($sourcePath.$file,$savePath.$file)) {
echo "failed to copy $file...\n";
}
}
}
mvFiles( $finalArray, $sourcePath, $savePath);
A simple solution :
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = $myArray; //corrected this line
function copyFiles($finalArray, $sourcePath, $savePath)
{
for ($i = 0; $i < count($finalArray); $i++)
{
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);
}
}
Hope you have right call to function copyFiles().
UPDATE for unlink() :
Let me try to throw some light on your work (written code):
foreach ($finalArray as $file)
{
if (!copy($sourcePath.$file,$savePath.$file))
{
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
Contents of $delete :
a. /source/img1.png
b. /source/img2.png
c. /source/img3.png
Now,
foreach ( $delete as $file )
{
unlink( $sourcePath.$file );
}
unlink() will be called with the following parameters:
$sourcePath.$file : /source/./source/img1.png : /source//source/img1.png => No such path exists
$sourcePath.$file : /source/./source/img2.png : /source//source/img2.png => No such path exists
$sourcePath.$file : /source/./source/img3.png : /source//source/img3.png => No such path exists
$sourcePath.$file : /source/./source/img4.png : /source//source/img4.png => No such path exists
I think for this reason, unlink is not working.
The code to be written should be like the following:
foreach ( $delete as $file )
{
unlink( $file );
}
Now, unlink() will be called with the following parameters:
a. /source/img1.png => path do exists
b. /source/img2.png => path do exists
c. /source/img3.png => path do exists
Do tell me if this does not solves the issue.
Update as per Dave Lynch's code:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
foreach ($finalArray as $file)
{
$delete[] = $sourcePath.$file;
}
foreach ( $delete as $file )
{
echo $sourcePath.$file . "</br>";
}
Output:
/source//source/img1.png
/source//source/img2.png
/source//source/img3.png
Please check.
Thanks and Regards,

Multiple files uploading not working in Codeigniter

While uploading the multiple files in codeigniter i am getting error like this,
Fatal error: Unsupported operand types in .../system\libraries\Upload.php
if(isset($_FILES['med_file']))
{
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
$this->load->library('upload', $config);
$files = $_FILES;
$cpt = count($_FILES['med_file']['name']);
for($i=0; $i<$cpt; $i++)
{
if($files['med_file']['name'][$i] !="")
{
$_FILES['med_file']['name']= $files['med_file']['name'][$i];
$_FILES['med_file']['type']= $files['med_file']['type'][$i];
$_FILES['med_file']['tmp_name']= $files['med_file']['tmp_name'][$i];
$attachment_name=$files['med_file']['name'][$i];
$path_info=pathinfo($attachment_name);
$file_extension=#$path_info['extension'];
$path_part_filename=$path_info['filename'];
$rename_file=str_replace(" ","",$path_part_filename).'_'.date('Ymdhis');
if(!empty($rename_file))
{
$_FILES['med_file']['name'] = $rename_file.'.'.$file_extension;
$medical_history_files[]=$rename_file.'.'.$file_extension;
if($this->upload->do_upload('med_file'))
{
$file_upload='true';
}
else if(!$this->upload->do_upload('med_file'))
{
$file_upload="fail";
$error= $this->upload->display_errors();
$this->session->set_flashdata('sucess', $error);
}
}
}
}
}
}
and my view page code is like this.
<form method="post" name="medicalhistory" id="medicalhistory"
enctype="multipart/form-data">
<input id="med_file" type="file" name="med_file[]" multiple>
</form>
Please help me how to solve this problem. Thanks
You missed a couple of things here.. First of all, your HTML form should have the attribute action pointing to your controller method. Second, the $_FILES array should always contain the following: name, type, tmp_name, error, size, however, in your loop you are only rebuilding with name, type, tmp_name, and you are forgetting the others. You are also renaming the file prior its being sent to the upload library. You should do this by setting it in the config array that is being sent to the library. I would redo you code in the following manner:
Step 1: Make sure the HTML form has the action attribute:
<form action="<?= base_url()?>controller/upload" ..
Step 2: Retrieve the files and unset the original $_FILES so that you can rebuild the array:
$uploaded_files = $_FILES['med_file'];
unset($_FILES);
Step 3: loop through the obtained files and rebuild the $_FILES array into a multidimensional array:
foreach ($uploaded_files as $desc => $arr) {
foreach ($arr as $k => $string) {
$_FILES[$k][$desc] = $string;
}
}
Step 4: Load the Upload library, and set your config options
$this->load->library('upload');
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
Step 5: Loop through the new $_FILES array, rename you file and set the config['filename'] to the new name. Initialize your upload, then run it:
foreach ($_FILES as $k => $file) {
$path_info = pathinfo($file["name"]);
$file_extension = $path_info['extension'];
$path_part_filename = $path_info['filename'];
$config['file_name'] = str_replace(" ", "", $path_part_filename) . '_' . date('Ymdhis') . '.' . $file_extension;
$this->upload->initialize($config);
if (!$this->upload->do_upload($k)) {
$errors = $this->upload->display_errors();
var_dump($errors);
} else {
var_dump("success");
}
}
FINAL RESULT:
View:
<form action="<?= base_url()?>controller/upload" method="post" id="medicalhistory" enctype="multipart/form-data">
<input id="med_file" type="file" name="med_file[]" multiple>
<input type="submit">
</form>
Controller:
public function upload() {
$uploaded_files = $_FILES['med_file'];
unset($_FILES);
foreach ($uploaded_files as $desc => $arr) {
foreach ($arr as $k => $string) {
$_FILES[$k][$desc] = $string;
}
}
$this->load->library('upload');
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
foreach ($_FILES as $k => $file) {
$path_info = pathinfo($file["name"]);
$file_extension = $path_info['extension'];
$path_part_filename = $path_info['filename'];
$config['file_name'] = str_replace(" ", "", $path_part_filename) . '_' . date('Ymdhis') . '.' . $file_extension;
$this->upload->initialize($config);
if (!$this->upload->do_upload($k)) {
$errors = $this->upload->display_errors();
var_dump($errors);
} else {
var_dump("success");
}
}
}

CSV upload and change to php array for insert to db

So I am wanting to allow users to:
1. Upload a .csv file (mystudents.csv)
2. Import the rows in the .csv
3. Create a PHP array for all this
4. Insert this information into a database
I have the following code to upload the file and create the array.
public function studentImport()
{
ini_set('auto_detect_line_endings', TRUE);
$config['upload_path'] = './static/files/importFiles';
$config['allowed_types'] = '*';
$config['max_size'] = '800';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
var_dump($this->upload->display_errors());
}
else
{
$data = $this->upload->data();
$file_path = './static/files/importFiles/'.$data['file_name'];
$rows = array_map('str_getcsv', file($file_path));
if($rows){
$header = array_shift($rows);
$csv = array();
foreach($rows as $row) {
$csv[] = array_combine($header, $row);
}
var_dump($csv);
}
}
}
The file gets uploaded just fine, but the errors happens with the line: $rows = array_map('str_getcsv', file($file_path));
And that error is:
array_map() [function.array-map]: The first argument, 'str_getcsv', should be either NULL or a valid callback
What do I need to do to make this work out?
looks like the function str_getcsv is not available
Test it with
if (function_exists('str_getcsv')) {
print "str_getcsv defined\n";
} else {
print "str_getcsv not defined\n";
}
if function exists try
$csv= file_get_contents($file_path);
$array = str_getcsv($csv);
print json_encode($array);
or
$csv= file_get_contents($file_path);
$array = array_map('str_getcsv', explode("\n", $csv));
print json_encode($array);

Using CodeIgniters Upload class, trying to put select data in a new array for DB stor

am trying to use CodeIgners Upload class to get info from a successfully uploaded image (file_name, image_size_str). i want to put this select data into a new array so i can then store in a DB table. the code fails when using foreach to cycle thru the data, to try and put into a new array using array_push. I have to fail commented.
function do_upload(){
$dbImgInfoStore = array();
$this->load->model('upload_model');
$config['upload_path']='./uploads/';
$config['allowed_types']='gif|jpg|png';
$config['max_size']='10000'; //etc, etc
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$error = array('error'=>$this->upload->display_errors());
$this->load->view('upload_form',$error);
} else {
$data = array('upload_data'=>$this->upload->data());
// NOT WORKING EITHER!
foreach($data as $key=>$value) {
if($key == 'image_size_str') {
array_push($dbImgInfoStore, $dbImgInfoStore['image_size_str']=$value);
} elseif ($key == 'file_name') {
array_push($dbImgInfoStore, $dbImgInfoStore['file_name']=$value);
}
}
$this->load->view('upload_success', $data);
}
}
strangely, when sending to a new page
$this->load->view('upload_success', $data);
i'm able to do exactly what i'm trying to do a few lines earlier.
You need to access $data['upload_data'] in the foreach loop:
foreach($data['upload_data'] as $key => $value) {
if($key == 'image_size_str') {
$dbImgInfoStore['image_size_str'] = $value;
}
elseif ($key == 'file_name') {
$dbImgInfoStore['file_name'] = $value;
}
}

looping through multiple file upload indexes

I am trying to get the name and size index of all uploaded files but I can't get it work. it works like this:
foreach ($_FILES['file']['name'] as $key => $file){
echo $file;
}
but if I want to echo multiple indexes in the same loop, i tries this, but I get "undefined index 'name' and 'size'" warnings. What am I doing wrong? thanks
foreach ($_FILES['file'] as $key => $file){
echo $file['name'].
$file['size'];
}
<input name ="file[]" type = "file" multiple />
function handle_image_upload($frmFilesID = false, $thisFile = false) {
$tmpName = $_FILES["$frmFilesID"]['tmp_name'][$thisFile];
if (!is_uploaded_file($tmpName)) { return false; }
$fileName = $_FILES["$frmFilesID"]['name'][$thisFile];
$fileSize = $_FILES["$frmFilesID"]['size'][$thisFile];
$fileType = $_FILES["$frmFilesID"]['type'][$thisFile];
...

Categories