I'm trying to upload multiple image to the server and to make different resolution version of each image.
To do this I'm using class.upload.php for the first time. http://www.verot.net/php_class_upload.htm
I look at the documentation and starting from the demo example http://www.verot.net/php_class_upload_download_zip.htm
I made a form with multiple input
<form name="form3" enctype="multipart/form-data" method="post" action="upload.php">
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p class="button"><input type="hidden" name="action" value="multiple" />
<input type="submit" name="Submit" value="upload" /></p>
</form>
the original php from the example only upload the image without resizing them:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
// now we can loop through $files, and feed each element to the class
foreach ($files as $file) {
// we instanciate the class for each element of $file
$handle = new Upload($file);
// then we check if the file has been uploaded properly
// in its *temporary* location in the server (often, it is /tmp)
if ($handle->uploaded) {
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
echo 'ok';
} else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
} else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
echo ' Error: ' . $handle->error . '';
}
}
What I'd like to do is to process each file inside the if ($handle->processed) {}
so I took the function form the example that resize img and paste it inside the if ($handle->processed) {} part. Now it look like this:
if ($handle->uploaded) {
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
// now, we start a serie of processes, with different parameters
// we use a little function TestProcess() to avoid repeting the same code too many times
function TestProcess(&$handle, $title) {
global $dir_pics, $dir_dest;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
echo 'ok';
} else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
}
if (!file_exists($dir_dest)) mkdir($dir_dest);
// ----------- save the uploaded img adding _xl to the name
$handle->file_name_body_add = '_xl';
$handle->file_overwrite = true;
TestProcess($handle, 'File originale', '');
// ----------- save the uploaded img adding _l to the name and downsizing it
$handle->file_name_body_add = '_l';
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 1024;
$handle->file_overwrite = true;
TestProcess($handle, 'Ridimensionato a 1024px');
}
At this point the script works fine only with the first img.
it not make the "foreach ($files as $file)" trow the $files array...
could you help my find where the error is?
thaks
Daniele
Creator of the class here... You need to change the $files array first, as following. It is in the FAQ:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
Okay, so i tried to use verot's answer but i got ALOT of errors, i tried other answers around the web.
Here is the working solution.
$placeDir = $_SERVER['DOCUMENT_ROOT'] . '/myuploadfolder';
$files = [];
foreach ($_FILES['image_field']['name'] as $key => $value) {
if(!empty($_FILES['image_field']['name'][$key])){
$name = $_FILES['image_field']['name'][$key];
$type = $_FILES['image_field']['type'][$key];
$tmp = $_FILES['image_field']['tmp_name'][$key];
$error = $_FILES['image_field']['error'][$key];
$size = $_FILES['image_field']['size'][$key];
$files[] = [
'name' => $name
, 'type' => $type
, 'tmp_name' => $tmp
, 'error' => $error
, 'size' => $size
];
}
}
foreach($files as $file){
$image = new uploadHelper($file);
$image->allowed = array('image/*');
if ($image->uploaded) {
$image->process($placeDir);
if ($image->processed) {
echo 'image done';
$image->clean();
} else {
echo 'error : ' . $image->error;
}
} else {
echo '<h1>IMAGE NOT UPLOADED</H1>';
}
}
I really hope this helps people out there.
Related
controller:
public function student()
{
if($this->input->post('save'))
{
$client_id[0]['client_id'] = $this->session->userdata('client_id');
$radio = $this->input->post('class');
$client = $client_id[0]['client_id'];
$filename = $_FILES['students_list']['name'];
$path = base_url()."resources/imported_file/".$filename;
$path = FCPATH."resources/imported_file/";
$move=move_uploaded_file($_FILES['students_list']['tmp_name'],$path.$_FILES['students_list']['name']);
if($_FILES["students_list"]["size"] > 0)
{
$file = fopen($path, "r");
while (($importdata = fgetcsv($file, 10000, ",")) !== FALSE)
{
$data = array(
'name' => $importdata[0],
'email' =>$importdata[1],
'phone' =>$importdata[2],
'uploaded_date' => date('d-m-y'),
'session' => date('Y'),
'client_id' => $client[0]['client_id'],
'class' => $radio
);
$this->partner_model->insertCSV($data);
echo $this->db->last_query();
}
fclose($file);
$this->session->set_flashdata('err_csv', '<p style="color: #87b87f;font-weight: bold;text-align:center;">Data are imported successfully..</p>');
}
else
{
$this->session->set_flashdata('err_csv', '<p style="color: red;font-weight: bold;text-align:center;">Something went wrong..</p>');
}
}
}
view:
<?php echo $this->session->flashdata('err_csv')?>
<form class="form-horizontal" method="post" role="form" enctype="multipart/form-data">
<input type="radio" name="class" value="11th"/><b>XI</b>
<input type="radio" name="class" value="12th Appearing"/><b>XII Appearing</b>
<input type="radio" name="class" value="12th Passed"/><b>XII Passed</b>
<input type="file" id="students_list" name="students_list" accept=".csv" class="required">
<input type="submit" name="save" id="save" value="save" class="btn btn-info" />
</form>
model:
<?php
class Partner_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public function insertCSV($data)
{
$this->db->insert('students', $data);
return TRUE;
}
}
In this code I have an input having name student_list where I am uploading only csv file. Now, I want to import data from csv file into database but right now it can't work. So, How can I do this ? Please help me.
Thank You
Unless you have some compelling reason to perform the import in code, I suggest you look at Pentaho (https://sourceforge.net/projects/pentaho/), which can upload data from a csv file to most popular databases.
Hey you need to add the library csvReader in your project and use the below code to setup this helps you lot
public function student(){
$this->load->library('CSVReader');
if (isset($_FILES['csv']))
{
if($_FILES["csv"]["error"] > 0)
{ //if there was an error uploading the file
$this->session->set_flashdata('bulkUploadError', 'Invalid CSV File.');
redirect('/');
}
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "csv" . date('m-d-Y') . ".xls";
move_uploaded_file($_FILES["csv"]["tmp_name"], realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename);
if ($file = fopen(realpath(dirname(__FILE__) . '/../../..') . "/uploads/" . $storagename, 'r+'))
{
$result = $this->csvreader->parse_file('uploads/' . $storagename);
$finalResult = $array = array_values(array_filter($result));
$this->data['worksheet'] = $finalResult;
foreach ($this->data['worksheet'] AS $key => $val)
{
$data['id'] = $val['table field name'];
$this->common->save('table_name',$data);
}
}
}
}
You can use PHPExcel to fetch data and insert it to database:
https://github.com/PHPOffice/PHPExcel
<?php
$target_dir = "/tmp/";
$target_file = $target_dir . basename($_FILES["students_list"]["name"]);
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
$filename = $_FILES["students_list"]["name"];
if (isset($_FILES["students_list"])) {
if($FileType == "csv" ) {
if (move_uploaded_file($_FILES["students_list"]["tmp_name"], $target_file)) {
$target_file = $target_dir . $filename;
set_include_path(get_include_path() . PATH_SEPARATOR . 'resources/imported_file/');
include 'PHPExcel/IOFactory.php';
try {
$objPHPExcel = PHPExcel_IOFactory::load($target_file);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($filename,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$name = trim($allDataInSheet[$i]["A"]);
$email = trim($allDataInSheet[$i]["B"]);
$phone = trim($allDataInSheet[$i]["C"]);
$uploaded_date = trim($allDataInSheet[$i]["D"]);
$session = trim($allDataInSheet[$i]["E"]);
$client_id = trim($allDataInSheet[$i]["F"]);
$class = trim($allDataInSheet[$i]["G"]);
$insert = $db->Queryinsert("students",array('',$name,$email,$phone,$uploaded_date,$session,$client_id,$class));
}
}
}
}
?>
This sample helps you to get data from csv file as row by row and after row 1 that involves column title, you try to get other rows then insert them to database.
In top of script i am saving file in /tmp/ folder and then doing needed actions.
You must set your own folder directions and needed Codeigniter syntaxes in this snippet.
I am creating a form with 20+ fields to submit the details of the employee's. In the form the employee has to fill their details and upload their document. There are five fields for documents namely (photo,idcard,licence,cv,attest) so the name of each uploaded document has to be stored in a particular field . If i upload all the files in sequence then it is working fine but how to insert the name of a file to their designated field if the employee only inserts one or two files.
Hope i am making sense.
controller
public function register()
{
//form validation
if($this->form_validation->run() === False){
$this->load->view('form');
}
else{
//uploading files
$number_of_files = sizeof(array_filter($_FILES['file']['tmp_name']));
$files = $_FILES['file'];
$errors = array();
for($i=0;$i<$number_of_files;$i++)
{
if($_FILES['file']['error'][$i] != 0)
{
$error[$i] = array('error' => 'Couldn\'t upload file '.$_FILES['file']['name'][$i]);
$this->load->view('form',$error);
}
}
//create a new directory for each new user
$dir = $this->input->post('fname').'_'.$this->input->post('country');
if( is_dir(FCPATH . 'uploads/'.$dir) === false )
{
mkdir(FCPATH . 'uploads/'.$dir);
}
$this->load->library('upload');
$config['upload_path'] = FCPATH . 'uploads/'.$dir;
$config['allowed_types'] = 'gif|jpg|png|docx';
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['file']['name'] = $files['name'][$i];
$_FILES['file']['type'] = $files['type'][$i];
$_FILES['file']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['file']['error'] = $files['error'][$i];
$_FILES['file']['size'] = $files['size'][$i];
$this->upload->initialize($config);
// we retrieve the number of files that were uploaded
if ($this->upload->do_upload('file'))
{
$data['uploads'][$i] = $this->upload->data();
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form',$error);
}
}
//assign names of uploaded files to insert in database
if($data){
foreach($data as $value){
$photo = FCPATH . 'uploads/'.$dir.$value[0]['file_name'];
$idProof = FCPATH . 'uploads/'.$dir.$value[1]['file_name'];
$cv = FCPATH . 'uploads/'.$dir.$value[2]['file_name'];
$license = FCPATH . 'uploads/'.$dir.$value[3]['file_name'];
$attest = FCPATH . 'uploads/'.$dir.$value[4]['file_name'];
}
}
$this->form_model->insert_users($photo,$idProof,$cv,$license,$attest);
redirect('form/registered');
}
}
model
public function insert_users($photo,$idProof,$cv,$license,$attest){
$data = array(
//other fields...
'other' => $this->input->post('other'),
'photo' => $photo,
'idProof' => $idProof,
'cv' => $cv,
'license' => $license,
'attest' => $attest
);
return $this->db->insert('employee',$data);
}
View
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
I am trying to upload images to a directory that is defined on input page and passed to the $path variable within the function. Right now it uploads the image in to the same directory as the upload script and not the defined image folder. I have re-worked this several ways the the result is always the same. Both $path and $this->destination remain empty and the image is uploaded to the wrong place. Can anyone else see what I have done wrong?
<?php
//set the max upload size in bytes
$max = 51200;
if(isset($_POST['upload'])){
//define path to the upload directory
$destination = '../../../../image_folder/test/';
require_once('upload.php');
try {
$upload = new Ps2_Upload("$destination");
$upload->move();
$result = $upload->getMessages();
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<body>
<?php
if (isset($result)) {
echo '<ul>';
foreach ($result as $message) {
echo "<li>$message</li>";
}
echo '</ul>';
}
echo "the place the files will be put is $destination";
?>
<form action="" method="post" enctype="multipart/form-data" id="uploadImage">
<label for="image">Upload New Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max; ?>" />
<input type="file" name="image" id="image" />
<input type="submit" name="upload" id="upload" value="Upload" />
</form>
</body>
</html>
<?php
class Ps2_Upload {
//protected variables
protected $_uploaded = array();
protected $_destination;
protected $_max = 51200;
protected $_messages = array();
protected $_permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/png');
protected $_renamed = false;
public function __construct($path){
if(!is_dir($path) || !is_writable($path)){
throw new Exception("$path must be a valid, writable directory.");
}
$this->_destination = $path;
$this->_uploaded = $_FILES;
}
public function move(){
$field = current($this->_uploaded);
$success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
if($success){
$this->_messages[] = $field['name'] . " uploaded successfully to $this->destination";
} else {
$this->_messages[] = 'Could not upload ' . $field['name'];
}
}
public function getMessages() {
return $this->_messages;
}
}
?>
In your constructor, you have this: $this->_destination = $path;
In your move() method, you have this: $success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
your protected variable is _destination but what you are using in the move() method is destination. No underscore before it. Work on that, might solve your problem:
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
Should work.
$success = move_uploaded_file($field['tmp_name'], $this->destination . $field['name']);
should be
$success = move_uploaded_file($field['tmp_name'], $this->_destination . $field['name']);
note that you have a typo in $this->destination, and it should be $this->_destination
I want to upload some files. I use codeigniter:
Html:
<input type="file" name="file1" />
<input type="file" name="file2" />
php:
$config['upload_path'] = './upload/';
$path = $config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['encrypt_name'] = 'TRUE';
$this->load->library('upload', $config);
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name']) && $value['size'] > 0) {
if (!$this->upload->do_upload($key)) {
// some errors
} else {
// Code After Files Upload Success GOES HERE
$data_name = $this->upload->data();
echo $data_name['file_name'];
}
}
}
When I want to echo file name, I get 1.jpg and 2.jpg. But I want to have them separately and insert them into database.
How can I do this? Thank you :)
Add the the value from $data_name['file_name'] into an array and after your foreach loop do a insert_batch.
something like:
$filename_arr = array();
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name']) && $value['size'] > 0) {
if (!$this->upload->do_upload($key)) {
// some errors
} else {
// Code After Files Upload Success GOES HERE
$data_name = $this->upload->data();
$filename_arr[] = $data_name['file_name'];
}
}
}
$this->db->insert_batch('mytable', $filename_arr);
I'm trying to upload multiple images at once to my database. I was able to do it with single files but i'm not able to get it going with the html5 multiple option.
This is my form:
<form action="includes/saveImage.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" multiple="multiple" name="image[]" accept="image/*"> <input type="submit" value="upload">
</form>
and this is my saveImage.php
$files = array();
$fdata = $_FILES["image"];
if (is_array($fdata["name"]))
for ($i = 0; $i < count($fdata['name']); ++$i) {
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
'image' => file_get_contents($fdata['tmp_name'][$i]),
);
}
} else {
$files[] = $fdata;
}
foreach ($files as $file)
{
if (!$album_mysqli->query("INSERT INTO '1' VALUES ('','{$file['name']}','{$file['image']}',NOW())"))
{
print"error while uploading";
}
// print_r( $file );
}
If i uncomment the last print_r($file); it shows the binary data of the image file.
Any ideas why it won't upload to my database?
The database I want to write to uses a BLOB field for the image.
Solved my problem
There was some problem with the SQL-statement
Adding the pictures in this way works just fine...
foreach ($files as $file)
{
$image = file_get_contents($file['tmp_name']);
$result = $album_mysqli->prepare("INSERT INTO '1' VALUES ('', ?, ?, CURDATE())");
$result->bind_param("ss", $file['name'], $image);
if (!$result->execute())
{
echo"Problem on file {$file['name']}. <br/>";
}
else
{
echo("{$file['name']} was added to the database. <br/>");
}
$result->close();
}
You cant upload images to your database like this. You should eiter upload the image via PHP to a certain directory and insert into your database their filenames so that you can fetch them after that, or you can upload their base64 code into the database and put it in the image tag like this <img src="base64_code_of_the_image" />
foreach ($files as $file)
{
#move_uploaded_file($file['tmp_name'],<destinationfile>);
if (!$album_mysqli->query("INSERT INTO '1' VALUES
('','{$file['name']}','',NOW())"))
{
print"error while uploading";
}
print_r( $file );
}
You can't upload the images into the database directly as you are trying. If you want to do that you need to create BLOB object for that specific field in the database table.
Solved my problem
There was some problem with the SQL-statement
Adding the pictures in this way works just fine...
$files = array();
$fdata = $_FILES["image"];
if (is_array($fdata["name"]))
for ($i = 0; $i < count($fdata['name']); ++$i) {
$files[] = array(
'name' => $fdata['name'][$i],
'tmp_name' => $fdata['tmp_name'][$i],
'image' => file_get_contents($fdata['tmp_name'][$i]),
);
}
} else {
$files[] = $fdata;
}
foreach ($files as $file)
{
$image = file_get_contents($file['tmp_name']);
$result = $album_mysqli->prepare("INSERT INTO '1' VALUES ('', ?, ?, CURDATE())");
$result->bind_param("ss", $file['name'], $image);
if (!$result->execute())
{
echo"Problem on file {$file['name']}. <br/>";
}
else
{
echo("{$file['name']} was added to the database. <br/>");
}
$result->close();
}
<?php
//include connection here
include'connect.php';
if(isset($_POST['submit']))
{
$file_name = $_FILES['image']['name'];
$file_type = $_FILES['image']['type'];
$file_size = $_FILES['image']['size'];
$data = $_FILES['image']['tmp_name'];
for($i=0; $i<=count($data)-1; $i++)
{
$name = addslashes($file_name[$i]);
$type = addslashes($file_type[$i]);
$size = addslashes($file_size[$i]);
$tmp = addslashes(file_get_contents($data[$i]));
$sql = "INSERT INTO t_home_pix(name, type, size, content) VALUES('".$name."','".$type."','".$size."','".$tmp."')";
mysqli_query($conn, $sql);
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
File:
<input type="file" multiple="multiple" name="image[]" accept="image/*">
<input type="submit" name="submit" value="upload">
</form>