How to make two foreach have the same variable? - php

I have a function to upload multiple files. I use two foreach to upload the files. In the first foreach, I loop the uploaded file,
$j_upl = count($my_upload["name"]);
$isUploaded = 0;
$files = $_FILES;
for($i=0;$i<$j_upl;$i++){
$random_name = substr($my_upload["name"][$i],0,-4)."_".date("ymdhis").$i.substr($my_upload["name"][$i],-4);
$this->load->library('upload', $config);
$_FILES['upload_act']['name'] = $files['upload_act']['name'][$i];
$_FILES['upload_act']['type'] = $files['upload_act']['type'][$i];
$_FILES['upload_act']['tmp_name'] = $files['upload_act']['tmp_name'][$i];
$_FILES['upload_act']['error'] = $files['upload_act']['error'][$i];
$_FILES['upload_act']['size'] = $files['upload_act']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('upload_act');
}
In the $random_name, I use .date("ymdhis") to be added to the file_name. So, the file will be renamed to the file name."_".datetime uploded.
In the second foreach, I use this to insert the $random_name into the database.
foreach($details as $rows){
$file_name = substr($rows['val_upl'],0,-4)."_".date("ymdhis").$ii.substr($rows['val_upl'],-4);
$dt_act['UPL_FILENAME'] = ($rows['val_upl'] == "") ? NULL : $file_name.$ii;
$this->MProject->ins_activity_m($dt_act);
$ii += 1;
}
I use the same method to get the $file_name. If I upload around 2-3 files, the $file_name is matching the $random_name. But, if there are more files to upload, it begins to not match the $random_name because the second in ('Ymdhis') is different.
What is the best method to get the $random_name match the $random_name so the inserted file_name is matching the uploaded file_name?
Note:
I may added something to the file_name, but I prefer not to remove anything (the datetime format should exist)

The easiest way to solve this is to create an associate array in the first for loop with the required information passed in as key-value pairs. You don't need to loop through this object as you can use keys that you already know the values of within your loop like an existing filename to access the values like below...
$file_uploads = array();
for($i=0;$i<$j_upl;$i++){
$random_name = substr($my_upload["name"][$i],0,-4)."_".date("ymdhis").$i.substr($my_upload["name"][$i],-4);
$file_uploads[$my_upload["name"][$i]] = array(
'new_name' => $random_name,
'some_other_value' => $some_other_var
);
$this->load->library('upload', $config);
$_FILES['upload_act']['name'] = $files['upload_act']['name'][$i];
$_FILES['upload_act']['type'] = $files['upload_act']['type'][$i];
$_FILES['upload_act']['tmp_name'] = $files['upload_act']['tmp_name'][$i];
$_FILES['upload_act']['error'] = $files['upload_act']['error'][$i];
$_FILES['upload_act']['size'] = $files['upload_act']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload('upload_act');
}
foreach($details as $rows){
$file_name = $file_uploads[substr($rows['val_upl']]['new_name'];
$dt_act['UPL_FILENAME'] = ($rows['val_upl'] == "") ? NULL : $file_name.$ii;
$this->MProject->ins_activity_m($dt_act);
$ii += 1;
}
please note i've not tested this and i'm coding blind here but that should be enough to get you there.

If you need to capture the exact file names from the first loop, why not build an array within the first loop that just stores the file names? Then you can reference the array by the value of $rows rather than attempt to rebuild the names. (It also depends on what's between these two loops.)

Related

php rename files when downloading

Having trouble and keep getting error with my efforts , currently have an array in this format ....
$espn_ar["pid_6254"] = "2977742";
$espn_ar["pid_8269"] = "9614";
I'm using it to create url paths to download some images and name them
foreach ($espn_ar as $value){
$imageUrl = "https://a.espncdn.com/combiner/i?img=/i/headshots/nfl/players/full/$value.png&h=107&w=80&scale=crop";
$imageName = "images/mfl_.$value.png";
$imageFile = file_get_contents($imageUrl);
file_put_contents($imageName, $imageFile);
}
using the array example above the files are being named
mfl_2977742.png
mfl_9614.png
But i want the files to be named for the value that follows the "pid_" in each array item , so the file names i want are
mfl_6254.png
mfl_8269.png
Using my example , can anyone show me how to change the value when naming each image to the numbers following "pid_"
Include the keys in your foreach loop and extract the number for your filename
foreach ($espn_ar as $key => $value) {
$imageName = sprintf('images/mfl_%s.png', str_replace('pid_', '', $key));
// etc
}
Demo ~ https://3v4l.org/FgMi2

PHP file_exists() to check multiple files at once

I want to check multiple files at once if they exist or not. I want to show a text if any of these files exists:
$filepre = ''.$br.'/filethumb/'.$name.'.jpg';
$filess = ''.$br.'/ss/'.$name.'.jpg';
$filess1 = ''.$br.'/ss/'.$name.'1.jpg';
$filess2 = ''.$br.'/ss/'.$name.'2.jpg';
$filess3 = ''.$br.'/ss/'.$name.'3.jpg';
$filess4 = ''.$br.'/ss/'.$name.'4.jpg';
$filess5 = ''.$br.'/ss/'.$name.'5.jpg';
$filess6 = ''.$br.'/ss/'.$name.'6.jpg';
$filess7 = ''.$br.'/ss/'.$name.'7.jpg';
$filess8 = ''.$br.'/ss/'.$name.'8.jpg';
$filess9 = ''.$br.'/ss/'.$name.'9.jpg';
Then I want to check if any of these files exist or not. If 1 of these 10 files exists then show a text "Screenshots:". If no file exists then nothing will be shown.
I tried:
if (file_exists($filess or $filess1 or $filess2 or $filess3 or $filess4 or $filess5 or $filess6 or $filess7 or $filess8 or $filess9)){
echo 'Screenshots';
}
Did I do anything wrong that it's not working?
Put your filenames in an array and loop through:
$files = array('file_name_1', 'file_name_2'...);
foreach($files as $file){
if(file_exists($file)){
echo "screenshots";
break;
}
}
I would use an array, filter it and check if it is empty or not:
$files[] = $br.'/ss/'.$name.'1.jpg';
$files[] = $br.'/ss/'.$name.'2.jpg';
//etc...
if(array_filter($files, 'file_exists')) {
echo "Screenshots:";
}
This is extendable as you can compare the count() of the result to see if 2, 3, 4, etc.. exist or if the count equals the count of the original array.
You need to rearrange the checking in the if condition,
if (file_exists($filess) or file_exists($filess1) or file_exists($filess2) or file_exists($filess3) or file_exists($filess4) or file_exists($filess5) or file_exists($filess6) or file_exists($filess7) or file_exists($filess8) or file_exists($filess9)){
echo 'Screenshots';
}
Only if you don't want to use array and looping.

PHP concatanate variable name

In Propriete entity I have 5 field called image1 image2 image3 image4 image5
I wan't to add these fields in a for loop
I tried this but it doesn't work:
for($i=0;$i<count($this->request->data['files'])&&$i<5;$i++){
//... some code
$propriete->{'image'.$i+1} = $file['name'];
}
}
Can someone help me?
EDIT
This is the code of my loop:
for($i=0; $i<count($this->request->data['files']) && $i<5; $i++){
$file=$this->request->data['files'][$i];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . '/img/' . $file['name']);
debug($file['name']);
//prepare the filename for database entry
$propriete->{'image'.$i+1} = $file['name'];
}
}
Your code should work fine, you're just missing parenthesis which makes your concatenation go haywire
$propriete->{'image'.($i+1)}="test";
This can also be demonstrated by this simple test
$i=2;
echo 'image'.$i+1; // 1 :)
VS
echo 'image'.($i+1); //image3
Put the value of every method in a variable to store the value and then use it.For eg
$values = $this->request->data['files'];
You cannot for loop the data without putting them in a variable first.
If you cannot find the filename the problem should be that you are naming the object property in the wrong manner.You should enclose $i+1 with quotes.

glob() not returning files with same creation time php

Currently i am using this code to get file in directory, but it only that files which different create date/time. If the files has same time, then it just shows 1 of them.
<?php
$perpage = 6;
$page = (int)$_GET['page'];
if(!($page>0)) $page = 1;
$offset = ($page-1)*$perpage;
$parm=$_GET['dir'];
$extensions = array('3gp', 'mp4', 'png', 'gif', 'bmp');
$files = glob('files/'.$parm.'/*'.'{'.implode(',', $extensions).'}', GLOB_BRACE);
$files = array_combine(array_map("filemtime", $files), $files);
krsort($files);
$total_files = sizeof($files);
$total_pages = ceil($total_files/$perpage);
$files = array_slice($files, $offset, $perpage);
?>
Now please solve this case
Actually, the glob() function does return what meets the specified criteria!
But the reason for your problem being is because the array_combine() function takes the first argument (the array which holds the file times) as the "keys" of the final output array, and as you know there can't be any key duplicates in an array, only the last file among those having the same file time will be added to the final result array.
By knowing that, you may think of an alternative way of what your trying to do (since I don't know what are you trying to do!)

Adding 1 to the image name every time a new image is uploaded to folder

I am a newbie at PHP and I'm learning.
I've made a basic script where you can upload an image to a director on the server. I want the image names to get a number at the end so that the name won't be duplicated.
This is my script to add 1 to the name (I'm really bad at "for loops"):
for(x=0; $imageName => 50000; x++){
$imageFolderName = $imageName.$x;
}
Please tell me if I'm doing this totally wrong.
Adding to Niet's answer, you can do a foreach loop on all the files in your folder and prepend a number to the file name like so:
<?
$directory = 'directory_name';
$files = array_diff(scandir($directory), array('.', '..'));
$count = 0;
foreach($files as $file)
{
$count++;
rename($file, $count.'-'.$file);
}
?>
Alternatively you could rename the file to the timestamp of when it was uploaded and prepend some random characters to the file with the rand() function:
<?
$uploaded_name = 'generic-image.jpeg';
$new_name = time().rand(0, 999).$uploaded_name;
?>
You'll need to handle and move the uploaded files before and after the rename, but you get the general gist of how this would work.
Here's a potential trick to avoid looping:
$existingfiles = count(glob("files/*"));
// this assumes you are saving in a directory called files!
$finalName = $imageName.$existingfiles;

Categories