Undefined offset: 1 twitch channel grab - arrays

I get this on my website:
Notice: Undefined offset: 1 in ...
Here is the full code, bolded is the part it refers to i think, basically this scripts should grab list of my channels from ther DB and then display info from the twitch:
<?php
defined('_JEXEC') or die('Direct access to this location is not allowed.');
$userList = $params->get('userlist');
$usersArray = explode(',', $userList);
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($usersArray as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
//used to be $viewer = $json_array[$i]['stream_count'];
**foreach($usersArray as $i =>$value){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$name = $json_array[$i]['name'];
$game = $json_array[$i]['meta_game'];
$viewer = $json_array[$i]['channel_count'];
$topic = $json_array[$i]['title'];
onlinecheck($member, $viewer, $topic, $game);
$checkedOnline[] = signin($member);
}**
unset($value);
unset($i);
function onlinecheck($online, $viewers, $topic, $game)
{
if ($game == "Counter-Strike: Global Offensive")
{
$igra = "csgo12.jpg";
}
else{
$igra = "online.png";
}
if ($online != null)
{
echo ' <img src="./modules/mod_twitchlist/tmpl/'.$igra.'">';
echo ' <strong>'.$online.'</strong>';
echo ' (' .$viewers.') - ';
echo '<strong>'.$topic.'</strong> </br>';
}
}
function signin($person){
if($person != null){
return $person;
}
else{
return null;
}
}
?>
<!-- <hr> -->
<?php
foreach ($usersArray as $i => $value1) {
foreach($checkedOnline as $ii => $value2){
if($value1 == $value2){
unset($usersArray[$i]);
}
}
}
$broj1 = count($usersArray); //neaktivni korisnici
$broj2 = count($checkedOnline); //ukupno streamova
if ($broj1 == $broj2){
echo '<strong><center>Nijedan stream nije aktivan trenutno!</center></strong>';
}
?>
Any hints?

Related

"return" in foreach will only return one set of results, but echo returns all

I have no idea why it will return all the values I'm looking for with echo, but only 1 set with "return".
I removed all the code within the first foreach statement to see if there was some conflict between the foreach statements, but it returns with the same result.
I've tried some of the suggestions on here that I thought might be relevant, but without any luck.
What could I possibly be doing wrong?
function getInvoiceTimeLog($project_unique_id, $user_id, $user_timezone, $time_format)
{
global $db;
$query = "SELECT t.task_id, t.unique_id, t.name, t.description, t.sub_total, p.project_id, p.user_id FROM task as t, task_project as tp, project as p WHERE t.task_id = tp.task_id AND tp.project_id = p.project_id AND p.unique_id = ".$db->prep($project_unique_id)." AND p.user_id = ".$db->prep($user_id)." ORDER BY t.name";
$res = $db->query($query,'assoc');
if($res != false)
{
foreach($res as $row1):
$date = '';
$prevDate = '';
$return = '';
$query = "SELECT a.track_id FROM task_track a INNER JOIN track_time b ON a.track_id = b.track_id WHERE a.task_id =".$db->prep($row1['task_id'])." ORDER BY FROM_UNIXTIME(b.time_start,'%Y-%m-%d %H:%i:%s') DESC";
$resT = $db->query($query,'assoc');
$return .= '<div class="table" id="InvoicetimeLog"><div class="thead"><div class="th date">Date</div><div class="th start">Start</div><div class="th stop">Stop</div><div class="th hours">Hours</div></div><ul class="list">';
$return .= '<li>'.$row1['description'].'</li>';
if($resT != false)
{
foreach($resT as $row):
$track_id = $row['track_id'];
$query = "SELECT comment_id FROM track_comment WHERE track_id = ".$db->prep($track_id);
$resComLink = $db->query($query,'assoc');
if($resComLink != false)
{
$query = "SELECT comment,time_left FROM comment WHERE comment_id = ".$db->prep($resComLink[0]['comment_id']);
$resComment = $db->query($query,'assoc');
$comment_class = 'comment_has';
}
else
{
$comment = '';
$comment_class = 'comment';
}
$query = "SELECT time_start,time_end FROM track_time WHERE track_id = ".$db->prep($track_id);
$resTime = $db->query($query,'assoc');
$date = format_time($resTime[0]['time_start'],'m/d/y');
if($date != $prevDate)
{
$prevDate = format_time($resTime[0]['time_start'],'m/d/y');
$timeLog_ex = '<div class="date bold">'.$prevDate.'</div>';
$group = 'grp_shw';
}
else
{
$timeLog_ex = '<div class="date bold"></div>';
$group = 'grp_no';
}
if($time_format == 'g')
{
$the_time_format = 'g:i a';
}
else
{
$the_time_format = 'G:i';
}
if(empty($resTime[0]['time_end']))
{
$return .= '<li class="'.$group.'" id="rtrack_'.$track_id.'">'.$timeLog_ex.'<div class="start inlineEdit">'.date('m/d/y - '.$the_time_format,$resTime[0]['time_start']).'</div><div class="stop" title="The current time is at '.date($the_time_format,$db->nowUnix($user_timezone)).'">Current</div><div class="hours">'.getTimeDifference($resTime[0]['time_start'],$db->nowUnix($user_timezone)).'</div></li>';
}
else
{
$return .= '<li class="'.$group.'" id="rtrack_'.$track_id.'">'.$timeLog_ex.'<div class="start inlineEdit">'.date('m/d/y - '.$the_time_format,$resTime[0]['time_start']).'</div><div class="stop">'.date('m/d/y - '.$the_time_format,$resTime[0]['time_end']).'</div><div class="hours">'.getTimeDifference($resTime[0]['time_start'],$resTime[0]['time_end']).'</div></li>';
}
endforeach;
$return .= '<li class="grp_no"><div class="date bold">Total Time</div><div class="total">'.tot_time($unique_id,$user_id, $user_timezone).'</div></li>';
}
$return .= '</ul></div>';
endforeach;
}
return $return;
}
What a dope I am. It's simple....just move the variable declarations OUTSIDE of the foreach loop!
Move these guys to above the first foreach:
$date = '';
$prevDate = '';
$return = '';

How to insert fetch array properly

How could I insert a fetch array into this code. I don't get fetcharray.
$ctext = "SELECT tekst FROM members";
if (mysqli_query($conn, $ctext))
{
echo $ctext;
}
else
{
echo "erooroorror";
}
mysqli_close($conn);
$ctext = "SELECT tekst FROM members";
$result = mysqli_query($conn, $ctext);
if ($result) {
while($row = mysqli_fetch_array($result)) {
echo $row['tekst'] . '<br />';
}
} else {
echo "erooroorror";
}
you can insert it by performing batch operation. please check below code, hope it will help you to find the solution
$QueryToMember = mysql_query("SELECT tekst FROM members");
if ($QueryToMember) {
while ($row = mysql_fetch_array($QueryToMember)) {
$Array[] = "('" . $row['tekst'] . "')";
}
if (isset($Array) && count($Array) > 0) {
$InsertString = implode(',', $Array);
$Query = mysql_query("INSERT INTO test1 (tekst) VALUES " . $InsertString);
}
}
else {
echo "erooroorror";
}

Backup an entire website and database using PHP

I've been at this for a bit now and this is the closest I've gotten to backing up an entire site and database with PHP. The issue is I can't figure out why I continue to receive errors on lines 145 and 154.
Error:Notice: Undefined variable: arr_zip in C:\xampp\htdocs\wordpress\backup.php on line 145
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wordpress\backup.php on line 145
Notice: Undefined variable: delete_zip in C:\xampp\htdocs\wordpress\backup.php on line 154
<?php
ini_set ("max_execution_time", 0);
$dir = "site-backup-stark";
if(!(file_exists($dir)))
{
mkdir($dir, 0777);
}
$host = "localhost"; //host name
$username = "wordpress_user"; //username
$password = "pasword99"; // your password
$dbname = "wordpress_db"; // database name
$zip = new ZipArchive();
backup_tables($host, $username, $password, $dbname);
/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '*')
{
$con = mysql_connect($host,$user,$pass);
mysql_select_db($name,$con);
//get all of the tables
if($tables == '*')
{
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result))
{
$tables[] = $row[0];
}
}
else
{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
$return = "";
//cycle through
foreach($tables as $table)
{
$result = mysql_query('SELECT * FROM '.$table);
$num_fields = mysql_num_fields($result);
$return.= 'DROP TABLE '.$table.';';
$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
$return.= "nn".$row2[1].";nn";
while($row = mysql_fetch_row($result))
{
$return.= 'INSERT INTO '.$table.' VALUES(';
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = preg_replace("#n#","n",$row[$j]);
if (isset($row[$j]))
{
$return.= '"'.$row[$j].'"' ;
}
else
{
$return.= '""';
}
if ($j<($num_fields-1)) { $return.= ','; }
}
$return.= ");n";
}
$return.="nnn";
}
//save file
$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
fwrite($handle,$return);
fclose($handle);
}
if (glob("*.sql") != false)
{
$filecount = count(glob("*.sql"));
$arr_file = glob("*.sql");
for($j=0;$j<$filecount;$j++)
{
$res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
if ($res === TRUE)
{
$zip->addFile($arr_file[$j]);
$zip->close();
unlink($arr_file[$j]);
}
}
}
//get the current folder name-start
$path = dirname($_SERVER['PHP_SELF']);
$position = strrpos($path,'/') + 1;
$folder_name = substr($path,$position);
//get the current folder name-end
$zipname = date('Y/m/d');
$str = "stark-".$zipname.".zip";
$str = str_replace("/", "-", $str);
// open archive
if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE)
{
die ("Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../$folder_name/"));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value)
{
if( strstr(realpath($key), "stark") == FALSE)
{
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
if(glob("*.sql.zip") != false)
{
$filecount = count(glob("*.sql.zip"));
$arr_file = glob("*.sql.zip");
for($j=0;$j<$filecount;$j++)
{
unlink($arr_file[$j]);
}
}
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
{
if (strstr($value, "stark"))
{
$delete_zip[] = $value;
copy("$value", "$dir/$value");
}
}
for ($i=0; $i < count($delete_zip); $i++) //error here
{
unlink($delete_zip[$i]);
}
?>
In this block of code:
//get the array of zip files
if(glob("*.zip") != false)
{
$arr_zip = glob("*.zip");
}
//copy the backup zip file to site-backup-stark folder
foreach ($arr_zip as $key => $value) //error here
If your call to glob("*.zip") returns a 'falsey' value your variable $arr_zip won't be initialised and you'll get an error in the foreach that follows it. Check for false explicitly with
if(glob("*.zip") !== false)
If this continues to fail you need to investigate why glob() is failing. I don't have a suggestion for that.
Later, you haven't initialised $delete_zip at all, somewhere you need
$delete_zip = array();

Backupme - Connection Manager missing

I'm using this shell script below. I have it in app/console/command/BackupShell.php
When I run the script I get this error:
Fatal error: Class 'ConnectionManager' not found in app/Console/Command/BackupShell.php
What am I doing wrong?
class BackupShell extends Shell {
var $tasks = array('ProgressBar');
public function main() {
//database configuration, default is "default"
if(!isset($this->args[0])){
$this->args[0] = 'default';
}
//rows per query (less rows = less ram usage but more running time), default is 0 which means all rows
if(!isset($this->args[1])){
$this->args[1] = 0;
}
//directory to save your backup, it will be created automatically if not found., default is webroot/db-backups/yyyy-mm-dd
if(!isset($this->args[2])){
$this->args[2] = 'db-backups/'.date('Y-m-d',time());
}
App::import('Core', 'ConnectionManager');
$db = ConnectionManager::getDataSource($this->args[0]);
$backupdir = $this->args[2];
$seleced_tables = '*';
//$tables = array('orders', 'users', 'profiles');
if ($seleced_tables == '*') {
$sources = $db->query("show full tables where Table_Type = 'BASE TABLE'", false);
foreach($sources as $table){
$table = array_shift($table);
$tables[] = array_shift($table);
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$filename = 'db-backup-' . date('Y-m-d-H-i-s',time()) .'_' . (md5(implode(',', $tables))) . '.sql';
$return = '';
$limit = $this->args[1];
$start = 0;
if(!is_dir($backupdir)) {
$this->out(' ', 1);
$this->out('Will create "'.$backupdir.'" directory!', 2);
if(mkdir($backupdir,0755,true)){
$this->out('Directory created!', 2);
}else{
$this->out('Failed to create destination directory! Can not proceed with the backup!', 2);
die;
}
}
if ($this->__isDbConnected($this->args[0])) {
$this->out('---------------------------------------------------------------');
$this->out(' Starting Backup..');
$this->out('---------------------------------------------------------------');
foreach ($tables as $table) {
$this->out(" ",2);
$this->out($table);
$handle = fopen($backupdir.'/'.$filename, 'a+');
$return= 'DROP TABLE IF EXISTS `' . $table . '`;';
$row2 = $db->query('SHOW CREATE TABLE ' . $table.';');
//$this->out($row2);
$return.= "\n\n" . $row2[0][0]['Create Table'] . ";\n\n";
fwrite($handle, $return);
for(;;){
if($limit == 0){
$limitation = '';
}else{
$limitation = ' Limit '.$start.', '.$limit;
}
$result = $db->query('SELECT * FROM ' . $table.$limitation.';', false);
$num_fields = count($result);
$this->ProgressBar->start($num_fields);
if($num_fields == 0){
$start = 0;
break;
}
foreach ($result as $row) {
$this->ProgressBar->next();
$return2 = 'INSERT INTO ' . $table . ' VALUES(';
$j = 0;
foreach ($row[$table] as $key => $inner) {
$j++;
if(isset($inner)){
if ($inner == NULL){
$return2 .= 'NULL';
}else{
$inner = addslashes($inner);
$inner = ereg_replace("\n", "\\n", $inner);
$return2.= '"' . $inner . '"';
}
}else {
$return2.= '""';
}
if ($j < (count($row[$table]))) {
$return2.= ',';
}
}
$return2.= ");\n";
fwrite($handle, $return2);
}
$start+=$limit;
if($limit == 0){
break;
}
}
$return.="\n\n\n";
fclose($handle);
}
$this->out(" ",2);
$this->out('---------------------------------------------------------------');
$this->out(' Yay! Backup Completed!');
$this->out('---------------------------------------------------------------');
}else{
$this->out(' ', 2);
$this->out('Error! Can\'t connect to "'.$this->args[0].'" database!', 2);
}
}
function __isDbConnected($db = NULL) {
$datasource = ConnectionManager::getDataSource($db);
return $datasource->isConnected();
}
}
Is this 2.x code?
App::import('Core', 'ConnectionManager');
is deprecated/wrong in 2.x and should be
App::uses('ConnectionManager', 'Model');
and also be placed at the top of the file, right after the <?php tag

Multiple files upload (Array) with CodeIgniter 2.0

I've been searching and struggling for 3 days now to make this works but I just can't.
What I want to do is use a Multiple file input form and then upload them. I can't just use a fixed number of file to upload. I tried many many solutions on StackOverflow but I wasn't able to find a working one.
Here's my Upload controller
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url','html'));
}
function index()
{
$this->load->view('pages/uploadform', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload');
foreach($_FILES['userfile'] as $key => $value)
{
if( ! empty($key['name']))
{
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($key))
{
$error['error'] = $this->upload->display_errors();
$this->load->view('pages/uploadform', $error);
}
else
{
$data[$key] = array('upload_data' => $this->upload->data());
$this->load->view('pages/uploadsuccess', $data[$key]);
}
}
}
}
}
?>
My upload form is This.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" multiple name="userfile[]" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
I just keep having this error :
You did not select a file to upload.
Here's the array of the example:
Array ( [userfile] => Array ( [name] => Array ( [0] => youtube.png [1] => zergling.jpg ) [type] => Array ( [0] => image/png [1] => image/jpeg ) [tmp_name] => Array ( [0] => E:\wamp\tmp\php7AC2.tmp [1] => E:\wamp\tmp\php7AC3.tmp ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 35266 [1] => 186448 ) ) )
I have this like 5 times in a row if I select 2 files.
I also use the standard Upload library.
I finally managed to make it work with your help!
Here's my code:
function do_upload()
{
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
}
}
private function set_upload_options()
{
//upload an image options
$config = array();
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
Thank you guys!
You should use this library for multi upload in CI https://github.com/stvnthomas/CodeIgniter-Multi-Upload
Installation Simply copy the MY_Upload.php file to your applications library directory.
Use: function test_up in controller
public function test_up(){
if($this->input->post('submit')){
$path = './public/test_upload/';
$this->load->library('upload');
$this->upload->initialize(array(
"upload_path"=>$path,
"allowed_types"=>"*"
));
if($this->upload->do_multi_upload("myfile")){
echo '<pre>';
print_r($this->upload->get_multi_upload_data());
echo '</pre>';
}
}else{
$this->load->view('test/upload_view');
}
}
upload_view.php in applications/view/test folder
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" id="myfile" multiple>
<input type="submit" name="submit" id="submit" value="submit"/>
Try this code.
It's working fine for me
You must initialize each time the library
function do_upload()
{
foreach ($_FILES as $index => $value)
{
if ($value['name'] != '')
{
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
//upload the image
if ( ! $this->upload->do_upload($index))
{
$error['upload_error'] = $this->upload->display_errors("<span class='error'>", "</span>");
//load the view and the layout
$this->load->view('pages/uploadform', $error);
return FALSE;
}
else
{
$data[$key] = array('upload_data' => $this->upload->data());
$this->load->view('pages/uploadsuccess', $data[$key]);
}
}
}
}
private function set_upload_options()
{
//upload an image options
$config = array();
$config['upload_path'] = 'your upload path';
$config['allowed_types'] = 'gif|jpg|png';
return $config;
}
Further edit
I have found the way you must upload your files with one unique input box
CodeIgniter doesn't support multiple files. Using the do_upload() in a foreach won't be different than using it outside.
You will need to deal with it without the help of CodeIgniter. Here's an example https://github.com/woxxy/FoOlSlide/blob/master/application/controllers/admin/series.php#L331-370
https://stackoverflow.com/a/9846065/1171049
This is that said you in the commments :)
another bit of code here:
refer: https://github.com/stvnthomas/CodeIgniter-Multi-Upload
As Carlos Rincones suggested; don't be affraid of playing with superglobals.
$files = $_FILES;
for($i=0; $i<count($files['userfile']['name']); $i++)
{
$_FILES = array();
foreach( $files['userfile'] as $k=>$v )
{
$_FILES['userfile'][$k] = $v[$i];
}
$this->upload->do_upload('userfile')
}
All Posted files will be come in $_FILES variable, for use codeigniter upload library we need to give field_name that we are using in for upload (by default it will be 'userfile'), so we get all posted file and create another files array that create our own name for each files, and give this name to codeigniter library do_upload function.
if(!empty($_FILES)){
$j = 1;
foreach($_FILES as $filekey=>$fileattachments){
foreach($fileattachments as $key=>$val){
if(is_array($val)){
$i = 1;
foreach($val as $v){
$field_name = "multiple_".$filekey."_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}else{
$field_name = "single_".$filekey."_".$j;
$_FILES[$field_name] = $fileattachments;
$j++;
break;
}
}
// Unset the useless one
unset($_FILES[$filekey]);
}
foreach($_FILES as $field_name => $file){
if(isset($file['error']) && $file['error']==0){
$config['upload_path'] = [upload_path];
$config['allowed_types'] = [allowed_types];
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($field_name)){
$error = array('error' => $this->upload->display_errors());
echo "Error Message : ". $error['error'];
}else{
$data = $this->upload->data();
echo "Uploaded FileName : ".$data['file_name'];
// Code for insert into database
}
}
}
}
public function imageupload()
{
$count = count($_FILES['userfile']['size']);
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['image_library'] = 'gd2';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = FALSE;
$config['width'] = 50;
$config['height'] = 50;
foreach($_FILES as $key=>$value)
{
for($s=0; $s<=$count-1; $s++)
{
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$this->load->library('upload', $config);
if ($this->upload->do_upload('userfile'))
{
$data['userfile'][$i] = $this->upload->data();
$full_path = $data['userfile']['full_path'];
$config['source_image'] = $full_path;
$config['new_image'] = './uploads/resiezedImage';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$this->image_lib->clear();
}
else
{
$data['upload_errors'][$i] = $this->upload->display_errors();
}
}
}
}
I have used below code in my custom library
call that from my controller like below,
function __construct() {<br />
parent::__construct();<br />
$this->load->library('CommonMethods');<br />
}<br />
$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />
// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);
/**
* do_upload_multiple_files - Multiple Methods
* #param type $fieldName
* #param type $options
* #return type
*/
public function do_upload_multiple_files($fieldName, $options) {
$response = array();
$files = $_FILES;
$cpt = count($_FILES[$fieldName]['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
$_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
$_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
$_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
$_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];
$this->CI->load->library('upload');
$this->CI->upload->initialize($options);
//upload the image
if (!$this->CI->upload->do_upload($fieldName)) {
$response['erros'][] = $this->CI->upload->display_errors();
} else {
$response['result'][] = $this->CI->upload->data();
}
}
return $response;
}
<form method="post" action="<?php echo base_url('submit'); ?>" enctype="multipart/form-data">
<input type="file" name="userfile[]" id="userfile" multiple="" accept="image/*">
</form>
MODEL : FilesUpload
class FilesUpload extends CI_Model {
public function setFiles()
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach ($_FILES as $key => $value)
for ($s = 0; $s <= $count - 1; $s++) {
$_FILES['userfile']['name'] = $value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = 'assets/product/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000000';
$config['max_width'] = '51024';
$config['max_height'] = '5768';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$data_error = array('msg' => $this->upload->display_errors());
var_dump($data_error);
} else {
$data = $this->upload->data();
}
$name_array[] = $data['file_name'];
}
$names = implode(',', $name_array);
return $names;
}
}
CONTROLER submit
class Submit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('html', 'url'));
}
public function index()
{
$this->load->model('FilesUpload');
$data = $this->FilesUpload->setFiles();
echo '<pre>';
print_r($data);
}
}
// Change $_FILES to new vars and loop them
foreach($_FILES['files'] as $key=>$val)
{
$i = 1;
foreach($val as $v)
{
$field_name = "file_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}
// Unset the useless one ;)
unset($_FILES['files']);
// Put each errors and upload data to an array
$error = array();
$success = array();
// main action to upload each file
foreach($_FILES as $field_name => $file)
{
if ( ! $this->upload->do_upload($field_name))
{
echo ' failed ';
}else{
echo ' success ';
}
}
function imageUpload(){
if ($this->input->post('submitImg') && !empty($_FILES['files']['name'])) {
$filesCount = count($_FILES['files']['name']);
$userID = $this->session->userdata('userID');
$this->load->library('upload');
$config['upload_path'] = './userdp/';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '9184928';
$config['max_width'] = '5000';
$config['max_height'] = '5000';
$files = $_FILES;
$cpt = count($_FILES['files']['name']);
for($i = 0 ; $i < $cpt ; $i++){
$_FILES['files']['name']= $files['files']['name'][$i];
$_FILES['files']['type']= $files['files']['type'][$i];
$_FILES['files']['tmp_name']= $files['files']['tmp_name'][$i];
$_FILES['files']['error']= $files['files']['error'][$i];
$_FILES['files']['size']= $files['files']['size'][$i];
$imageName = 'image_'.$userID.'_'.rand().'.png';
$config['file_name'] = $imageName;
$this->upload->initialize($config);
if($this->upload->do_upload('files')){
$fileData = $this->upload->data(); //it return
$uploadData[$i]['picturePath'] = $fileData['file_name'];
}
}
if (!empty($uploadData)) {
$imgInsert = $this->insert_model->insertImg($uploadData);
$statusMsg = $imgInsert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
redirect('home/user_dash');
}
}
else{
redirect('home/user_dash');
}
}
There is no predefined method available in codeigniter to upload multiple file at one time but you can send file in array and upload them one by one
here is refer: Here is best option to upload multiple file in codeigniter 3.0.1 with preview https://codeaskbuzz.com/how-to-upload-multiple-file-in-codeigniter-framework/
SO what I change is I load upload library each time
$config = array();
$config['upload_path'] = $filePath;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$files = $_FILES;
$count = count($_FILES['nameUpload']['name']);
for($i=0; $i<$count; $i++)
{
$this->load->library('upload', $config);
$_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
$_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
$_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
$_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
$_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];
$this->upload->do_upload('nameUpload');
}
And it work for me.
For CodeIgniter 3
<form action="<?php echo base_url('index.php/TestingController/insertdata') ?>" method="POST"
enctype="multipart/form-data">
<div class="form-group">
<label for="">title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
<div class="form-group">
<label for="">File</label>
<input type="file" name="files" id="files" class="form-control">
</div>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
public function insertdatanew()
{
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES['filesdua']['name']);
for ($i = 0; $i < $cpt; $i++) {
$_FILES['filesdua']['name'] = $files['filesdua']['name'][$i];
$_FILES['filesdua']['type'] = $files['filesdua']['type'][$i];
$_FILES['filesdua']['tmp_name'] = $files['filesdua']['tmp_name'][$i];
$_FILES['filesdua']['error'] = $files['filesdua']['error'][$i];
$_FILES['filesdua']['size'] = $files['filesdua']['size'][$i];
// fungsi uploud
$config['upload_path'] = './uploads/testing/';
$config['allowed_types'] = '*';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('filesdua')) {
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// $this->load->view('welcome_message', $error);
} else {
// menambil nilai value yang di upload
$data = array('upload_data' => $this->upload->data());
$nilai = $data['upload_data'];
$filename = $nilai['file_name'];
var_dump($filename);
// $this->load->view('upload_success', $data);
}
}
// var_dump($cpt);
}
I recently work on it. Try this function:
/**
* #return array an array of your files uploaded.
*/
private function _upload_files($field='userfile'){
$files = array();
foreach( $_FILES[$field] as $key => $all )
foreach( $all as $i => $val )
$files[$i][$key] = $val;
$files_uploaded = array();
for ($i=0; $i < count($files); $i++) {
$_FILES[$field] = $files[$i];
if ($this->upload->do_upload($field))
$files_uploaded[$i] = $this->upload->data($files);
else
$files_uploaded[$i] = null;
}
return $files_uploaded;
}
in your case:
<input type="file" multiple name="images[]" size="20" />
or
<input type="file" name="images[]">
<input type="file" name="images[]">
<input type="file" name="images[]">
in the controller:
public function do_upload(){
$config['upload_path'] = './Images/';
$config['allowed_types'] = 'gif|jpg|png';
//...
$this->load->library('upload',$config);
if ($_FILES['images']) {
$images= $this->_upload_files('images');
print_r($images);
}
}
Some basic reference from PHP manual: PHP file upload
Save, then redefine the variable $_FILES to whatever you need.
maybe not the best solution, but this worked for me.
function do_upload()
{
$this->load->library('upload');
$this->upload->initialize($this->set_upload_options());
$quantFiles = count($_FILES['userfile']['name']);
for($i = 0; $i < $quantFiles ; $i++)
{
$arquivo[$i] = array
(
'userfile' => array
(
'name' => $_FILES['userfile']['name'][$i],
'type' => $_FILES['userfile']['type'][$i],
'tmp_name' => $_FILES['userfile']['tmp_name'][$i],
'error' => $_FILES['userfile']['error'][$i],
'size' => $_FILES['userfile']['size'][$i]
)
);
}
for($i = 0; $i < $quantFiles ; $i++)
{
$_FILES = '';
$_FILES = $arquivo[$i];
if ( ! $this->upload->do_upload())
{
$error[$i] = array('error' => $this->upload->display_errors());
return FALSE;
}
else
{
$data[$i] = array('upload_data' => $this->upload->data());
var_dump($this->upload->data());
}
}
if(isset($error))
{
$this->index($error);
}
else
{
$this->index($data);
}
}
the separate function to establish the config..
private function set_upload_options()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'xml|pdf';
$config['max_size'] = '10000';
return $config;
}

Resources