I've been struggling with this for a while now and hoping someone can point me in the right direction. I have a script that works for uploading a single image. I'm now trying to amed it so that I can update more than 1 file at once. 2 in the example below. I understand that name needs to be an array and I loop through them however I only seem to be encountering errors. I've read and tried various different things.
I either was able to upload one file but not the second, upload no files or a blank white screen.
Below is what I'm currently working with after having various edits.
<?php
$upload_dir= 'training/trainingDocuments';
$numUploads = 2;
$msg = 'Please select files for uploading';
$errors = array();
if(isset($_FILES['myTrainingFile']['tmp_name']))
{
for($i=0; $i < count($_FILES['myTrainingFile']['tmp_name']);$i++)
{
$fileName = $_FILES['myTrainingFile']['name'][$i];
$tempName = $_FILES['myTrainingFile']['tmp_name'][$i];
$blacklist = array('exe','php','jsp','js','bat','asp','aspx','com','dmg');
$a = explode('.', $fileName);
$fileExt = strtolower(end($a)); unset($a);
$fileSize = $_FILES['myTrainingFile']['size'];
if(in_array($fileExt, $blacklist) === true){
$errors[] = "File type not allowed";
}
//$newPath = $general->fileNewPath($path, $fileName);
$newPath = "training/trainingDocuments/" . $_FILES['myTrainingFile']['name'][$i];
$moveFileResult = move_uploaded_file($tempName, $newPath);
if($moveFileResult != true){
$errors[] = 'Upload Failed - MOVE';
}
$comments = htmlentities(trim($_POST['comments']));
$category = htmlentities(trim($_POST['category']));
//insert into db
$training->uploadDocument($fileName, $category, $comments);
if(!is_uploaded_file($_FILES['myTrainingFile']['name'][$i]))
{
$errors[] = 'Uploading '.$_FILES['myTrainingFile']['name'][$i] . 'failed -.-';
}
}
}
?>
Thanks for any help!
Try this code, i added a function named convert_files, so you can handle your uploads in a better way
Code:
<?php
$upload_dir = "training/trainingDocuments";
$numUploads = 2;
$msg = "Please select file(s) for uploading";
$errors = array();
// how many files you want to upload
$maxFiles = 3;
if ( $files = convert_files( $_FILES["myTrainingFile"] ) ) {
foreach( $files as $i => $file ) {
$fileName = $file["name"];
$tempName = $file["tmp_name"];
$fileSize = $file["size"];
// get file extension, and do strtolower
$fileExt = strtolower( pathinfo( $fileName, PATHINFO_EXTENSION ) );
// invalid file types
$blacklist = array( 'exe','php','jsp','js','bat','asp','aspx','com','dmg' );
// new path to upload current file
$newPath = "training/trainingDocuments/".$fileName;
// Check whether its a valid file or invalid file
if ( in_array( $fileExt, $blacklist ) ) {
// invalid file type, add error
$errors[$i] = "File type not allowed";
}
if ( !is_uploaded_file( $tempName ) ) {
// its'' not an uploaded file, add error
$errors[$i] = "Uploading ".$fileName." failed -.-";
}
if ( file_exists( $newPath ) ) {
// file already exists in your directory, add error
$errors[$i] = "File ".$fileName." already exists";
// if you dont want to add error, (adding an error will not upload file)
// just comment above line, and uncomment below line
/*
// get the filename without extension
$name = pathinfo( $fileName, PATHINFO_FILENAME );
//create new file name
$fileName = $name."_".uniqid().".".$fileExt;
//update upload path
$newPath = "training/trainingDocuments/".$fileName;
*/
}
// make sure $errors[$i] contains any errors
if ( isset( $errors[$i] ) ) {
// errors occured, so continue to next file
continue;
}
if ( !move_uploaded_file( $tempName, $newPath ) ) {
$errors[$i] = "Upload Failed - MOVE"; // failed to move file
}
$comments = htmlentities( trim( $_POST['comments'] ) );
$category = htmlentities( trim( $_POST['category'] ) );
// Upload document
$training->uploadDocument( $fileName, $category, $comments );
// check maximum allowed files limit exceeded
if ( ( $i + 1 ) == $maxFiles ) {
// limit exceeded, break the execution
break;
}
}
}
?>
Function:
<?php
function convert_files( $files ) {
if ( is_array( $files ) && !empty( $files["name"] ) ) {
if ( is_array( $files["name"] ) ) {
$merged = array();
foreach( $files["name"] as $i => $name ) {
$merged[] = array(
"name" => $name,
"type" => $files["type"][$i],
"size" => $files["size"][$i],
"error" => $files["error"][$i],
"tmp_name" => $files["tmp_name"][$i]
);
}
return $merged;
}
return array( $files );
}
return false;
}
?>
Related
I want to upload multiple image using PDO in one row with comma separation, however I can only able to insert one image to database but in the upload directory all selected files are moved. How to do it?
<?php
for($x=0; $x<count($_FILES['pic']['tmp_name']); $x++ ) {
$file_name = $_FILES['pic']['name'][$x];
$file_size = $_FILES['pic']['size'][$x];
$file_tmp = $_FILES['pic']['tmp_name'][$x];
$t = explode(".", $file_name);
$t1 = end($t);
$file_ext = strtolower(end($t));
$ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");
if(in_array($file_ext, $ext_boleh)) {
$dir = 'uploads/';
$sumber = $file_tmp;
move_uploaded_file($sumber, $dir.$file_name);
$sql2 = "UPDATE project_detail SET pic = :pic WHERE no = '$no'";
$statement1 = $connection->prepare($sql2);
if ($statement1->execute([':pic' => $file_name])){ ?>
<script>
alert("new record uploded successfully");
window.location.href=('project.php');
</script>
<?php }
}else {
echo "Only Images can be store!";
}
}
?>
If I've understood correctly ( though I'm still confused by the update satement rather than an insert statement ) then a little re-writing to perform all the upload actions before trying to write to the db should work.
<?php
$images=[];
for( $x=0; $x < count( $_FILES['pic']['tmp_name'] ); $x++ ) {
$file_name = $_FILES['pic']['name'][$x];
$file_size = $_FILES['pic']['size'][$x];
$file_tmp = $_FILES['pic']['tmp_name'][$x];
/* Less complicated and more reliable method to find the file extension!! */
$file_ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
$ext_boleh = array( 'jpg', 'jpeg', 'png', 'gif', 'bmp' );
if( in_array( $file_ext, $ext_boleh ) ) {
$dir = 'uploads/';
$status = move_uploaded_file( $file_tmp, $dir . $file_name );
/*
if the file was moved OK then add it's name
to the images array - this will be used in
the sql later...
*/
if( $status )$images[]=$file_name;
}
}
/*
Where does `$no` come from?
Construct update ( or insert? ) sql statement
making sure we do not leave potential injection
possibilities....!
*/
$sql2 = 'UPDATE `project_detail` SET `pic` = :pic WHERE `no` = :no';
$statement1 = $connection->prepare( $sql2 );
/* Concatenate the image names into a comma separated string */
$args = array(
':pic' => implode(',', $images ),
':no' => $no
);
$result = $statement1->execute( $args );
if( $result ){
/* do a happy dance */
} else {
/* weep */
}
?>
I'm having trouble figuring out why it is that when an image size is too big, I get the error 'Invalid File Type' 'Uploaded file is not an image' instead of getting 'File is too big' (The image validation/upload script I didn't completely write myself- I found the code and made it work with for my needs). Everything else seems to work fine except for this. Also I get the following warning
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\minnow\includes\create-post.php on line 75
Here is my code
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
$imageError = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if ( !getimagesize($_FILES[$image]['tmp_name']) ) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
$data = "<article class='post'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''><div class='post-body'><div class='post-options'><a class='likes' href=''>156 likes</a></div><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}else{
$data = "<article class='post no-img'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><div class='post-body'><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><div class='post-options'><a class='likes' href=''>1 like</a></div><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
}else{
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
}
die();
It could be that the file was just not uploaded to the server.
Check $_FILES[$image]['error'] to see what may have gone wrong.
Refer to the error messages here.
Edit: After these lines:
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
Do this:
// check for error greater than zero
if($_FILES[$image]['error'] > 0) {
// something went wrong with the upload, handle the error
echo $_FILES[$image]['error']; exit; // as an example to find out what the error was
}
Then refer to http://php.net/manual/en/features.file-upload.errors.php to find out the reason.
I'm trying to create a new folder within the upload folder so that a user can upload file to there own folder.
Can I do this using PHP or do I need to a column "LONGBLOB" in MYSQL?
I've read that it's not good practice to store images in you database
<?php
header('Content-Type: application/json');
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
if(!empty($_FILES["file"])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
}else{
$failed[] = array(
'name' => $name);
}
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
}
?>
Assuming you have the user's username or id in a session variable then that could be used as the basis for the new folder into which he/she would upload files.
Obiously that same username,id would have to be used when they wish to download the file. By storing a hash and the filepath you can generate links that do not reveal filename, folder path, owner etc as the db could check the ash and return the file and path when needed.
The following is an untested example of generating the user's own folder and using that in the upload process - hope it gives you some ideas / guidance.
<?php
$succeeded = [];
$failed =[];
$uploaded = [];
$allowed = ['png', 'gif', 'jpg'];
/*
generate a suitable name for the new folder,
remove characters which might be troublesome
*/
$userdir = str_replace(
array("'",'"','-'),
array('','','_'),
$_SESSION['username']
);
/*
new path into which the files are saved
It might be better to have the files
stored outside of the document root.
*/
$savepath = 'uploads/' . $userdir;
/* create the folder if it does not exist */
if( !file_exists( $savepath ) ) {
mkdir( $savepath );
chown( $savepath, $username );
chmod( $savepath, 0644 );
}
if( !empty( $_FILES["file"] ) ) {
foreach( $_FILES['file']['name'] as $key => $name ) {
if( $_FILES['file']['error'][$key] === 0 ) {
$temp = $_FILES['file']['tmp_name'][$key];
/*
is there anything to be gained by hashing the filename?
the hash would be the same for filenames with the same
name anyway.
If the file is large, calculating the hash of the file could
take some time...
*/
$ext = explode('.', $name);
$ext = strtolower( end( $ext ) );
$file = md5_file( $temp ) . time() . '.' . $ext;
/* generate a random hash to use in downloads */
$hash=uniqid( md5( date(DATE_COOKIE) ) );
/* here probably - store reference in db? Assign permissions based upon owner etc */
$sql='insert into `table` (`filename`,`username`,`uid`,`datetime`,`hash`) values (?,?,?,?,?);';
/* bind params and execute - not shown */
if ( in_array( $ext, $allowed ) === true && move_uploaded_file( $temp, "{$savepath}/{$file}") === true ) {
$succeeded[] = array( 'name' => $name, 'file' => $file );
}else{
$failed[] = array( 'name' => $name );
}
}
}
}
if (!empty($_POST['ajax'])) {
header('Content-Type: application/json');
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed ));
} else {
header( 'HTTP/1.1 404 Not Found', true, 404 );
}
?>
i am using the code bellow to upload images to my wp directory.
I tried to modified the code so i can download images directly from the url but i didnt have any luck.
My code is bellow:
<?php
class imgUploader
{
var $exts = array( ".png", ".gif", ".png", ".jpg", ".jpeg" ); //all the extensions that will be allowed to be uploaded
var $maxSize = 9999999; //if you set to "0" (no quotes), there will be no limit
var $uploadTarget = "../wp-content/uploads/"; //make sure you have the '/' at the end
var $fileName = ""; //this will be automatically set. you do not need to worry about this
var $tmpName = ""; //this will be automatically set. you do not need to worry about this
public function startUpload()
{
$this->fileName = $_FILES['uploaded']['name'];
$this->tmpName = $_FILES['uploaded']['tmp_name'];
if( !$this->isWritable() )
{
die( "Sorry, you must CHMOD your upload target to 777!" );
}
if( !$this->checkExt() )
{
die( "Sorry, you can not upload this filetype!" );
}
if( !$this->checkSize() )
{
die( "Sorry, the file you have attempted to upload is too large!" );
}
if( $this->fileExists() )
{
die( "Sorry, this file already exists on our servers!" );
}
if( $this->uploadIt() )
{
echo "Your file has been uploaded!<br><br>Click here to view your file!";
}
else
{
echo "Sorry, your file could not be uploaded for some unknown reason!";
}
}
public function uploadIt()
{
return ( move_uploaded_file( $this->tmpName, $this->uploadTarget . time() . $this->fileName ) ? true : false );
}
public function checkSize()
{
return ( ( filesize( $this->tmpName ) > $this->maxSize ) ? false : true );
}
public function getExt()
{
return strtolower( substr( $this->fileName, strpos( $this->fileName, "." ), strlen( $this->fileName ) - 1 ) );
}
public function checkExt()
{
return ( in_array( $this->getExt(), $this->exts ) ? true : false );
}
public function isWritable()
{
return ( is_writable( $this->uploadTarget ) );
}
public function fileExists()
{
return ( file_exists( $this->uploadTarget . time() . $this->fileName ) );
}
}
$img = new imgUploader();
if( $_POST['upload_file'] )
{
$img->startUpload();
}
else
{
echo "<form method=\"post\" enctype=\"multipart/form-data\">
<p>
<label for=\"file\">Select a file to upload:</label> <input type=\"file\" name=\"uploaded\" id=\"file\"><br>
<input type=\"submit\" name=\"upload_file\" value=\"Upload!\">
<p>
</form>";
}
?>
I tried to remove the hole form and give to $filename and $temp name the image url but it doesnt work..
any idea?
How do I solve this error?
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: admin/tour.php
Line Number: 81
this is line 81:
$files = $this->multi_upload->go_upload();
var_dump($files);
$images = array();
foreach ($files as $img) { //line 81
$images[] = $img['file'];
}
this my $files in top code:
function go_upload($field = 'userfile') {
$CI =& get_instance();
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]['name'][0]))
{
$CI->upload->set_error('upload_no_file_selected');
return FALSE;
} else
{
$num_files = count($_FILES[$field]['name']) -1;
$file_list = array();
$error_hold = array();
$error_upload = FALSE;
}
// Is the upload path valid?
if ( ! $CI->upload->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
for ($i=0; $i < $num_files; $i++) {
// $fname = $_FILES[$field]['name'][$i];
// echo "$fname\n\n<br><br>\n\n";
$error_hold[$i] = FALSE;
// Was the file able to be uploaded? If not, determine the reason why.
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
{
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
switch($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$error_hold[$i] = 'upload_file_exceeds_limit';
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$error_hold[$i] = 'upload_file_exceeds_form_limit';
break;
case 3: // UPLOAD_ERR_PARTIAL
$error_hold[$i] = 'upload_file_partial';
break;
case 4: // UPLOAD_ERR_NO_FILE
$error_hold[$i] = 'upload_no_file_selected';
break;
case 6: // UPLOAD_ERR_NO_TMP_DIR
$error_hold[$i] = 'upload_no_temp_directory';
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$error_hold[$i] = 'upload_unable_to_write_file';
break;
case 8: // UPLOAD_ERR_EXTENSION
$error_hold[$i] = 'upload_stopped_by_extension';
break;
default :
$error_hold[$i] = 'upload_no_file_selected';
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$CI->upload->file_temp = $_FILES[$field]['tmp_name'][$i];
$CI->upload->file_name = $_FILES[$field]['name'][$i];
$CI->upload->file_size = $_FILES[$field]['size'][$i];
$CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$i]);
$CI->upload->file_type = strtolower($CI->upload->file_type);
$CI->upload->file_ext = $CI->upload->get_extension($_FILES[$field]['name'][$i]);
// Convert the file size to kilobytes
if ($CI->upload->file_size > 0)
{
$CI->upload->file_size = round($CI->upload->file_size/1024, 2);
}
// Is the file type allowed to be uploaded?
if ( ! $CI->upload->is_allowed_filetype())
{
$error_hold[$i] = 'upload_invalid_filetype';
}
// Is the file size within the allowed maximum?
if ( ! $CI->upload->is_allowed_filesize())
{
$error_hold[$i] = 'upload_invalid_filesize';
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $CI->upload->is_allowed_dimensions())
{
$error_hold[$i] = 'upload_invalid_dimensions';
}
// Sanitize the file name for security
$CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);
// Remove white spaces in the name
if ($CI->upload->remove_spaces == TRUE)
{
$CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$CI->upload->orig_name = $CI->upload->file_name;
if ($CI->upload->overwrite == FALSE)
{
$CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
if ($CI->upload->file_name === FALSE)
{
$error_hold[$i] = TRUE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! #copy($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
if ( ! #move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
$error_hold[$i] = 'upload_destination_error';
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($CI->upload->xss_clean == TRUE)
{
$CI->upload->do_xss_clean();
}
if ($error_hold[$i]) {
$error_upload = TRUE;
// echo $error_hold[$i];
} else {
if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'ext' => $CI->upload->file_ext,
'image_type' => $imageVar->image_type,
'height' => $imageVar->height,
'width' => $imageVar->width
);
} else {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'type' => $CI->upload->file_type,
'ext' => $CI->upload->file_ext,
);
}
}
// For debugging
/*
if (strlen($error_hold[$i]) > 1) {
print_r($error_hold);
}
*/
} // end for loop
// Add error display for individual files
if ($error_upload) {
$this->set_error($error_hold);
return FALSE;
} else {
return $file_list;
}
}
The simple answer is that $files is not an array. foreach only works on arrays. We don't know what the value is, but in any case, it's not right. You'd have to look at the go_upload function to see why it's not doing what you expect.
Actually doing like this you wil get the file or the value you want to.
foreach ($files as $img) { //line 81
echo $img; // echo the Var and you will see..
}
This line -> $files = $this->multi_upload->go_upload(); probably come from a file object in your form, right? Then it must to be named like this file[] and not only file. You need to be specific that it is an Array. Otherwise nothing will happen.
Too avoid seeing this warning message you should count the array:
if (count($files) > 0)
{
foreach ($files as $img) { //line 81
$images[] = $img['file'];
}
}
Regarding the 'Invalid argument supplied for foreach()' error this is probably because $files is not an array (or similar). The best way to do this IMHO is:
$files = $this->multi_upload->go_upload();
echo '<pre>';
echo "Files:\n";
print_r($files);
echo '</pre>';
$images = array();
foreach ($files as $img) { //this is line 80
$images[] = $img['file'];
}
if ( ! $files )
{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/tour/insert_foreign');
}
Please make this change and show us the output.
I figure I would just share how I handle multiple uploads in CI, it's a little different than your method:
Form looks like this:
<?php echo form_open_multipart('upload/multiple_upload');?>
<input type="file" name="userfile[]" size="20" /><br />
<input type="file" name="userfile[]" size="20" /><br />
</form>
Upload/multiple_upload function in controller looks like this:
function multiple_upload()
{
$config['upload_path'] = './userpics/originals/'; // server directory
$config['allowed_types'] = 'gif|jpg|png'; // by extension, will check for whether it is an image
$config['max_size'] = '512'; // in kb
//$config['max_width'] = '1024';
//$config['max_height'] = '768';
$this->load->library('myupload');
$error = array(); $data = array();
for ($i=0;$i<count($_FILES['userfile']['name']);$i++) {
$this->myupload->initialize($config);
if (!$this->myupload->do_upload('userfile',$i)) {
$error[] = $this->myupload->display_errors();
}
$data[$i] = $this->myupload->data(); //gradually build up upload->data()
}
if ( count($error) > 0 )
{
print_r($error);
}
else
{
print_r($data);
}
}
At this point I made a copy of CI upload class, and pasted it into my applications library directory. A few changes need to be made. I named it myupload.
# Line 143:
public function do_upload($field = 'userfile')
change to
public function do_upload($field = 'userfile', $i = 0)
Any lines in this function above line 200, you must add [$i] to the end of the $_FILES variables.
Example:
is_uploaded_file($_FILES[$field]['tmp_name'])
change to:
is_uploaded_file($_FILES[$field]['tmp_name'][$i])
There are 9 lines to be updated.
Are you sure that you get an array? is see several return FALSE. So you should check,
if ($files !== FALSE)
or casting it to an (empty) array (if false returns) with
$files = (array) $this->multi_upload->go_upload();