I work on a oop class.php file. I want to implement function __contruct(). I don't know why it doesn't work.
I think there is error, but I don't know how to write it. $args['file_upload'] = $_FILES['file_upload'][''] ?? NULL;
Thanks.
fileupload.class.php
public function __construct($string){
$this->filename = $_FILES['$string']['name']['0'];
$this->temp_path = $_FILES['$string']['tmp_name']['0'];
$this->type = $_FILES['$string']['type']['0'];
$this->size = $_FILES['$string']['size']['0'];
}
public function create() {
if(move_uploaded_file....
}
fileupload.php
if(is_post_request()) {
//Create record using post parameters
$args = [];
$args['prod_name'] = $_POST['prod_name'] ?? NULL;
$args['file_upload'] = $_FILES['file_upload'][''] ?? NULL;
$image = new Imageupload($args);
$result = $image->create();
if($result === true) {
$new_id = $image->id;
$_SESSION['message'] = 'The image was uploaded.';
} else {
// show errors
}
} else {
// display the form
$image = [];
}
<p><input name="file_upload[]" type="file" id="file_upload[]" value=""></p>
<p>Product name: <input type="text" name="prod_name" value="" /></p>
UPDATE1 function works
public function add_files() {
$this->filename = $_FILES['file_upload']['name']['0'];
$this->temp_path = $_FILES['file_upload']['tmp_name']['0'];
$this->type = $_FILES['file_upload']['type']['0'];
$this->size = $_FILES['file_upload']['size']['0'];
}
$image = new Imageupload($args);
$image->add_files();
Looks like you're creating a wheel again? :)
Try one of the libraries has been created for this purpose.
https://github.com/brandonsavage/Upload
Install composer in you operating system and run the following command in your command line
composer require codeguy/upload
Html
<form method="POST" enctype="multipart/form-data">
<input type="file" name="foo" value=""/>
<input type="submit" value="Upload File"/>
</form>
PHP
<?php
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);
// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);
// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations(array(
// Ensure file is of type "image/png"
new \Upload\Validation\Mimetype('image/png'),
//You can also add multi mimetype validation
//new \Upload\Validation\Mimetype(array('image/png', 'image/gif'))
// Ensure file is no larger than 5M (use "B", "K", M", or "G")
new \Upload\Validation\Size('5M')
));
// Access data about the file that has been uploaded
$data = array(
'name' => $file->getNameWithExtension(),
'extension' => $file->getExtension(),
'mime' => $file->getMimetype(),
'size' => $file->getSize(),
'md5' => $file->getMd5(),
'dimensions' => $file->getDimensions()
);
// Try to upload file
try {
// Success!
$file->upload();
} catch (\Exception $e) {
// Fail!
$errors = $file->getErrors();
}
Related
I cant figure out how how zip a file in PHP with password. The password will be the time and filename.
This is what i have done so far.
HTML Code for upload.
<form enctype="multipart/form-data" action="http://localhost/CSS/addfile.php" method="POST">
<div id="label">
<label>Upload File</label>
</div>
<input name="doc" type="file" placeholder="Upload File Here" accept="files/topsecret/*" required>
<input type="submit" value="Upload" name="submit">
</form>
PHP code
function GetImageExtension($filetype)
{
if(empty($filetype)) return false;
switch($filetype)
{
case 'files/topsecret/bmp': return '.bmp';
case 'files/topsecret/gif': return '.gif';
case 'files/topsecret/jpeg': return '.jpg';
case 'files/topsecret/png': return '.png';
case 'files/topsecret/txt': return '.txt';
case 'files/topsecret/doc': return '.doc';
case 'files/topsecret/docx': return '.docx';
case 'files/topsecret/pdf': return '.pdf';
default: return false;
}
}
$upFile = $_FILES['doc']['name'];
$tmp_name = $_FILES['doc']['tmp_name'];
$ftype = $_FILES['doc']['type'];
$fileExt = GetImageExtension($ftype);
$filename = $upFile.$fileExt;
$target_path="files/topsecret/".$filename;
move_uploaded_file($tmp_name,$target_path);
date_default_timezone_set('Asia/Kuala_Lumpur');
$timefile = date("F j, Y g:ia");
$size = filesize($target_path);
$size = number_format($size / 1024, 2) . ' KB';
try{
$sql = "INSERT INTO file(File_path,Date,Size,Name) VALUES ('".$target_path."','".$timefile."','".$size."','".$filename."')";
if ($connection->query($sql)){
echo"<script type= 'text/javascript'>alert('Upload Successfully');</script>";
header("refresh:2;index.php");
}else{
echo "<script type= 'text/javascript'>alert('Upload Not Successfully Inserted.');</script>";
}
I have research a found a few function for php but dont know how to use it.
like. ZipArchive::setEncryptionName ... but cant use it as i am using PHP version 7.1.8, in xampp.
Please help me explain on how to do it, as simple as possible. I need to encrypt the uploaded file with password using zip or rar. Plan to use hash the file name and time together and then setting it as the password.
Thanks a lot.
First, a try block needs a catch.
Secondly, you shouldn't need the GetImageExtension function, $_FILES has the extension in the uploaded array, all you needed to do was print_r($_FILES); to be able to verify.
Sadly though, from what I read you can't encrypt a file just yet, you need to wait for php 7.2 to be released to use $zip->setEncryptionName;.
I figured this out after writing out a bit of code, I figured it might be helpful nonetheless that's why I'm posting this answer.
You can look into: http://php.net/manual/en/filters.encryption.php, that's a good option to integrate into the code below, I don't have the time right now but it's fairly easy to do following their examples.
if(isset($_POST['submit'])){
upload($_FILES);
}
class Connection {
protected $db = null;
public function db(){
if($this->db === null){
try {
$this->db = new PDO('mysql:host=localhost;dbname=name; charset=utf8', user, password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
return $this->db;
}
}
function upload($file_data){
// calling this statically, don't suggest it
$conn = Connetion::db();
$name = $file_data['doc']['name'];
$tmp_name = $file_data['doc']['tmp_name'];
$extension = explode('/', $file_data['doc']['type']); // $extension[1] returns file type.
$image_size = getimagesize($tmp_name);
$file_name = $name . '.' . $extension[1];
$target_path = "";
if($image_size !== false){
$zip = new ZipArchive();
if ($zip->open('uploaded_file.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFromString("text.txt", "#1 This is a test string added as testfilephp.txt.\n");
$zip->setEncryptionName('text.txt', ZipArchive::EM_AES_256, 'secret'); // here we'd set the password
$zip->close();
$zip_created = true;
} else {
$zip_created = false;
}
// if zip was created and uploaded the file, then we upload it to the database
if($zip_created == true){
$sth = $conn->prepare('INSERT INTO file (file_path, `date`, size, name) VALUES (:target_path, :time_file, :size, :file_name)');
$sth->bindValue(':target_path', $target_path, PDO::PARAM_STR);
$sth->bindValue(':time_file', date('m-d-Y H:i:s'), PDO::PARAM_STR);
$sth->bindValue(':target_path', $target_path, PDO::PARAM_STR);
$sth->bindValue(':file_name', $file_name, PDO::PARAM_STR);
$sth->execute();
} else {
// here we can upload the error to the database or do nothing
}
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="doc">
<input type="submit" value="Upload" name="submit">
</form>
My controller code for upload file in laravel 5.4:
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = rand(11111, 99999) . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
Image was successfully uploaded but the code threw an exception :
FileNotFoundException in MimeTypeGuesser.php line 123
The file is there any fault in my code or is it a bug in laravel 5.4, can anyone help me solve the problem ?
My view code:
<form enctype="multipart/form-data" method="post" action="{{url('admin/post/insert')}}">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput">File input</label>
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="form-group">
<label for="">submit</label>
<input class="form-control" type="submit">
</div>
</form>
Try this code. This will solve your problem.
public function fileUpload(Request $request) {
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('input_img')) {
$image = $request->file('input_img');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
You can use it by easy way, through store method in your controller
like the below
First, we must create a form with file input to let us upload our file.
{{Form::open(['route' => 'user.store', 'files' => true])}}
{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}
{{Form::close()}}
Here is how we can handle file in our controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function store(Request $request)
{
// get current time and append the upload file extension to it,
// then put that name to $photoName variable.
$photoName = time().'.'.$request->user_photo->getClientOriginalExtension();
/*
talk the select file and move it public directory and make avatars
folder if doesn't exsit then give it that unique name.
*/
$request->user_photo->move(public_path('avatars'), $photoName);
}
}
That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.
A good logic for your application could be something like:
public function uploadGalery(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/storage/galeryImages/');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
Use the following code:
$imageName = time().'.'.$request->input_img->getClientOriginalExtension();
$request->input_img->move(public_path('fotoupload'), $imageName);
public function store()
{
$this->validate(request(), [
'title' => 'required',
'slug' => 'required',
'file' => 'required|image|mimes:jpg,jpeg,png,gif'
]);
$fileName = null;
if (request()->hasFile('file')) {
$file = request()->file('file');
$fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
$file->move('./uploads/categories/', $fileName);
}
Category::create([
'title' => request()->get('title'),
'slug' => str_slug(request()->get('slug')),
'description' => request()->get('description'),
'category_img' => $fileName,
'category_status' => 'DEACTIVE'
]);
return redirect()->to('/admin/category');
}
Intervention Image is an open source PHP image handling and manipulation library
http://image.intervention.io/
This library provides a lot of useful features:
Basic Examples
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Method chaining:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Tips: (In your case)
https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Tips 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Tips 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Function:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}
if ($request->hasFile('input_img')) {
if($request->file('input_img')->isValid()) {
try {
$file = $request->file('input_img');
$name = time() . '.' . $file->getClientOriginalExtension();
$request->file('input_img')->move("fotoupload", $name);
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
or follow
https://laracasts.com/discuss/channels/laravel/image-upload-file-does-not-working
or
https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/12
i think better to do this
if ( $request->hasFile('file')){
if ($request->file('file')->isValid()){
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('images' , $name);
$inputs = $request->all();
$inputs['path'] = $name;
}
}
Post::create($inputs);
actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory
// get image from upload-image page
public function postUplodeImage(Request $request)
{
$this->validate($request, [
// check validtion for image or file
'uplode_image_file' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
// rename image name or file name
$getimageName = time().'.'.$request->uplode_image_file->getClientOriginalExtension();
$request->uplode_image_file->move(public_path('images'), $getimageName);
return back()
->with('success','images Has been You uploaded successfully.')
->with('image',$getimageName);
}
This code will store the image in database.
$('#image').change(function(){
// FileReader function for read the file.
let reader = new FileReader();
var base64;
reader.readAsDataURL(this.files[0]);
//Read File
let filereader = new FileReader();
var selectedFile = this.files[0];
// Onload of file read the file content
filereader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
$("#pimage").val(JSON.stringify(base64));
};
filereader.readAsDataURL(selectedFile);
});
HTML content should be like this.
<div class="col-xs-12 col-sm-4 col-md-4 user_frm form-group">
<input id="image" type="file" class="inputMaterial" name="image">
<input type="hidden" id="pimage" name="pimage" value="">
<span class="bar"></span>
</div>
Store image data in database like this:
//property_image longtext(database field type)
$data= array(
'property_image' => trim($request->get('pimage'),'"')
);
Display image:
<img src="{{$result->property_image}}" >
public function ImageUplode(Request $request) {
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = $request['code'].'.jpg';
//move image to public/image folder
$file->move(public_path('imgage'), $picture);
// image uplode function Succesfully saved message
return response()->json(["message" => "Image Uploaded Succesfully"]);
}
else {
return response()->json(["message" => "Select image first."]);
}
}
In Laravel 5.4, you can use guessClientExtension
i have multiple textbox with file uploader but i can't able to store the file in folder path. i want to add more fields for upload and store the files in the specific folder.
I tried everything. i have attached my code with this please look.
Sorry for my bad english.
PHP code for upload:
<?php if(isset($_FILES['attach'])){
$errors= array();
$file_name = $_FILES['attach']['name'];
$file_size =$_FILES['attach']['size'];
$file_tmp =$_FILES['attach']['tmp_name'];
$file_type=$_FILES['attach']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['attach']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size < 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type = "text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><input type="text" name="hint[]" value=""> <input type="file" name="attach[]" value=""><img src="remove-icon.png" alt="Remove"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<form name="" action="" method="post" enctype="multipart/form-data">
<div class="field_wrapper" id="qus_box">
<div>
<input type="text" name="field_name[]" value=""/>
<input type="text" name="hint[]" value="">
<input type="file" name="attach[]" value="">
Add
<input type="submit" name="submit" value="SUBMIT"/>
</div>
</div>
</form>
You just do a foreach loop over the $_FILES array. This is a duplicate of this question and has been asked and answered many times over:
Multiple file upload in php
That being said, since it's been answered already and so I don't just regurgitate what's already out there, I will add a bit more to this answer. In this day and age, you can't just simply upload a file. Likely you will want to keep records of it in a database or show some stats on the view after the page reloads. To do that you need to use a class/method system (in my opinion) where you can actually do the upload but also get useful information back. A framework would take care of all this for you (and more!), but for the sake of this answer, here is a simple example, maybe it will give you ideas:
class Files
{
private $filesArr,
$destination,
$errors,
$success,
$full_path;
/*
** #description This will point the image uploads to a folder
** #param $dir [string] This is the directory where files will save
** #param $make [bool] This will instruct the method to make or not
** make a folder if not exists
*/
public function setDest($dir,$make = true)
{
if(!is_dir($dir)) {
if(!$make || ($make && !mkdir($dir,0755,true)))
throw new Exception('Directory does not exist');
}
$this->destination = $dir;
return $this;
}
/*
** #description This will upload the files and keep some records
** for reference after the fact
*/
public function saveFiles()
{
if(empty($this->filesArr)){
throw new Exception('No files to upload.');
return false;
}
foreach($this->filesArr as $file) {
$filename = $file['name'].'.'.$file['ext'];
if(!move_uploaded_file($file['tmp_name'],$this->destination.'/'.$filename))
throw new Exception('Could not save file "'.htmlspecialchars($filename).'" to folder.');
else {
$this->full_path[] = $this->destination.'/'.$filename;
$this->success[] = $filename;
}
}
}
/*
** #description This organized the files array and allows you to
** set different listeners
*/
public function organize($key)
{
foreach($_FILES[$key]['name'] as $num => $val) {
$ext = $this->getExt($val);
$size = $_FILES[$key]['size'][$num];
$name = pathinfo($val,PATHINFO_FILENAME);
if($_FILES[$key]['error'][$num] != 0) {
$this->errors[] = 'An error occurred: '.htmlspecialchars($name);
continue;
}
elseif(!$this->typeAllowed($ext)) {
$this->errors[] = 'File type not allowed ('.htmlspecialchars($ext).') :'.htmlspecialchars($name);
continue;
}
elseif(!$this->sizeAllowed($size)){
$this->errors[] = 'File too big: '.htmlspecialchars($name);
continue;
}
$this->filesArr[$num]['name'] = $name;
$this->filesArr[$num]['ext'] = $ext;
$this->filesArr[$num]['tmp_name'] = $_FILES[$key]['tmp_name'][$num];
$this->filesArr[$num]['size'] = $size;
$this->filesArr[$num]['tmp_name'] = $_FILES[$key]['tmp_name'][$num];
# I would put a path. I would remove directories outside
# of the root from the destination path. This way you
# can move a website to different web hosts and the
# path will still be good because it will be relative to
# the site root, not the server root. This is only important
# if you plan to store the path in a database...
$this->filesArr[$num]['full_path'] = $this->destination.'/'.$name.'.'.$ext;
}
return $this;
}
/*
** #description This just gives a summary of the actions taken in
** the event
*/
public function getStats()
{
$extsCnt = array();
$fileSum = 0;
if(!empty($this->filesArr)) {
foreach($this->filesArr as $files) {
$store['ext'][] = $files['ext'];
$store['size'][] = $files['size'];
}
if(!empty($store)){
$extsCnt = array_count_values($store['ext']);
$fileSum = array_sum($store['size']);
}
}
return array(
'success'=>(!empty($this->filesArr))? count($this->filesArr):0,
'errors'=>(!empty($this->errors))? count($this->errors):0,
'total_uploaded'=>$fileSum,
'extension_count'=>$extsCnt
);
}
public function toJson()
{
return json_encode($this->getFiles());
}
public function getFiles()
{
return $this->filesArr;
}
public function getErrors()
{
return $this->errors;
}
public function getSuccess()
{
return $this->success;
}
public function getPaths()
{
return $this->full_path;
}
# This method is a little weak. It needs to be more flexible
# Should be able to add/remove file types
public function typeAllowed($ext)
{
return in_array($ext,array("jpeg","jpg","png",'sql'));
}
public function getExt($filename)
{
return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
}
public function sizeAllowed($size,$max = 2097152)
{
return ($size <= $max);
}
}
To apply to the page (the business logic) would be something like:
if(isset($_FILES['attach'])){
try {
# Create our instance
$fileManager = new Files();
# Set where we want to save files to
$fileManager
->setDest(__DIR__.'/file/to/save/here')
# Process what name from the form
->organize('attach')
# Do the upload
->saveFiles();
}
# Catch any errors thrown
catch(Exception $e) {
#You would probably want to display this in the view
# so output buffer works here
ob_start();
?>
<script>
alert('<?php echo $e->getMessage(); ?>');
</script>
<?php
$catch = ob_get_contents();
ob_end_clean();
}
}
# Here are some helpful data returns for DB storage or page view
if(isset($fileManager)) {
# Show errors
echo implode('<br />',$fileManager->getErrors()).'<br />';
# Show successful uploads
if(!empty($fileManager->getSuccess()))
echo 'Uploaded: '.implode('<br />Uploaded: ',$fileManager->getSuccess());
# Just some information that can be passed to other classes
print_r($fileManager->getFiles());
print_r($fileManager->getStats());
print_r($fileManager->toJson());
}
# Show alert in the view somewhere
if(isset($catch))
echo $catch;
The return shows something similar to this:
File type not allowed (pdf) : Filename1
Uploaded: Filename2.jpg
Uploaded: Filename3.png
Uploaded: Filename4.png
Array
(
[0] => Array
(
[name] => Filename2
[ext] => jpg
[tmp_name] => /datatmp/phpwDpP27
[size] => 17251
[full_path] => root/path/httpdocs/file/to/save/here/Filename2.jpg
)
[1] => Array
(
[name] => Filename3
[ext] => png
[tmp_name] => /datatmp/phpDXlSmH
[size] => 22636
[full_path] => root/path/httpdocs/file/to/save/here/Filename3.png
)
[2] => Array
(
[name] => Filename3
[ext] => png
[tmp_name] => /datatmp/phpSfE2Hg
[size] => 398811
[full_path] => root/path/httpdocs/file/to/save/here/Filename3.png
)
)
Array
(
[success] => 3
[errors] => 1
[total_uploaded] => 438698
[extension_count] => Array
(
[jpg] => 1
[png] => 2
)
)
[{"name":"Filename2","ext":"jpg","tmp_name":"\/datatmp\/phpwDpP27","size":17251},{"name":"Filename3","ext":"png","tmp_name":"\/datatmp\/phpDXlSmH","size":22636},{"name":"Filename4","ext":"png","tmp_name":"\/datatmp\/phpSfE2Hg","size":398811}]
Please use this code for multiple file upload:
<form name="" action="" method="post" enctype="multipart/form-data">
<div class="field_wrapper" id="qus_box">
<div>
<input type="text" name="field_name[]" value=""/>
<input type="text" name="hint[]" value="">
<input type="file" name="attach[]" value="" multiple="multiple">
Add
<input type="submit" name="submit" value="SUBMIT"/>
</div>
</div>
</form>
<?php
if(isset($_FILES['attach'])){
$errors= array();
$file_name = $_FILES['attach']['name'];
$file_size =$_FILES['attach']['size'];
$file_tmp =$_FILES['attach']['tmp_name'];
$file_type=$_FILES['attach']['type'];
$file_error = $_FILES['attach']['error'];
$extensions= array("jpeg","jpg","png");
foreach ($file_name as $f => $name) {
$file_ext=strtolower(end(explode('.',$name)));
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size < 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp[$f],"images/".$file_name[$f]);
echo "Success";
}else{
print_r($errors);
}
}
?>
Please make sure that you have given permission to images folder.
For more details refer this link.
Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
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 have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
Even if I select 2 or more images, only one gets uploaded.
I have a simple form:
<form action="/images/thumbs" method="post" enctype="multipart/form-data">
<input name="file[]" id="file" type="file" multiple="" />
<input type="submit" name="upload_images" value="Upload Images">
</form>
Then in my controller:
public function thumbsAction()
{
$request = $this->getRequest();
if ($request->isPost()) {
if (isset($_POST['upload_images'])) {
$names = $_FILES['file']['name'];
// the names will be an array of names
foreach($names as $name){
$path = APPLICATION_PATH.'/../public/img/'.$name;
echo $path; // will return all the paths of all the images that i selected
$uploaded = Application_Model_Functions::upload($path);
echo $uploaded; // will return true as many times as i select pictures, though only one file gets uploaded
}
}
}
}
and the upload method:
public static function upload($path)
{
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->addFilter('Rename', array(
'target' => $path,
'overwrite' => true
));
try {
$upload->receive();
return true;
} catch (Zend_File_Transfer_Exception $e) {
echo $e->message();
}
}
Any ideas why I get only one file uploaded?
Zend_File_Transfer_Adapter_Http actually has the information about the file upload. You just have to iterate using that resource:
$upload = new Zend_File_Transfer_Adapter_Http();
$files = $upload->getFileInfo();
foreach($files as $file => $fileInfo) {
if ($upload->isUploaded($file)) {
if ($upload->isValid($file)) {
if ($upload->receive($file)) {
$info = $upload->getFileInfo($file);
$tmp = $info[$file]['tmp_name'];
// here $tmp is the location of the uploaded file on the server
// var_dump($info); to see all the fields you can use
}
}
}
}