looping through multiple file upload indexes - php

I am trying to get the name and size index of all uploaded files but I can't get it work. it works like this:
foreach ($_FILES['file']['name'] as $key => $file){
echo $file;
}
but if I want to echo multiple indexes in the same loop, i tries this, but I get "undefined index 'name' and 'size'" warnings. What am I doing wrong? thanks
foreach ($_FILES['file'] as $key => $file){
echo $file['name'].
$file['size'];
}
<input name ="file[]" type = "file" multiple />

function handle_image_upload($frmFilesID = false, $thisFile = false) {
$tmpName = $_FILES["$frmFilesID"]['tmp_name'][$thisFile];
if (!is_uploaded_file($tmpName)) { return false; }
$fileName = $_FILES["$frmFilesID"]['name'][$thisFile];
$fileSize = $_FILES["$frmFilesID"]['size'][$thisFile];
$fileType = $_FILES["$frmFilesID"]['type'][$thisFile];
...

Related

how to multiple image in laravel 8?

I tried the following code but an error occurs when I run the project
$files = $request->file('files');
if($request->hasFile('files'))
{
foreach ($files as $file) {
$path = $file->store('public/gallery');
ProductGallery::create([
'products_id' => $product->id,
'url' => $path
]);
}
}
Upon using hasFile on an array it seems that it only checks the first element from the array. If the first element of your files array is empty, the result will always be false. A workaround to your problem is:
$files = $request->file('files');
if(count($request->file('files')) > 0)
{
foreach ($files as $file) {
if ($file->isValid()) {
/* Write your file upload code here */
}
}
}

How to display images(.jpg) only?

Array ( [0] => assets/image/man.jpg [1] => assets/image/violin.jpg [2] => assets/image/test.txt )
The data from data base is like above.It contain images and txt.how can i display only images.
$ar = ['assets/image/man.jpg','assets/image/violin.jpg','assets/image/test.txt'];
$allowed = ['jpg']; //your image extensions
$img_ar = [];
foreach($ar as $img){
$ext = pathinfo($img,PATHINFO_EXTENSION);
if(in_array($ext,$allowed)){
$img_ar[] = $img;
}
}
print_r($img_ar);
$array= Array ( [0] => assets/image/man.jpg [1] => assets/image/violin.jpg [2] => assets/image/test.txt )
$m_array = preg_grep('/^.jpg\s.*/', $array);
$m_array contains matched elements of array.
For more detail have look at this thread search a php array for partial string match
For this you can directly filter it when you are querying like
field like '%.jpg'
If you don't want to do that and manipulate the array you can use array_filter like,
$array= Array ('assets/image/man.jpg', 'assets/image/violin.jpg', 'assets/image/test.txt');
$output = array_filter($array, function($arr) {
if (strpos($arr, '.jpg') == true){
return $arr;
}
});
$output array contains only the entries which having the .jpg string.
Here am using strpos to check .jpg exists or not.
you maybe use substr($str, -4) == '.jpg' to check the last 4characters.
If you are using PHP 5+ (which I hope you are on 7.0+), use SplFileInfo() class
$spl = new SplFileInfo($fileName);
if ($spl->getExtension() == 'jpg') {
//image
}
Use foreach loop and get an extension of the file and display.
foreach($array_result as $result){
//$array_result is array data
//condition is checking the file that if it is an image or not
$allowed = array('gif','png' ,'jpg');
$filename = $result;
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext, $allowed) ) {
echo '<img src="'.$result.'" alt="" /> ';
}
}
This should do the trick:
$images = array();
$images_exts = array('.jpg','.png');
foreach($db_array as $key => $value)
{
foreach($images_exts as $ext)
{
if (strpos($value,$ext))
{
$images[] = $value;
}
}
}
Here is an example https://3v4l.org/8W3Be
And here is another way, whatever you like the most:
$images = array();
$images_exts = array('jpg','png');
foreach($input as $value)
{
if(in_array(#end(explode('.', $value)), $images_exts))
{
$images[] = $value;
}
}
Here is an example https://3v4l.org/b0njd
Why do you check it when you want write it on page?
You can:
1. split assets/image/man.jpg with '/'
2. get last one,
3. split last one with '.'
4. get extension and if it was 'jpg' write it to page.
<?php
$error = array();
$file_extArr = explode(".", $file_name);
$file_extEnd = end($file_extArr);
$file_ext = strtolower($file_extEnd);
$validateImage = array("png", "jpg", "jpeg", "gif");
if (!in_array($file_ext, $validateImage)) {
$error[] = "wrong format image";
}
if (!empty($error)) {
return;
}
?>
<?php
$data = Array (
'assets/image/man.jpg ',
'assets/image/violin.jpg ',
'assets/image/test.txt ',
);
$arrDara = array();
foreach ($data as $value) {
$fileName = explode('/', $value);
$arrDara[] = end($fileName);
}
print_r($arrDara);
?>
Just loop your array and explode every sting. the last index is what all you need.

php copy file for each filename in array

I am trying to move all the files in my array from one directory to another.
I have done some research and are using the php Copy() function.
here is my code so far:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = print_r($myArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
for($i = 0;$i < count($finalArray);$i++){
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);}
}
Anyone see where I'm going wrong?
Thanks in advance!
This is the unlink ive been attempting to use.
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
}
// Delete all successfully-copied files
foreach ( $delete as $file ) {
unlink( $sourcePath.$file );
}
My Final Working Code
the code below moves images in comma seperated array to new folder and removes them from current folder
$finalArray = explode(',', $filenameArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
}
}
copyFiles( $finalArray, $sourcePath, $savePath);
function removeFiles($finalArray,$sourcePath) {
foreach ($finalArray as $file){
if (!unlink($sourcePath.$file)) {
echo "Failed to remove image";
}
}
}
removeFiles( $finalArray, $sourcePath);
In your code you are not calling the copyFile function. Try this:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
function mvFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!rename($sourcePath.$file,$savePath.$file)) {
echo "failed to copy $file...\n";
}
}
}
mvFiles( $finalArray, $sourcePath, $savePath);
A simple solution :
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = $myArray; //corrected this line
function copyFiles($finalArray, $sourcePath, $savePath)
{
for ($i = 0; $i < count($finalArray); $i++)
{
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);
}
}
Hope you have right call to function copyFiles().
UPDATE for unlink() :
Let me try to throw some light on your work (written code):
foreach ($finalArray as $file)
{
if (!copy($sourcePath.$file,$savePath.$file))
{
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
Contents of $delete :
a. /source/img1.png
b. /source/img2.png
c. /source/img3.png
Now,
foreach ( $delete as $file )
{
unlink( $sourcePath.$file );
}
unlink() will be called with the following parameters:
$sourcePath.$file : /source/./source/img1.png : /source//source/img1.png => No such path exists
$sourcePath.$file : /source/./source/img2.png : /source//source/img2.png => No such path exists
$sourcePath.$file : /source/./source/img3.png : /source//source/img3.png => No such path exists
$sourcePath.$file : /source/./source/img4.png : /source//source/img4.png => No such path exists
I think for this reason, unlink is not working.
The code to be written should be like the following:
foreach ( $delete as $file )
{
unlink( $file );
}
Now, unlink() will be called with the following parameters:
a. /source/img1.png => path do exists
b. /source/img2.png => path do exists
c. /source/img3.png => path do exists
Do tell me if this does not solves the issue.
Update as per Dave Lynch's code:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
foreach ($finalArray as $file)
{
$delete[] = $sourcePath.$file;
}
foreach ( $delete as $file )
{
echo $sourcePath.$file . "</br>";
}
Output:
/source//source/img1.png
/source//source/img2.png
/source//source/img3.png
Please check.
Thanks and Regards,

Sort Images by Date Modified

I have a small script that puts images from a folder into a web page.
I would like to sort by DATE MODIFIED anyone know how to do this?
function php_thumbnails($imagefolder,$thumbfolder,$lightbox)
{
//Get image and thumbnail folder from function
$images = "portfolio/" . $imagefolder; //The folder that contains your images. This folder must contain ONLY ".jpg files"!
$thumbnails = "portfolio/" . $thumbfolder; // the folder that contains all created thumbnails.
//Load Images
//load images into an array and sort them alphabeticall:
$files = array();
if ($handle = opendir($images))
{
while (false !== ($file = readdir($handle)))
{
//Only do JPG's
if(eregi("((.jpeg|.jpg)$)", $file))
{
$files[] = array("name" => $file);
}
}
closedir($handle);
}
//Obtain a list of columns
foreach ($files as $key => $row)
{
$name[$key] = $row['name'];
}
//Put images in order:
array_multisort($name, SORT_ASC, $files);
//set the GET variable name
$pic = $imagefolder;
You need to use filemtime function to retrieve the files modification time, and then use it to build your multisort help array.
...
if(eregi("((.jpeg|.jpg)$)", $file))
{
$datem = filemtime($images . '/' . $file);
$files[] = array("name" => $file, "date" => $datem);
}
}
...
...
...
foreach ($files as $key => $row)
{
$date[$key] = $row['date'];
}
//Put images in order:
array_multisort($date, SORT_ASC, $files);

Multiple files uploading not working in Codeigniter

While uploading the multiple files in codeigniter i am getting error like this,
Fatal error: Unsupported operand types in .../system\libraries\Upload.php
if(isset($_FILES['med_file']))
{
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
$this->load->library('upload', $config);
$files = $_FILES;
$cpt = count($_FILES['med_file']['name']);
for($i=0; $i<$cpt; $i++)
{
if($files['med_file']['name'][$i] !="")
{
$_FILES['med_file']['name']= $files['med_file']['name'][$i];
$_FILES['med_file']['type']= $files['med_file']['type'][$i];
$_FILES['med_file']['tmp_name']= $files['med_file']['tmp_name'][$i];
$attachment_name=$files['med_file']['name'][$i];
$path_info=pathinfo($attachment_name);
$file_extension=#$path_info['extension'];
$path_part_filename=$path_info['filename'];
$rename_file=str_replace(" ","",$path_part_filename).'_'.date('Ymdhis');
if(!empty($rename_file))
{
$_FILES['med_file']['name'] = $rename_file.'.'.$file_extension;
$medical_history_files[]=$rename_file.'.'.$file_extension;
if($this->upload->do_upload('med_file'))
{
$file_upload='true';
}
else if(!$this->upload->do_upload('med_file'))
{
$file_upload="fail";
$error= $this->upload->display_errors();
$this->session->set_flashdata('sucess', $error);
}
}
}
}
}
}
and my view page code is like this.
<form method="post" name="medicalhistory" id="medicalhistory"
enctype="multipart/form-data">
<input id="med_file" type="file" name="med_file[]" multiple>
</form>
Please help me how to solve this problem. Thanks
You missed a couple of things here.. First of all, your HTML form should have the attribute action pointing to your controller method. Second, the $_FILES array should always contain the following: name, type, tmp_name, error, size, however, in your loop you are only rebuilding with name, type, tmp_name, and you are forgetting the others. You are also renaming the file prior its being sent to the upload library. You should do this by setting it in the config array that is being sent to the library. I would redo you code in the following manner:
Step 1: Make sure the HTML form has the action attribute:
<form action="<?= base_url()?>controller/upload" ..
Step 2: Retrieve the files and unset the original $_FILES so that you can rebuild the array:
$uploaded_files = $_FILES['med_file'];
unset($_FILES);
Step 3: loop through the obtained files and rebuild the $_FILES array into a multidimensional array:
foreach ($uploaded_files as $desc => $arr) {
foreach ($arr as $k => $string) {
$_FILES[$k][$desc] = $string;
}
}
Step 4: Load the Upload library, and set your config options
$this->load->library('upload');
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
Step 5: Loop through the new $_FILES array, rename you file and set the config['filename'] to the new name. Initialize your upload, then run it:
foreach ($_FILES as $k => $file) {
$path_info = pathinfo($file["name"]);
$file_extension = $path_info['extension'];
$path_part_filename = $path_info['filename'];
$config['file_name'] = str_replace(" ", "", $path_part_filename) . '_' . date('Ymdhis') . '.' . $file_extension;
$this->upload->initialize($config);
if (!$this->upload->do_upload($k)) {
$errors = $this->upload->display_errors();
var_dump($errors);
} else {
var_dump("success");
}
}
FINAL RESULT:
View:
<form action="<?= base_url()?>controller/upload" method="post" id="medicalhistory" enctype="multipart/form-data">
<input id="med_file" type="file" name="med_file[]" multiple>
<input type="submit">
</form>
Controller:
public function upload() {
$uploaded_files = $_FILES['med_file'];
unset($_FILES);
foreach ($uploaded_files as $desc => $arr) {
foreach ($arr as $k => $string) {
$_FILES[$k][$desc] = $string;
}
}
$this->load->library('upload');
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
foreach ($_FILES as $k => $file) {
$path_info = pathinfo($file["name"]);
$file_extension = $path_info['extension'];
$path_part_filename = $path_info['filename'];
$config['file_name'] = str_replace(" ", "", $path_part_filename) . '_' . date('Ymdhis') . '.' . $file_extension;
$this->upload->initialize($config);
if (!$this->upload->do_upload($k)) {
$errors = $this->upload->display_errors();
var_dump($errors);
} else {
var_dump("success");
}
}
}

Categories