Language: PHP / Using Class Upload by Colin Verot
About: Multiple Uploading
The code below already uploads the files fine, it works...
PROBLEM: I am having trouble figuring out how to get the filename extension.
(In a comment below, I have specified where my problem area is...)
// CONNECTION TO DATABASE HERE...
// INCLUDE UPLOAD CLASS LIBRARY
include (dirname(__FILE__).'/lib/class.upload.php');
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_FILES['fileupload']['name'];
}
}
foreach ($files as $file) {
// THIS IS MY PROBLEM AREA, GETTING FILE EXTENSION
$ext=strchr($imagename,".");
$generate_name = rand(100,99999);
$generate_name_extra = rand(200,9999);
$filenamex = "PHOTO_".$generate_name.$generate_name_extra."_".time();
$filenamex_thumb = $filenamex."_thumb";
// COMPLETE FILENAME WITH EXTENSION
$filename = $filenamex.strtolower($ext);
$handle = new upload($file);
if ($handle->uploaded) {
///// 1 ////////////////////////////////////////////////////////////////////
$handle->file_new_name_body = $filenamex_thumb;
$handle->image_resize = true;
$handle->image_x = '300';
$handle->image_ratio_y = true;
$handle->jpeg_quality = '100';
// ABSOLUTE PATH BELOW
$handle->process($absoRoot.'covers/thumbs/');
if ($handle->processed) {
// SUCCESSFUL RESPONSE
}
else
{
// FAILED RESPONSE
}
}
}
And the webform is:
<form method="post" action="upload.php" enctype="multipart/form-data">
<input name="fileupload[]" id="fileupload" type="file" multiple>
I really pretty much need the file extensions to serve the files correctly online, but I can't spot where to find it. I have tried using: $files[$i][$k] instead of $imagename in my specified problem area above, as well as $file and other possible solutions, but I can't spot which one's going to give me the filename with extension.
Hopefully someone could point it out. Thank you for your time and assistance!
$ext=array_pop(explode('.', $imagename));
The function you're looking for is pathinfo().
$pathdata = pathinfo($filename);
$extension = $pathdata['extension'];
Related
I am trying to upload a .qif file in php codeigniter but it returns an error
The filetype you are attempting to upload is not allowed.
When I try to upload another type file (PDF, CSV, docs, etc.) they upload successfully.
Here is my code:
function do_upload($field_name, $files, $folder_path,$save_name="",$prefix="bk_"){
$ci = & get_instance();
//create upload folder if not exists
if (!is_dir($folder_path)) {
mkdir($folder_path, 0777, TRUE);
}
$save_name = $prefix.time()."_".$files['name'];
$data = array();
$config = array();
$config['upload_path'] = $folder_path;
//$config['max_size'] = 0;
$config['allowed_types'] = 'csv|CSV|txt|TXT|pdf|PDF|zip|ZIP|doc|DOC|docx|DOCX|xlsx|xls|XLS|XLSX|QIF|qif';
$config['file_name'] = $save_name;
$ci->load->library('upload');
$ci->upload->initialize($config);
// echo "hello 1"; die;
if ($ci->upload->do_upload($field_name)){
$data = $ci->upload->data();
$data['status'] = 1;
}
else{
$data['status'] = 0;
$data['error'] = $ci->upload->display_errors();
}
return $data;
}
You get the "filetype is not allowed" error, because the original Codeigniter mime-type configuration file doesn't list an qif entry:
in your config/mimes.php file add to the $mimes array this line:
'qif' => 'application/qif'
and eventually
'qif' => 'image/x-quicktime'
mime-type source: http://fileformats.archiveteam.org/wiki/Ext:qif
the native php move_uploaded_file method without checking for mime-types can turn into a security problem
I got a solution after lot of searches
I just use move_uploaded_file function and it's work
move_uploaded_file($_FILES["file"]["tmp_name"], $path);
if someone have a better answer answer please share that.
thanks
First off, the upload folder is given 777, and my old upload script works, so the server accepts files. How ever this is a new destination.
I use krajee bootstrap upload to send the files. And I receive a Jason response. The error seems to be around move uploaded file. I bet it's a simple error from my side, but I can't see it.
<?php
if (empty($_FILES['filer42'])) {
echo json_encode(['error'=>'No files found for upload.']);
// or you can throw an exception
return; // terminate
}
// get the files posted
$images = $_FILES['filer42'];
// a flag to see if everything is ok
$success = null;
// file paths to store
$paths= [];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
$ext = explode('.', basename($filenames[$i]));
$target = "uploads" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);
if(move_uploaded_file($_FILES["filer42"]["tmp_name"][$i], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
}
// check and process based on successful status
if ($success === true) {.
$output = [];
$output = ['uploaded' => $paths];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
// delete any uploaded files
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>
I think field name is the issue. Because you are getting image name with filer42 and upload time, you are using pictures.
Please change
$_FILES["pictures"]["tmp_name"][$i]
to
$_FILES["filer42"]["tmp_name"][$i]
And check now, Hope it will work. Let me know if you still get issue.
The error is not in this script but in the post.
I was using <input id="filer42" name="filer42" type="file">
but it have to be <input id="filer42" name="filer42[]" type="file" multiple>
as the script seems to need an arrey.
It works just fine now.
In my Laravel project I created a page to upload the files and I use the $file of laravel it works fine for some system only but for some system it shows an error as shown in image below.
Function I am using to upload files in model
public function add_document_sub_cert($req)
{
$subcontractor_id = $req['subcontractor_id'];
$reference_id = $req['reference_id'];
$files = $req->file("uploaded_doc0");
$i = 0;
foreach($files as $file){
$i++;
$ext = $file->guessClientExtension();
$name = $file->getClientOriginalName();
$file_name_1 = str_replace(".".$ext,"",$name);
$path = $file->storeAs('subcontractor/','avc'.$i.'.jpg');
if($path){
$document = new Document();
$document->doc_name = 'avc.jpg';
$document->module = 'subcontractor';
$document->reference_id = $reference_id;
$document->save();
}
}
}
Your error says that you didn't specify a filename. I see that your variable $file_name_1 is never used. Haven't you forgotten to use it somewhere?
Without knowing how your class Document works, it's impossible to tell you exactly where is the bug.
I use an upload form to upload images. Small image like < 4mb will work.
But if I upload an image with a file size like 5.7MB, it doesn't do anything. It just doesn't upload the file. I have searched a lot but I couldn't figure it out. I think the problem has to deal with this code:
case 'png':
if (!function_exists('imagecreatefrompng')) {
$this->processed = false;
$this->error = $this->translate('no_create_support', array('PNG'));
} else {
echo $this->file_src_pathname;
echo $this->log;
echo $this->error;
echo $image_src = #imagecreatefrompng($this->file_src_pathname);
if (!$image_src) {
$this->processed = false;
$this->error = $this->translate('create_error', array('PNG'));
} else {
$this->log .= '- source image is PNG<br />';
}
}
break;
The #imagecreatefrompng($this->file_src_pathname) function is that piece of code where my code breaks. It doesn't output anything after that code, except when I comment it out. I have already changed my memory limit to 256M and the file upload to 64M. The file name is set. I have no idea why it only breaks my code when it has to deal with big files. Do any of you guys have an idea?
The code on the file upload page is:
//form processing
include('../includes/class.upload.php');
$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;
}
}
foreach ($files as $file) {
if(!empty($file)){
$handle = new Upload($file, 'nl_NL');
if (!file_exists("../classified_images/$adid"))
mkdir("../classified_images/$adid", 0777);
$tag_code_p = generatePassword(25);
if ($handle->uploaded) {
$oriname = $handle->file_src_name;
$handle->mime_magic_check = true;
$handle->allowed = array('image/*');
$handle->image_convert = 'jpg';
$newname = $adid."_big_".$tag_code_p;
$handle->file_new_name_body = $newname;
$handle->image_resize = true;
$handle->image_ratio_fill = true;
$handle->image_y = 600;
$handle->image_x = 800;
$handle->image_background_color = '#FFFFFF';
// // 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("../classified_images/");
// we check if everything went OK
if ($handle->processed) {
$handle->image_convert = 'jpg';
$newnamesmall =$adid."_small_".$tag_code_p;
$handle->file_new_name_body = $newnamesmall;
$handle->image_resize = true;
$handle->image_ratio_fill = true;
$handle->image_y = 94;
$handle->image_x = 125;
$handle->image_background_color = '#FFFFFF';
// 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("../classified_images/");
$handle->clean();
//inserten in database
$sql_foto_insert = "insert into photos
( adid, photosmall, photo)
values
('$adid', '$newnamesmall.jpg','$newname.jpg')";
$foto_result = mysql_query($sql_foto_insert);
// everything was fine !
//$msg .= $oriname.' '.LANG_FOTOS_SAVED.'<br />';
$allok = 1;
} else {
// one error occured
$msg .= $handle->error . '<br />';
}
}
This can be caused by configuration issues. Since this happens for files > certain size, I feel it can be related to php ini settings.
Check upload_max_filesize and post_max_size in your php ini settings. These could be set to 4MB. You can increase these values to make it work.
If you are in a shared hosting environment where you cannot edit php ini, you can add them to .htaccess file like so:
php_value upload_max_filesize 7M
php_value post_max_size 7M
Also you should remove the # from your function to see what the error is. Suppressing errors by adding # is a bad idea while developing/debugging.
Additionally, if you are in a local machine or own dev server, open the apache error_log and check the last few lines to see what the error is. If you are on a third party server, most control panels provide an interface to view the error log.
Language: PHP / MySQL
I am going out of my mind, I really have to ask now... I have a multiple file upload form:
<input type="file" name="fileupload[]" multiple>
With the help of some Javascript, on each change made to this input, it appends a list of filenames, + a formatted string (grabbed from the filename) inside another input, so onchange we have a layout as shown below (assuming that we just added some images):
Almost similar to: http://jsfiddle.net/pxfunc/WWNnV/4/
// An HTML representation of such layout would be... (assuming that we added 3 images)
<input type="file" name="fileupload[]" multiple>
image-name-1.jpg <input type="text" value="Image Name 1" name="keyword[]">
justsome_file.png <input type="text" value="Justsome File" name="keyword[]">
some_Img-031.gif <input type="text" value="Some Img 031" name="keyword[]">
<input type="submit" value="Upload">
I have it this way because aside from uploading the files, I would also like to add them to my database, with a default title based on its filename (and the option to set/change this title for each image as I upload it). There is no problem with my form.
PROBLEM: My dilemma lies inside the PHP page where the form data/action is submitted.
I can only manage to either:
Upload correct images, but get same title for all
Insert correct titles, but get same image for all
Here is my PHP action page: (Currently uploading correct images, but having same title for all)
<?php
// CONNECT TO DATABASE...
// INCLUDE UPLOAD CLASS LIBRARY
include (dirname(__FILE__).'/lib/class.upload.php');
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
// create an array here to hold file names
$uploaded = array();
foreach ($files as $file)
{
$generate_name = rand(100,99999);
$generate_name_extra = rand(200,9999);
$filenamex = "COVER_PHOTO_".$generate_name.$generate_name_extra."_".time();
$filenamex_thumb = $filenamex."_thumb";
$handle = new upload($file);
if ($handle->uploaded) {
$this_upload = array();
///// 1 ////////////////////////////////////////////////////////////////////
$handle->file_new_name_body = $filenamex_thumb;
$handle->file_force_extension = true;
$handle->image_resize = true;
$handle->image_x = '300';
$handle->image_ratio_y = true;
$handle->jpeg_quality = '100';
// ABSOLUTE PATH BELOW
$handle->process($absoRoot.'covers/thumbs/');
////////////////////////////////////////////////////////////////////////////
if ($handle->processed) {
// store the image filename
$this_upload['image'] = $handle->file_dst_name; // Destination file name
$this_upload['body'] = $handle->file_dst_name_body; // Destination file name body
$this_upload['extension'] = $handle->file_dst_name_ext; // Destination file extension
$category_id = $_POST['cat'];
$hiddenvalues = explode ("|",$_POST["cat"]);
$category = $hiddenvalues[0];
$category_name = $hiddenvalues[1];
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id) VALUES ("", "'.$this_upload['image'].'", "'.$imagename.'", "'.$category_name.'", "'.$category.'")';
mysql_query($sql);
}
$handle->clean();
header("Location: ./upload.php");
$message = "";
} else {
echo ' file not uploaded to the wanted location';
echo ' Error: ' . $handle->error . '';
}
} ?>
(I use the Upload Class by Colin Verot to handle image uploads, and their FAQ tutorial to handle MULTIPLE image uploads on this page, under: What about multiple uploads?)
This would work perfect if I were just uploading images, however I added the functionality of adding each image data to my database. & This is where it gets confusing.
I'm sure the key is placing the SQL query inside the right foreach, or perhaps making another one, but I've tried that & it only gives me 1 good result for either the image upload or the title, never for both.
I need to upload the image to the site, then store its data (including image path) to my database.
Please look into my code and enlighten me how to solve this problem? A snippet clue would really be great for now as I am already very confused after having tried all I could think of. Thank you so much!
You aren't saving your $imagename variable to the $files array, you're just resetting it each time.
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
Should be something like:
$files[$i][$k] = array($v, $_POST['keyword'][$i]);
...
foreach ($files as $data) {
list($file, $imagename) = $data;
...
}
I do think one of your problems is your foreach:
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
So you are going through each of the fields assigning their value to the right file which fits this structure policy:
_FILES => array(
'name' => array(0 => 'file.txt'),
'size' => array(0 => 235)
)
Which is correct for multifiles but then you do:
$imagename = $_POST['keyword'][$i];
Which does not look right. You are overwriting the var each time with the last looked at which means you will only ever get one input vlaue.
When you're gathering the file information you're overwriting $imagename on every loop so it will be assigned to the last one. Try attaching it to the $files variable (hopefully this doesn't mess with the upload class you're using).
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$files[$i]['imagename'] = $_POST['keyword'][$i];
}
Then update your $sql string to reference that
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id)
VALUES ("", "'.$this_upload['image'].'", "'.$file['imagename'].'",
"'.$category_name.'", "'.$category.'")';