How to request file with array name of input file? - php

Just wondering why I can't get value of array name from input type file.
HTML:
<input type="file" name="collateral_photo[]" id="collateral_photo" class="default"/>
The name of this input file is an array.
PHP Laravel
return Request::file('collateral_photo');
The return result is [{}]
What I want right now just how to get value from this input file with array name.
Please, please help me out.
Thank you very much for any help.

use the below code, since the name attribute is an array
$files = Request::file('collateral_photo');
return $files[0];
or if you want second file
return $files[1];
//if you want to access second file and so on
you need to access the file with array index specified.
If you want to return the whole files array itself then use
return $files

And going one step further we can work with multiple-level-arrays like so:
<input name="channel[1][file]" type="file">
<input name="channel[2][file]" type="file">
in laravel you would need a structure
$files = $request->file('channel');
$file1 = $files[1]['file'];
$file2 = $files[2]['file'];

If it is an array of files do:
$request()->file($fieldName)[$key]->getClientOriginalName();

Related

How to get file input name in Laravel?

I am using a jQuery form builder to create any kind of form input. The issue I had, in particular, is when I create multiple file inputs, the input name is generated randomly by default, the format is something like "file-0000-0". I would like to get the input name but since it's random, I can only think of one way to fetch the name which is by using the allFiles() method. How do I fetch the name of the input?
Code Example
$fileRequest = $request->allFiles();
return $fileRequest;
It will return something like this:
{file-1649657296668-0: {…}, file-1649657297967-0: {…}}.
Now how do I get both of the file input names above?
Thanks for the help.
Since allFiles() returns associative array you can get keys:
$files = $request->allFiles();
$name_of_files = array_keys($files);
// ["file-1649657296668-0", "file-1649657297967-0"]
Or you can loop through that array and access files as well:
$files = $request->allFiles();
foreach($files as $name_of_file => $file) {
echo $name_of_file; // file-1649657296668-0
// $file is UploadedFile instance
}

laravel | How to replace a field in form's request?

I am using laravel 5.4 and I'm trying to replace the imagePath field in my request (renaming the uploaded image).
explanation:
when the form is submitted the request field(request->imagePath) contains the temporary location of the uploaded image, I am moving that tmp image to a dir while changing its name ($name). so now as the request->imagePath still has old tmp image location I want to change request->imagePath value to have the new location and then create the user.
Like so
if($request->hasFile('imagePath'))
{
$file = Input::file('imagePath');
$name = $request->name. '-'.$request->mobile_no.'.'.$file->getClientOriginalExtension();
echo $name."<br>";
//tried this didn't work
//$request->imagePath = $name;
$file->move(public_path().'/images/collectors', $name);
$request->merge(array('imagePath' => $name));
echo $request->imagePath."<br>";
}
But Its not working, Here is the output
mahela-7829899075.jpg
C:\xampp\tmp\php286A.tmp
Please Help
I believe merge() is the correct method, it will merge the provided array with the existing array in the ParameterBag.
However, you're accessing the input variables incorrectly. Try using $request->input('PARAMETER_NAME') instead...
Therefore, your code should look like this:
if ($request->hasFile('imagePath')) {
$file = Input::file('imagePath');
$name = "{$request->input('name')}-{$request->input('mobile_no')}.{$file->getClientOriginalExtension()}";
$file->move(public_path('/images/collectors'), $name);
$request->merge(['imagePath' => $name]);
echo $request->input('imagePath')."<br>";
}
Note: You can also pass your path into public_path() and it will concatenate it for you.
References
Retrieving Input:
https://laravel.com/docs/5.4/requests#retrieving-input
$request->merge():
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Http/Request.php#L269
public_path: https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/helpers.php#L635

Getting File Name Details from Image File

I am looking for a way to grab details from a file name to insert it into my database. My issue is that the file name is always a bit different, even if it has a pattern.
Examples:
arizona-911545_1920.jpg
bass-guitar-913092_1280.jpg
eiffel-tower-905039_1280.jpg
new-york-city-78181_1920.jpg
The first part is always what the image is about, for example arizona, bass guitar, eiffel tower, new york city followed by a unique id and the width of the image.
What I am after would be extracting:
name id and width
So if I run for example getInfo('arizona-911545_1920.jpg');
it would return something like
$extractedname
$extractedid
$extractedwidth
so I could easily save this in my mysql database like
INSERT into images VALUES ('$extractedname','$extractedid','$extractedwidth')
What bothers me most is that image names can be longer, for example new-york-city-bank or even new-york-city-bank-window so I need a safe method to get the name, no matter how long it would be.
I do know how to replace the - between the name, that's not an issue. I am really just searching for a way to extract the details I mentioned above.
I would appreciate it if someone could enlighten me on how to solve this.
Thanks :)
One of the simplest way in this case is to use regexp, for example:
preg_match('/^(\D+)-(\d+)_(\d+)/', $filename, $matches);
// $matches[1] - name
// $matches[2] - id
// $matches[3] - width
This is the main Idea.
Let's pick a file first.
Filename will be "bass-guitar-913092_1280.jpg"
First of all we will Split this with explode, to dot( . ) in variable $Temp
This will give us an Array of bass-guitar-913092_1280 and jpg
We will choose to have the first Item of the array to continue since is the name we are interested in so we will get it with $Temp[0]
After this we will Split it Again this time to ( _ ).
Now we will have an array of bass-guitar-913092 and 1280
The Second value of the Array is what We need so we will pick it with $Temp[1]
The Last part is simple as the others, We will now Split the file name $Temp[0] with ( - ) We will get the Last value of it which is the id $Temp[count($Temp)-1] and we will remove this from the array list, and Connect everything else with implode and the delimeter we want
Now we can use also the Function ucwords to Capitalize every first letter of each word on the main name.
In the following code, there are 2 ways of getting the name, one with lowercase letters, and one with uppercase first letters of each word, uncomment what you want.
Edited Code as a Function
<?php
function ExtractFileInfo($fileName) {
$Temp = explode(".",$fileName);
$Temp = explode("_",$Temp[0]);
$width = $Temp[1];
$Temp = explode("-",$Temp[0]);
$id = $Temp[count($Temp)-1];
unset($Temp[count($Temp-1)]);
// If you want to have the name with lowercase letters Uncomment the Following:
//$name = implode(" ",$Temp);
// If you Want to Capitalize every first letter of the name Uncomment the Following:
//$name = ucwords(implode(" ",$Temp));
return array($name,$id,$width);
}
?>
This will return an Array of 3 Elements Name, Id and Width
Extracting the data you are looking for would be best via a regex pattern like the following:
(.+)-(\d+_(\d+))
Example here: https://regex101.com/r/oM5bS8/2
preg_match('(.+)-(\d+_(\d+))',"<filename>", $matches);
$extractedname = $matches[1];
$extractedid = $matches[2];
$extractedwidth = $matches[3];
EDIT - Just reread the question and you are looking for extraction techniques not how to post the image from a page to your backend. I will leave this here for reference.
When you post files via a form in html to a PHP backend there are few items that are needed.
1) You need to ensure that your form type is multi-part so that it knows to pass the files along.
<form enctype="multipart/form-data">
2) Your php backend needs to iterate over the files and save them accordingly.
Here is a sample of how to iterate over the files that are being submitted.
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
if (!$n) continue;
echo "File: $n ($s bytes)";
}

Counting sent files

I have an multiple input sending files and I need guard this images with another name inside my folder called 'home';
So the pictures filing with the name home1.jpg, home2.jpg, etc
So, here is my code:
$file = $_FILES['Filedata'];
$filename_home = "";
$img_array = array($filename);
foreach($img_array as $key=>$value){
$filename_home.="home".$key.".jpg";
}
But this doesn't producing the result.
Any help, will be appreciate
Where does $filename come from? It looks like you want to use $file instead.

how to insert value in a particular location in csv file using php

Is it possible to write at a particular location in a CSV file using PHP?
I don't want to append data at the end of the CSV file. But I want to add data at the end of a row already having values in the CSV.
thanks in advance
No, it s not possible to insert new data in the middle of a file, due to filesystem nature.
Only append at the end is possible.
So, the only solution is to make another file, write a beginning part of source, append a new value, and then append the rest of the source file. And finally rename a resulting file to original name.
There you go. Complete working code:
<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
$array2 = array_splice($array, $pos);
$array[] = $val;
$array = array_merge($array, $array2);
return $array;
}
//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;
//Full path & Name of the CSV File
$FileName = 'data.csv';
//Read the file and get is as a array of lines.
$arrLines = file($FileName);
//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);
//Convert result array to string.
$ResultStr = implode("\n", $Result);
//Write to the file.
file_put_contents($FileName, $ResultStr);
?>
Technically Col. Shrapnel's answer is absolutely right.
Your problem is that you don't want to deal with all these file operations just to change some data. I agree with you. But you're looking for the solution in a wrong level. Put this problem in a higher level. Create a model that represents an entity in your CSV database. Modify the model's state and call its save() method. The method should be responsible to write your model's state in CSV format.
Still, you can use a CSV library that abstracts low level operations for you. For instance, parsecsv-for-php allows you to target a specific cell:
$csv = new parseCSV();
$csv->sort_by = 'id';
$csv->parse('data.csv');
# "4" is the value of the "id" column of the CSV row
$csv->data[4]['firstname'] = 'John';
$csv->save();

Categories