I need to upload multiple images via form. I thought that I will do it with no problem, but I have one.
When I try to do foreach and get image by image it is not acting like I hoped it will.
HTML
<form method="post" action="" enctype="multipart/form-data" id="frmImgUpload">
<input name="fileImage[]" type="file" multiple="true" />
<br />
<input name="btnSubmit" type="submit" value="Upload" />
</form>
PHP
<?php
if ($_POST)
{
echo "<pre>";
foreach ($_FILES['fileImage'] as $file)
{
print_r($file);
die(); // I want it to print first image content and then die to test this out...
//imgUpload($file) - I already have working function that uploads one image
}
}
What I expected from it to print out first image, instead it prints names of all the images.
Example
Array
(
[0] => 002.jpg
[1] => 003.jpg
[2] => 004.jpg
[3] => 005.jpg
)
What I want it to output
Array
(
[name] => 002.jpg
[type] => image/jpeg
[tmp_name] => php68A5.tmp
[error] => 0
[size] => 359227
)
So how can I select image by image in the loop so I can upload them all?
Okey I found solution and this is how I did it, probably not the best way but it works.
foreach ($_FILES['fileImage']['name'] as $f)
{
$file['name'] = $_FILES['fileImage']['name'][$i];
$file['type'] = $_FILES['fileImage']['type'][$i];
$file['tmp_name'] = $_FILES['fileImage']['tmp_name'][$i];
$file['error'] = $_FILES['fileImage']['error'][$i];
$file['size'] = $_FILES['fileImage']['size'][$i];
imgUpload($file);
$i++;
}
that array is formed in another way
it's something line this:
array (
'name' => array (
[0] => 'yourimagename',
[1] => 'yourimagename2',
....
),
'tmp_file' => array (
....
that shoud do it :
foreach ($_FILES['fileImage']['name'] as $file)
{
print_r($file);
die(); // I want it to print first image content and then die to test this out...
//imgUpload($file) - I already have working function that uploads one image
}
You are basically asking of how to rebuild the $_FILES array to access subitems of them as one array.
$index = 0;
$field = 'fileImage';
$keys = array_keys($_FILES[$field]);
$file = array();
foreach($keys as $key)
{
$file[$key] = $_FILES[$field][$key][$index];
}
print_r($file);
change $index to the value you need to pick a specific file.
Related
I am building a file upload tool for my website and am running into a strange issue. The html input is set up to accept image/png, image/jpg, image/jpeg, .pdf files and it works fine when I am using it to upload PDFs or images that came from a camera or a design software.
However, when I upload an image (png) that was a screenshot taken on my Mac, the $_FILES has a value for the name attribute, but has no values for the tmp_name, type, error, size attributes. I've tried renaming the file to see if that was the issue, and that doesn't appear to be the problem either.
This is the output I get when I run print_r($_FILES):
Array ( [fileupload] => Array ( [name] => Array ( [0] => Screen Shot 2020-12-23 at 2.10.06 PM.png ) [type] => Array ( [0] => ) [tmp_name] => Array ( [0] => ) [error] => Array ( [0] => 1 ) [size] => Array ( [0] => 0 ) ) )
Warning: mime_content_type(): Empty filename or path in pro_testupload.php on line 87
Warning: getimagesize(): Filename cannot be empty in pro_testupload.php on line 91
Warning: mime_content_type(): Empty filename or path in pro_testupload.php on line 103
Does anyone have any idea about what is going on here? Below is my code:
HTML Code
<form method="POST" action="_process/pro_testupload.php" enctype="multipart/form-data">
<input type="file" id="fileupload" name="fileupload[]" accept="image/png, image/jpg, image/jpeg, .pdf" multiple required>
<button class="btn waves-effect black waves-light" type="submit">Upload</button>
</form>
PHP Code
// -----------------------------------------------------------------
// FILE FORMAT CHECKING FUNCTIONS
// -----------------------------------------------------------------
function check_image($filename) {
// Check mime type using PHPs own built in functions (as client side mime type is vulnerable to exploitation)
$mime_type = mime_content_type($filename);
$allowed_file_types = ['image/png', 'image/jpeg', 'image/jpg'];
// Check the file is actually an image
$check = getimagesize($filename);
// Perform all checks
if (in_array($mime_type, $allowed_file_types) && is_array($check) !== False) {
return True;
} else {
return False;
}
}
function check_pdf($filename) {
// Check mime type using PHPs own built in functions (as client side mime type is vulnerable to exploitation)
$mime_type = mime_content_type($filename);
$allowed_file_types = ['application/pdf'];
// Perform checks
if (in_array($mime_type, $allowed_file_types)) {
return True;
} else {
return False;
}
}
// -----------------------------------------------------------------
// CHECK FILES TO ENSURE THEY MEET REQUIREMENTS
// -----------------------------------------------------------------
if(!empty(array_filter($_FILES['fileupload']['name']))) {
foreach ($_FILES['fileupload']['tmp_name'] as $key => $value) {
if (!(check_image($_FILES['fileupload']['tmp_name'][$key]) || check_pdf($_FILES['fileupload']['tmp_name'][$key]))) {
echo ("The files do not meet the uploaded file requirements");
exit;
}
}
} else {
echo ("There were no files requested to be uploaded.");
exit;
}
Got a script I've used several times, using move_uploaded_file. But what I can't figure out is why it do not respond in any way, no error reports, nothing.
<form> using method="post", target="upload" that is an <iframe>
action="file.php" responds to $_FILES
Correct enctype
Filerights is set to 777
Upload folder "uploads" exists
print_r($_FILES['file']) gives me:
Array
(
[name] => 1392930853.png
[type] => image/png
[tmp_name] => /tmp/php0rZdBf
[error] => 0
[size] => 611
)
The code below illustrates my script, and what I've figured out is that the last line with move_uploaded_file is the cause of my problem as it do not respond at all. As I wrote above, no error, no nothing.
Pastebin to script: http://pastebin.com/49m9Siqi
Got a clue what could be the cause of this?
$destination_path = getcwd().'/uploads/';
//echo $destination_path;
// File handling
$counted = count($_FILES['file']['name']);
$counted = $counted-1;
for ($i=0; $i<=$counted; $i++) {
if ($_FILES['file']['error'][$i] == UPLOAD_ERR_OK) {
$md5file = rand() . rand() . md5($_FILES['file']['name'][$i]) . rand() . rand();
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $destination_path . $md5file . "." . basename($_FILES['file']['type'][$i]))) { echo 'THIS WILL NOT BE ECHOED OUT ON THE PAGE'; }}}
There was a simple error in my form, as I handle my uploaded files like an array I need to create the array first.... Which I forgot to do in my form.
Wrong
<input type="file" name="file">
Correct
<input type="file" name="file[]">
I have the following situation:
I need to upload 3 files at once, when the user clicks to do so. There's the code I have in my view:
<?php echo form_open_multipart('uploads/do_upload', 'class="dropzone", id="dropzone-prod", data-nextFormExecDropzone="#dropzone-promo"');?>
<div class="fallback">
<input type="file" name="userfile" size="20" />
</div>
</form>
<?php echo form_open_multipart('uploads/do_upload', 'class="dropzone", id="dropzone-promo", data-nextFormExecDropzone="#dropzone-plan"');?>
<div class="fallback">
<input type="file" name="userfile" size="20" />
</div>
</form>
<?php echo form_open_multipart('uploads/do_upload', 'class="dropzone", id="dropzone-plan"');?>
<div class="fallback">
<input type="file" name="userfile" size="20" />
</div>
</form>
<div class="col-lg-4">
<button id="processQueue" class="btn btn-primary" type="button"><i class="fa fa-upload"></i>Start Upload</button>
</div>
When the user clicks in the button, I have a javascript code that sends each form the order I want it to.
In my controller, I have the following method (do_upload()):
function do_upload() {
//$filePath = $this->config->item('base_current_upload_url');
$filePath = APPPATH.'UPLOADS/';
$filePathAfterUploaded = $this->config->item('base_uploaded_url');
$config['upload_path'] = $filePath;
$config['allowed_types'] = '*';
$config['max_size'] = 1024 * 100;
$this->load->library('upload', $config);
//$this->load->library('csvreader');
//$filePathAfterUploaded = $this->config->item('base_uploaded_url');
//print_r($filePath); die();
$basefilepath = APPPATH.'UPLOADS/';
$this->load->model('uploads_m');
if ( ! $this->upload->do_upload('file')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else {
$data = array('upload_data' => $this->upload->data());
print_r($data); die();
}
}
PROBLEM:
I need the 3 files to be uploaded. If only one is missing I can't proceed.
This way I'm doing, the function do_upload is being called during the upload of each file, so I need to find a way to identify that the 3 files were uploaded. (After that, I'll use mysql 'load data infile' to load data from these files into some tables, but I can only do this if the three were uploaded.
Can you help me finding a way to handle this situation?
The structure of the $data everytime do_uplaod is called is this:
Array
(
[upload_data] => Array
(
[file_name] => PROMOWEB111120131.txt
[file_type] => text/plain
[file_path] => C:/Program Files/EasyPHP-DevServer-13.1VC9/data/localweb/projects/integration/www/application/UPLOADS/
[full_path] => C:/Program Files/EasyPHP-DevServer-13.1VC9/data/localweb/projects/integration/www/application/UPLOADS/PROMOWEB111120131.txt
[raw_name] => PROMOWEB111120131
[orig_name] => PROMOWEB11112013.txt
[client_name] => PROMOWEB11112013.txt
[file_ext] => .txt
[file_size] => 2.67
[is_image] =>
[image_width] =>
[image_height] =>
[image_type] =>
[image_size_str] =>
)
)
If do_upload is a standalone function, then introduce a static variable that counts the number of calls.
function do_upload () {
static $count = 0;
// The rest of your function goes here
if (no_errors_occurred) {
static::$count++;
}
if ($count == 3) {
// This function has been called 3 times; trigger something here
}
}
Better yet, if it's in a class...
class MyClass {
protected static $data = array ();
// Other functions and properties
public function do_upload () {
// The rest of your function
if (no_errors_occurred) {
static::$data[] = array (
'upload_data' => array (
'file_name' => ...,
// Populate the data array
)
);
}
$this->do_mysql_load_data_infile();
}
protected function do_mysql_load_data_infile () {
if (count(static::$data) != 3) {
return false;
}
// Do MySQL load data infile
// Get information about file uploads by accessing the static::$data array
foreach (static::$data as $file) {
echo $file['upload_data']['file_name'];
}
}
}
I'm trying parse a tab delemited text file into a set of PHP arrays, and help would be very much appreciated.
The .txt wil look like this (tab delimited not spaces)
data1a data1b data1c data1d
data2a data2b data2c data2d
data3a data3b data3c data3d
data4a data4b data4c data4d
and so on
I wish the PHP arrays to look like this
$arrayA = array('data1a', 'data2a', 'data3a', 'data4a');
$arrayB = array('data1b', 'data2b', 'data3b', 'data4b');
$arrayC = array('data1c', 'data2c', 'data3c', 'data4c');
$arrayD = array('data1d', 'data2d', 'data3d', 'data4d');
And I need the .txt file uploaded by a simple html form, e.g.
<form action="form.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
Any ideas on the code to place inside form.php?
Many thanks!
Consider the content of your text.txt file
FristLineFirstData FirstLineSecondData FirstLineThirdData
SecondLineFirstData SecondLineSecondData SecondLineThirdData
Tab separed.
And the script :
<?php
$file = "text.txt";// Your Temp Uploaded file
$handle = fopen($file, "r"); // Make all conditions to avoid errors
$read = file_get_contents($file); //read
$lines = explode("\n", $read);//get
$i= 0;//initialize
foreach($lines as $key => $value){
$cols[$i] = explode("\t", $value);
$i++;
}
echo "<pre>";
print_r($cols); //explore results
echo "</pre>";
?>
will return
Array
(
[0] => Array
(
[0] => FristLineFirstData
[1] => FirstLineSecondData
[2] => FirstLineThirdData
)
[1] => Array
(
[0] => SecondLineFirstData
[1] => SecondLineSecondData
[2] => SecondLineThirdData
)
)
Below is a barebone solution for your problem:
<?php
$error = false;
if (isset($_POST) && isset($_POST['submit']) && isset($_FILES) {)
$file = $_FILES['file'];
if (file_exists($_FILES['tmp_name'])){
$handle = fopen($_FILES['tmp_name']);
$data = fgetcsv($handle, 0, '\t');
}
// do your data processing here
// ...
// do your processing result display there
// ...
// or redirect to another page.
}
if ($error) {
// put some error message here if necessary
}
// form display below
?>
<!-- HTML FORM goes here --!>
<?
}
?>
The file data will be all grouped in the same array $data, indexed by the corresponding line number in the file.
See:
fgetcsv
$_FILES
on the PHP documentation website.
I have a multiple image upload form, and the following code is working well for uploading. I need to save file names to database to the database, but I cannot figure out how to do that properly.
uploadform.php:
echo form_open_multipart('gallery/upload');
<input type="file" name="photo" size="50" />
<input type="file" name="thumb" size="50" />
<input type="submit" value="Upload" />
</form>
gallery_model.php
function multiple_upload($upload_dir = 'uploads/', $config = array())
{
/* Upload */
$CI =& get_instance();
$files = array();
if(empty($config))
{
$config['upload_path'] = realpath($upload_dir);
$config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
$config['max_size'] = '2048';
}
$CI->load->library('upload', $config);
$errors = FALSE;
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if( ! $CI->upload->do_upload($key))
{
$data['upload_message'] = $CI->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
$CI->load->vars($data);
$errors = TRUE;
}
else
{
// Build a file array from all uploaded files
$files[] = $CI->upload->data();
}
}
}
// There was errors, we have to delete the uploaded files
if($errors)
{
foreach($files as $key => $file)
{
#unlink($file['full_path']);
}
}
elseif(empty($files) AND empty($data['upload_message']))
{
$CI->lang->load('upload');
$data['upload_message'] = ERR_OPEN.$CI->lang->line('upload_no_file_selected').ERR_CLOSE;
$CI->load->vars($data);
}
else
{
return $files;
}
/* -------------------------------
Insert to database */
// problem is here, i need file names to add db.
// if there is already same names file at the folder, it rename file itself. so in such case, I need renamed file name :/
}
}
You should keep your model for database operations only. All the upload processing and file moving has to be done in the controller. The model has to insert the record about the photo in the database and that's about it.
And as a response to your question do a print_r($files) and see what it contains. It should have the original filenames. It'll probably be something like artmania said above: $files[0]['file_name']. You should be able to loop through your $files array with a foreach construct like this:
foreach($files as $file) {
$file_name = $file['file_name'];
}
You can get all the other data about the file in the same way. The CodeIgniter manual says about $this->upload->data():
This is a helper function that returns
an array containing all of the data
related to the file you uploaded. Here
is the array prototype:
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
Fore more info check out the manual.