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 */
}
}
}
Related
I have this script for upload images, and I upload several images and get only one value:
In PHP/Laravel:
if ($request->hasFile('files')) {
$images = $request->file('files');
$array=[];
foreach($images as $key => $image) {
$filename = rand(1,99).'nameimage.'.$image->getClientOriginalExtension();
$array[] = $filename;
//upload images
}
return response()->json($array);
}
In script:
$.each(response, function (k,v){
console.log('Position: '+k+'. Value: '+v);
});
Result, for example: 'Position: 0. Value: 76nameimage.jpg ,
Why?
I have tried this manually;
if ($request->hasFile('files')) {
$images = $request->file('files');
//$array=[];
foreach($images as $key => $image) {
$filename = rand(1,99).'nameimage.'.$image->getClientOriginalExtension();
//$array[] = $filename;
//upload images
}
$array=array('1.jpg','2.jpg');
return response()->json($array);
}
$.each(response, function (k,v){
console.log('Position: '+k+'. Value: '+v);
});
It works fine, but can the problem be an array inside foreach?
What's the solution?
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,
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);
I am trying to get the last element of the request array in foreach loop that would look something like this:
array:5 [▼
0 => "files/uploads/articles/bear_PNG1183.png"
1 => "files/uploads/articles/bear_PNG1189.png"
2 => "files/uploads/articles/bear_PNG1188.png"
3 => "files/uploads/articles/bear_PNG1182 (1).png"
4 => "files/uploads/articles/bear_PNG1190.png"
]
But I can't use the end() function because then I get:
Only variables should be passed by reference
This is how foreach function looks like:
foreach ($request->get('uploadedItems') as $file) {
//make a new directory for the article and move all the uploaded files to it
$filePathArr = explode('/', $file);
$lastItem = array_pop($filePathArr);
array_push($filePathArr, $article->id, $lastItem);
$newPath = implode('/', $filePathArr);
$articleDirectory = $this->destinationPath.'/'.$article->id;
if(!File::exists($articleDirectory))
File::makeDirectory($articleDirectory, 0755, true);
File::move(public_path($file), public_path($newPath));
if(end($request->get('uploadedItems')) == $file){
dd($file);
}
Media::create(['path' => $newPath, 'article_id' => $article->id]);
}
Why call $request->get('uploadedItems') multiple times? Call it once and assign it to a variable before the loop or:
foreach ($files = $request->get('uploadedItems') as $file) {
if(end($files) == $file){
dd($file);
}
}
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];
...