Looping through image array and moving them - Laravel - php

I have a form which has 5 file inputs to create an array of images.
When processing, I wish to loop through the images and process them.
$images = Input::get('images');
// image proccessing
foreach ($images as $image) {
print_r($image);
}
That will output the file name, but If I call the move function on the $image variable I get "method move called on string".
How should I be doing this?

You should be doing something like this
$input = Input::file('files'); //get file as input
//check if input has file
if ($input){
foreach($input as $key){
//loop through file and perform action...
$array = Image::file_upload($key, 'file', 'Images');
// I assume you have your method for upload like the above
$key = $array['filename'];
print_r($key);
}
}
$this->image->save($input); //save to db file name.

Related

How to retrive single field array data from database and separate them- using laravel, PHP

I Trying to upload multiple image for my product, and store the names of that images in database as an array.
My code works like this-
$images = $request->file('images');
if (isset($images)) {
foreach($images as $image){
$imagename = $slug.'-'.$currentDate.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if (!file_exists('uploads/product/images')) {
mkdir('uploads/product/images', 0777, true);
}
$image->move('uploads/product/images', $imagename);
$data[] = $imagename;
}
}else{
$data[] = 'default.png';
}
$product = new Product();
$product->images = json_encode($data);
And data stored inside the images field like-
["jeans-2020-08-13-5f352f18b30a4.jpg","jeans-2020-08-13-5f352f18b36a0.jpg","jeans-2020-08-13-5f352f18b3a2c.jpg"]
**And the problem is how can i separate this image name to show images in Laravel Blade? **
OR Suggest me, If there is another way to upload multiple image or multiple value in laravel-6
You need to deserialize the images names and then loop through them:
#foreach(json_decode($product->images) ?? [] as $image)
<img src="uploads/product/images/{{ $image }}">
#endforeach

get random background image using php

I want to get a random background image using php. Thats done easy (Source):
<?php
$bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' );
$i = rand(0, count($bg)-1);
$selectedBg = "$bg[$i]";
?>
Lets optimize it to choose all background-images possible inside a folder:
function randImage($path)
{
if (is_dir($path))
{
$folder = glob($path); // will grab every files in the current directory
$arrayImage = array(); // create an empty array
// read throught all files
foreach ($folder as $img)
{
// check file mime type like (jpeg,jpg,gif,png), you can limit or allow certain file type
if (preg_match('/[.](jpeg|jpg|gif|png)$/i', basename($img))) { $arrayImage[] = $img; }
}
return($arrayImage); // return every images back as an array
}
else
{
return('Undefine folder.');
}
}
$bkgd = randImage('image/');
$i = rand(0, count($bkgd)-1); // while generate a random array
$myRandBkgd = "$bkgd[$i]"; // set variable equal to which random filename was chosen
As I am using this inside a wordpress theme, I need to set the $bkgd = randImage('image/'); relative to my theme folder. I thought, I could do that using:
$bgfolder = get_template_directory_uri() . '/images/backgrounds/';
bkgd = randImage($bgfolder);
When I test $bgfolder, which seems to be the most important part, using var_dump() I receive a not working path:
http://yw.hiamovi-client.com/wp-content/themes/youthwork string(19) "/images/backgrounds"
Somehow there is a space before the /images/backgrounds/. I have no idea where this comes from! …?
You'll want to change
$myRandBkgd = "$bkgd[$i]";
to
$myRandBkgd = $bkgd[$i];
If that doesn't help, use var_dump() instead of echo() to dump some of your variables along the way and check if the output corresponds to your expectations.

Laravel sorting empty input

I am building a image upload in Laravel but I keep getting an error inside my foreach loop if one filed is empty.
My upload allows multible images[], so if one field is empty I get an error but I want to allow users to choose if they want to upload eg 2 or 5 images
$input = Input::all();
//Validation
File::exists($path) or File::makeDirectory($path);
foreach($input['images'] as $file) {
$image = Image::make($file->getRealPath()); //getRealPath gives me an error if not all images[] fields from post data containts an image
}
So how can I sort my input images[] from empty inputs?
Thanks in advance,
If I understood well you need something like this:
if(empty($file)) {
unset($file);
}
or something like this:
if(!empty($file)){
$image = Image::make($file->getRealPath());
}
Try checking whether $file has a non-null value before running getRealPath
File::exists($path) or File::makeDirectory($path);
foreach($input['images'] as $file) {
if($file) {
$image = Image::make($file->getRealPath());
}
}
By the way, $image is reset with every iteration. Is that really what you want? Do you care which $image you get?
You can use array_filter() with no callback to remove all elements that have a falsy value:
$input = array_filter($input);
foreach($input['images'] as $file) {
$image = Image::make($file->getRealPath());
}
What I did to solve it was to add if check within my foreach loop and it worked. But im not sure if this is the best solution?
$input = Input::all();
foreach($input['images'] as $file) {
if($file == ""){ //If one input is empty it jumps over it, instead of trying to use getRealPath() on an empty value
break;
}
$image = Image::make($file->getRealPath());
}

php upload file into the folder

I am trying to upload multiple images into the folder using php . The code can print out the file names which means I get the files but now it does not upload them and I get no error : below is my code
<?php
$target = "image_uploads/";
if(isset($_FILES['FILE_NAME'])){
foreach($_FILES['FILE_NAME']['tmp_name']as $key => $error ){
print_r($key);
$file_upload = $key.$_FILES['FILE_NAME']['name'][$key];
#print image names
echo $file_upload.'</br>';
move_uploaded_file($file_upload,$target);
}
}
?>
In target you have to give the file name too. Please use the code below,
$target = "image_uploads/";
if(isset($_FILES['FILE_NAME'])){
foreach($_FILES['FILE_NAME']['tmp_name'] as $key => $error ){
print_r($key);
$file_upload = $key.$_FILES['FILE_NAME']['name'][$key];
print image names
echo $file_upload.'</br>';
move_uploaded_file($file_upload,$target.$_FILES['FILE_NAME']['name']);
}
}
I think the problem is in the foreach loop.
foreach ($_FILES['FILE_NAME']['tmp_name'] as $key => $val) {
// this loops through the tmp_name of $_FILES['FILE_NAME']
// which is a string
}
I think you meant something like:
foreach ($_FILES as $index => $fileArray) {
$tmpName = $fileArray['tmp_name'];
echo "File at key $index is temporarily uploaded at $tmpName";
}
The code above will loop through all uploaded files and print it's current filename.
It might happen that your target folder is not writable.
I also think, that the cause of which you're not getting errors is, that you have the following:
print_r($key);
Yous should have:
print_r($error);
There can be multiple reasons for this :
The target folder must exist before trying to move the file from temp location to the target and must also be writable
the move_uploaded_file takes the second argument as the file name followed by the directory name, so it can be something like : target folder/user.file.name.ext
If you are uploading multiple files, then the $_FILES must be accessed as shown in the link : http://php.net/manual/en/features.file-upload.multiple.php
for the php error messages that you may encounter, here is a list : http://php.net/manual/en/features.file-upload.errors.php

Arrays from multiple upload form, Upload images then insert to database (PHP, MySQL)

Language: PHP / MySQL
I am going out of my mind, I really have to ask now... I have a multiple file upload form:
<input type="file" name="fileupload[]" multiple>
With the help of some Javascript, on each change made to this input, it appends a list of filenames, + a formatted string (grabbed from the filename) inside another input, so onchange we have a layout as shown below (assuming that we just added some images):
Almost similar to: http://jsfiddle.net/pxfunc/WWNnV/4/
// An HTML representation of such layout would be... (assuming that we added 3 images)
<input type="file" name="fileupload[]" multiple>
image-name-1.jpg <input type="text" value="Image Name 1" name="keyword[]">
justsome_file.png <input type="text" value="Justsome File" name="keyword[]">
some_Img-031.gif <input type="text" value="Some Img 031" name="keyword[]">
<input type="submit" value="Upload">
I have it this way because aside from uploading the files, I would also like to add them to my database, with a default title based on its filename (and the option to set/change this title for each image as I upload it). There is no problem with my form.
PROBLEM: My dilemma lies inside the PHP page where the form data/action is submitted.
I can only manage to either:
Upload correct images, but get same title for all
Insert correct titles, but get same image for all
Here is my PHP action page: (Currently uploading correct images, but having same title for all)
<?php
// CONNECT TO DATABASE...
// INCLUDE UPLOAD CLASS LIBRARY
include (dirname(__FILE__).'/lib/class.upload.php');
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
// create an array here to hold file names
$uploaded = array();
foreach ($files as $file)
{
$generate_name = rand(100,99999);
$generate_name_extra = rand(200,9999);
$filenamex = "COVER_PHOTO_".$generate_name.$generate_name_extra."_".time();
$filenamex_thumb = $filenamex."_thumb";
$handle = new upload($file);
if ($handle->uploaded) {
$this_upload = array();
///// 1 ////////////////////////////////////////////////////////////////////
$handle->file_new_name_body = $filenamex_thumb;
$handle->file_force_extension = true;
$handle->image_resize = true;
$handle->image_x = '300';
$handle->image_ratio_y = true;
$handle->jpeg_quality = '100';
// ABSOLUTE PATH BELOW
$handle->process($absoRoot.'covers/thumbs/');
////////////////////////////////////////////////////////////////////////////
if ($handle->processed) {
// store the image filename
$this_upload['image'] = $handle->file_dst_name; // Destination file name
$this_upload['body'] = $handle->file_dst_name_body; // Destination file name body
$this_upload['extension'] = $handle->file_dst_name_ext; // Destination file extension
$category_id = $_POST['cat'];
$hiddenvalues = explode ("|",$_POST["cat"]);
$category = $hiddenvalues[0];
$category_name = $hiddenvalues[1];
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id) VALUES ("", "'.$this_upload['image'].'", "'.$imagename.'", "'.$category_name.'", "'.$category.'")';
mysql_query($sql);
}
$handle->clean();
header("Location: ./upload.php");
$message = "";
} else {
echo ' file not uploaded to the wanted location';
echo ' Error: ' . $handle->error . '';
}
} ?>
(I use the Upload Class by Colin Verot to handle image uploads, and their FAQ tutorial to handle MULTIPLE image uploads on this page, under: What about multiple uploads?)
This would work perfect if I were just uploading images, however I added the functionality of adding each image data to my database. & This is where it gets confusing.
I'm sure the key is placing the SQL query inside the right foreach, or perhaps making another one, but I've tried that & it only gives me 1 good result for either the image upload or the title, never for both.
I need to upload the image to the site, then store its data (including image path) to my database.
Please look into my code and enlighten me how to solve this problem? A snippet clue would really be great for now as I am already very confused after having tried all I could think of. Thank you so much!
You aren't saving your $imagename variable to the $files array, you're just resetting it each time.
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
Should be something like:
$files[$i][$k] = array($v, $_POST['keyword'][$i]);
...
foreach ($files as $data) {
list($file, $imagename) = $data;
...
}
I do think one of your problems is your foreach:
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
So you are going through each of the fields assigning their value to the right file which fits this structure policy:
_FILES => array(
'name' => array(0 => 'file.txt'),
'size' => array(0 => 235)
)
Which is correct for multifiles but then you do:
$imagename = $_POST['keyword'][$i];
Which does not look right. You are overwriting the var each time with the last looked at which means you will only ever get one input vlaue.
When you're gathering the file information you're overwriting $imagename on every loop so it will be assigned to the last one. Try attaching it to the $files variable (hopefully this doesn't mess with the upload class you're using).
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$files[$i]['imagename'] = $_POST['keyword'][$i];
}
Then update your $sql string to reference that
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id)
VALUES ("", "'.$this_upload['image'].'", "'.$file['imagename'].'",
"'.$category_name.'", "'.$category.'")';

Categories