I need to upload multiple files in laravel 4
I have written the following code in controller
public function post_files()
{
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'upload/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000))
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess )
{
$document_details=Response::json(Author::insert_document_details_Call($filename,$destinationPath));
return $document_details; // or do a redirect with some message that file was uploaded
}
else
{
return Response::json('error', 400);
}
}
}
}
else
{
return "Invalid file";
}
}
}
I am able to upload a single file via this code but not able to upload multiple files.
Please help me in this isue..Thank you in advance..
public function post_abc()
{
// $file = Input::file('file'); // your file upload input field in the form should be named 'file'
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf","docx","xls","xlsx");
foreach($_FILES['file'] as $key => $abc)
{
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'abc/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000))
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
if (file_exists($destinationPath))
{
echo $filename." already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess )
{
return "hello";
}
else
{
return Response::json('error', 400);
}
}
}
}
}
Using postman rest client on google chrome I have passed key as 'file' and value as '3 files selected' and input type is file
Call This part into a loop
if(in_array($extension, $allowedExts)&&($_FILES["file"]["size"] < 20000000))
{
if($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["file"]["tmp_name"],$destinationPath);
if( $uploadSuccess )
{
$document_details=Response::json(Author::insert_document_details_Call($filename,$destinationPath));
return $document_details; // or do a redirect with some message that file was uploaded
}
else
{
return Response::json('error', 400);
}
}
}
}
else
{
return "Invalid file";
}
Issue solved. I changed the code as follows in the controller:
public function post_multiple()
{
// $file = Input::file('file'); // your file upload input field in the form should be named 'file'
$allowedExts = array("gif", "jpeg", "jpg", "png","txt","pdf","doc","rtf","docx","xls","xlsx");
if(isset($_FILES['image']['tmp_name']))
{
$i=0;
foreach(Input::file('image') as $key => $file)
{
$temp = explode(".", $_FILES["image"]["name"][$i]);
$extension = end($temp);
$filename= $temp[0];
$destinationPath = 'abc/'.$filename.'.'.$extension;
if(in_array($extension, $allowedExts)&&($_FILES["image"]["size"][$i] < 20000000))
{
if($_FILES["image"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["image"]["error"][$i] . "<br>";
}
if (file_exists($destinationPath))
{
echo $filename." already exists. ";
}
else
{
$uploadSuccess=move_uploaded_file($_FILES["image"]["tmp_name"][$i],$destinationPath);
if( $uploadSuccess )
{
$name=$filename.".".$extension;
$document_details=Response::json(Author::insert_document_details_Call($name,$destinationPath));
echo "Update";
}
else
{
return Response::json('error', 400);
}
}
}
$i++;
}
}
}
And in View part I had written name=image instead of image[]
Related
I cannot upload the images while using angular and php using this code.
please assist..
I got an error undefined index error on line 2 from php
angular side
const formData = new FormData();
formData.append('date', this.uploadRequest.date.toString());
formData.append('description', this.uploadRequest.description);
formData.append('title', this.uploadRequest.title);
this.imageDetails.forEach((image, i) => {
formData.append('images[' + i + ']', image.file);
});
const params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', '/api/upload', formData, options);
return this.http.request(req).subscribe();
php side
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if (!empty($_FILES['image'])) {
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
$uploadOk = 1;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = time() . '.' . $ext;
move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' .
$image);
echo "Image uploaded successfully as " . $image;
} else {
echo "Image Is too Large";
}
} else {
echo "Image Is Empty";
}
You need to put your code inside the if statement. You are trying to execute a code before the if statement is ran and that code is crucial for the if statement to function properly.
if (!empty($_FILES['image'])) {
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
$uploadOk = 1;
$ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$image = time() . '.' . $ext;
move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' .
$image);
echo "Image uploaded successfully as " . $image;
} else {
echo "Image Is too Large";
}
} else {
echo "Image Is Empty";
}
i have a function to upload a file(video,audio, images and documents) .. but i cant think of how to continue it.. I'm a beginner in programming by the way. and i want to upload a file and check the limit of the folder where i want to save the file if the folder reached the limit of 10 000 file inside, if it is true then it will create a new folder that has the same name but has a number in it (folder,folder 1 will be the next created) and save it to the folder created..
function uploads($filename,$tempname){
$errors= array();
$file_name = $filename;
$file_tmp = $tempname;
$audioPath = "./archivestorage/upload/media/audio/";
$videoPath = "./archivestorage/upload/media/video/";
$imagePath = "./archivestorage/upload/media/images/";
$documentPath = "./archivestorage/upload/document/";
$file = pathinfo($filename,PATHINFO_EXTENSION);
if(empty($errors)==true) {
if($file ==='jpg')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='mp4')
{
move_uploaded_file($file_tmp,$videoPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='mp3')
{
move_uploaded_file($file_tmp,$audioPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='jpeg')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else if($file ==='docx')
{
move_uploaded_file($file_tmp,$documentPath.$file_name);
echo "Success";
$return = $imagePath;
}
elseif($file ==='png')
{
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
print_r($errors);
}
}
i am giving you simple demonstration here.may be its not correct as per your need. remember class FilesystemIterator will work if your php version is above 5.3
if($file ==='jpg')
{
$folderChk = new FilesystemIterator($imagePath, FilesystemIterator::SKIP_DOTS)
if (iterator_count($folderChk)<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
$imagePath=$imagePath." 1 " ;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
}
if its not work you can use glob() try like that
if($file ==='jpg')
{ $filecount = 0;
$files = glob($imagePath . "*");
if ($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else{
$imagePath=$imagePath." 1 " ;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
}
if you want to create multiple folder you should try like this
$imagePath = "./archivestorage/upload/media/images/";
$folderCount = 0;
$folder = scandir($imagePath);//read directory
if ($folder){
$folderCount = count($folder)-2;//count dir
}
$file = pathinfo($filename,PATHINFO_EXTENSION);
if(empty($errors)==true) {
if($file ==='jpg')
{
$filecount = 0;
if (is_dir($imagePath)) {
$files = glob($imagePath . "*");
if($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
}
else
{
for ($i = 1; $i <=$folderCount ; $i++) {
if(is_dir($imagePath." ".$i)) {
$imagePath=$imagePath." ".$i;
$files = glob($imagePath . "*");
if ($files){
$filecount = count($files);
}
if ($filecount<10000) {
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
exit();
}
}
else
{
$imagePath=$imagePath." "$i;
mkdir($imagePath, 0777, true);
move_uploaded_file($file_tmp,$imagePath.$file_name);
echo "Success";
$return = $imagePath;
exit();
}
}
}
}
}
}
function addFlyer($db) {
if (isset($_FILES['file_array'])) {
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for ($i = 0; $i < count($tmp_name_array); $i++) {
if (file_exists($name_array[$i])) {
echo "Sorry file already exists. ";
$uploadOk = 0;
}
else {
if (move_uploaded_file($tmp_name_array[$i], "images/" . $name_array[$i])) {
echo $name_array[$i] . " upload is complete<br>";
} else {
echo "move_uploaded_file function failed for " . $name_array[$i] . "<br>";
}
}
}
}
At the moment I got this code for upload multiple files to a folder and insert it into the database (I excluded the code for inserting.)
But if I want to use the file_exists function correctly I need to seperate the extension and the name from the file. But I have no idea how I can explode an array.
Is there someone that can help me with this?
You don't need to explode or something else. You could get image extension by path_info() PHP Function. PLease have a look on below.
$path = $_FILES['file_array']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
If you want to explode a file name. You can use below trick
$file = $_FILES['file_array']['name'];
$image_info = explode(".", $file);
$image_type = end($image_info)
foreach ($name_array as $value) {
if (file_exists($value)) {
echo "Sorry file already exists. ";
$uploadOk = 0;
} else {
if (move_uploaded_file($value, "images/" . $value)) {
echo $value . " upload is complete<br>";
} else {
echo "move_uploaded_file function failed for " . $value . "<br>";
}
}
}
This may work. Use foreach() loop instead of for() loop.
I'm trying upload multiple images. Below you can see my code.
Image uploaded massage repenting (exactly the amount of image chosen to upload.)
How can i show "Image uploaded" massage only ones on successful submit?
If i put the message after the loop it will start to show no matter if there is any errors.
This is my PHP code:
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats))
{
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
echo "Image uploaded";
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>';
}
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
}
}
?>
Any help will be appropriated.
You can implement a counter and when an upload completes successfully you can increment that counter variable then compare it against total number of array items after foreach loop completes. I modified your code for this (haven't checked it but should work).
<?php
error_reporting(0);
session_start();
include('db.php');
$id = $mysqli->escape_string($_GET['id']);
define ("MAX_SIZE","9000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "gallery/"; //a directory inside
$successfulUploads = 0;
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//get the extension of the file in a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
if(in_array($ext,$valid_formats)) {
if ($size < (MAX_SIZE*1024)) {
$image_name=time().$filename;
$newname=$uploaddir.$image_name;
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname)) {
$mysqli->query("INSERT INTO galleries(image) VALUES('$image_name')");
//echo "Image uploaded";
$successfulUploads = $successfulUploads + 1;
} else {
echo '<span class="imgList">Moving unsuccessful! </span>';
}
} else {
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
} else {
echo '<span class="imgList">Unknown extension!</span>';
}
}
if($successfulUploads === count($_FILES['photos'])){
echo 'UPLOAD SUCCESS!';
} else {
echo 'NOT ALL IMAGES WERE UPLOADED SUCCESSFULLY';
}
}
*If you wanted to get more complex with it you could create another array variable instead of a counter and if the upload fails you could add the file name to the array and then check the length of the array where I'm doing the comparison. If count > 0 then you would know there was an error and you could echo the filenames that failed to upload
I am creating an application of uploading swf files in a folder using PHP.
My script is all working except for the first if condition where I'm checking whether the extension is swf or not, but I seems to have some error.
I'm not sure whether video/swf is a valid checking parameter for SWF files or not. My full script is below. I'm checking the size of the SWF using getimagesize(). Some people may wonder that getimagesize works for image, but I saw some examples where getimagesize() has been used for getting size of SWF files.
It's giving me the message "invalid swf file", that means its not satisfying the first checking condition at all.
<?php
foreach($_FILES['item_swf']['tmp_name'] as $key=>$val)
{
list($width, $height) = getimagesize($_FILES['item_swf']['tmp_name'][$key]);
if (( ($_FILES["item_swf"]["type"][$key] == "video/swf") || ($_FILES["item_swf"]["type"][$key] == "video/SWF") )
&& ($_FILES["item_swf"]["size"][$key] < 800000))
{
if ($_FILES["item_swf"]["error"][$key] > 0)
{
echo "Error: " . $_FILES["item_swf"]["error"][$key] . "<br />";
}
else if($width==1000 && $height==328)
{
if (file_exists('../../swf_folder/header_swf/' . $_FILES["item_swf"]["name"]))
{
echo $_FILES["item_swf"]["name"][$key] . " already exists. ";
}
else
{
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
echo "done";
}
}
else
{
echo "size doest permit";
}
}
else
{
echo "Not a valid swf file::";
}
}
?>
The line given below
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
is working perfectly as it is uploading files to the dedicated folder, it somehow seems that the checking parameters for SWF only files are not set properly.
Edit
I got my answer. Instead of using video/swf I need to use application/x-shockwave-flash.
So the ultimate code will be:
<?php
foreach($_FILES['item_swf']['tmp_name'] as $key=>$val)
{
list($width, $height) = getimagesize($_FILES['item_swf']['tmp_name'][$key]);
if (($_FILES["item_swf"]["type"][$key] == "application/x-shockwave-flash")
&& ($_FILES["item_swf"]["size"][$key] < 800000))
{
if ($_FILES["item_swf"]["error"][$key] > 0)
{
echo "Error: " . $_FILES["item_swf"]["error"][$key] . "<br />";
}
else if($width==1000 && $height==328)
{
if (file_exists('../../swf_folder/header_swf/' . $_FILES["item_swf"]["name"]))
{
echo $_FILES["item_swf"]["name"][$key] . " already exists. ";
}
else
{
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
echo "done";
}
}
else
{
echo "size doest permit";
}
}
else
{
echo "Not a valid swf file::";
}
}
?>
you can try
$savePath = "PATH_TO_SAVE";
$errors = array ();
$output = array ();
//
if (isset ( $_FILES ['item_swf'])) {
foreach ( $_FILES ['item_swf'] ['tmp_name'] as $key => $val ) {
$fileName = $_FILES ['item_swf'] ['name'] [$key];
$fileSize = $_FILES ['item_swf'] ['size'] [$key];
$fileTemp = $_FILES ['item_swf'] ['tmp_name'] [$key];
$fileExtention = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExtention = strtolower ( $fileExtention );
if ($fileExtention != ".swf") {
$errors [$fileName] [] = "Invalid File Extention";
continue;
}
if ($fileSize > 800000) {
$errors [$fileName] [] = "File Too large";
continue;
}
list ( $width, $height ) = getimagesize ( $fileTemp );
if ($width != 1000 && $height != 328) {
$errors [$fileName] [] = "Wrong File dimention ";
continue;
}
if (file_exists ( $savePath . DIRECTORY_SEPARATOR . $fileName )) {
$errors [$fileName] [] = "File Exist";
continue;
}
if(!is_writable($savePath ))
{
$errors [$fileName] [] = "File Destination not writeable";
}
if(count($errors [$fileName]) == 0)
{
if(#move_uploaded_file ( $fileTemp, $savePath . DIRECTORY_SEPARATOR . $fileName))
{
$output[$fileName] == "OK" ;
}
else
{
$errors [$fileName] [] = "Error Saving File";
}
}
}
var_dump($errors, $output);
}
Let me know if you have any more challenge
ok, i got my answer....
instead of using video/swf i need to use application/x-shockwave-flash
so the ultimate code will be
<?php
foreach($_FILES['item_swf']['tmp_name'] as $key=>$val)
{
list($width, $height) = getimagesize($_FILES['item_swf']['tmp_name'][$key]);
if (( ($_FILES["item_swf"]["type"][$key] == "application/x-shockwave-flash") || ($_FILES["item_swf"]["type"][$key] == "video/SWF") )
&& ($_FILES["item_swf"]["size"][$key] < 800000))
{
if ($_FILES["item_swf"]["error"][$key] > 0)
{
echo "Error: " . $_FILES["item_swf"]["error"][$key] . "<br />";
}
else if($width==1000 && $height==328)
{
if (file_exists('../../swf_folder/header_swf/' . $_FILES["item_swf"]["name"]))
{
echo $_FILES["item_swf"]["name"][$key] . " already exists. ";
}
else
{
move_uploaded_file($val, '../../swf_folder/header_swf/'.$_FILES['item_swf']['name'][$key]);
echo "done";
}
}
else
{
echo "size doest permit";
}
}
else
{
echo "Not a valid swf file::";
}
}
?>