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
Related
I want to build a program for a photo studio that will calculate files in a folder for example I have a folder named Upload and it contains 10 files
7 of the files are named 1 5x7 and
3 of the files are named 2 5x7.
I want the program that will sum them up based on the first letter of the file name.
All I was able the do is to scan the directory and list the files in this directory.
<?php $dir = "/upload/"; $list = scandir($dir); print_r($list);?>
Any help will be greatly appreciated.
Unless I'm misunderstanding your requirements, this might do it ...
$files = scandir('/upload/');
$counts = [];
foreach ($files as $f) {
$char1 = substr($f,0,1);
$counts[$char1] = empty($counts[$char1]) ? 1 : $counts[$char1]+1;
}
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.)
So what i am trying to do is get a list of text files from a directory.
take that list and randomly choose 1 file.
then take that file and print out the contents. now i did this a few years back. but can't find my old script. i tried what i have below just to print out a file name.. but event that is not working?
$path = '/seg1';
$files = scandir($path);
$seg = array ( $files );
$rand_keys = array_rand($seg, 1);
print $rand_keys;
Would love some new eyes on this as well as any input.
/*** Search All files in Dir. with .txt extension ***/
foreach (glob('./seg1/*.txt') as $filename)
{
$myFiles[] = $filename;
/*** Array of file names **/
}
/*** Total count of files ***/
$max=sizeof($myFiles);
/*** Select a Random index for Array with Max limit ***/
$fileNo=rand(0, $max);
/*** Path of the Random file to Access ***/
$file=$myFiles[$fileNo];
/*** Get the content from Text file ****/
$data = file_get_contents($file, true);
As your variable naming suggests, you randomly select one key out of the array; try getting the value by
$filename = $seg[$rand_keys];
$path = '/seg1';
$files = scandir($path));
if($files)
echo file_get_contents($files[mt_rand(2,count($files))]);
Recommend you use glob so you only get files you want, this excludes system directories like . and ..
foreach (glob("seg1/*.txt") as $filename) {
$seg[] = $filename;
}
Or an even simpler solution:
$rand_keys = array_rand(glob("seg1/*.txt"), 1);
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;
I need to download some images from a specific array of urls, something like:
<?php
$images = array('http://url1.com/img1.png','http://url1.com/img2.png');
// download this images from this paths
I saw some scripts here but don't get them exactly on how can i link them to this array.
The expected output would be: When i run the script to download those images from that array to a specific folder from my server: home/user/public_html/images. It's much appreciated anyone who helps me, i am trying but can't make the connections, currently a rookie.
Something like this maybe.
$images = array('http://ecx.images-amazon.com/images/I/214RgVjsvTL.jpg','http://ecx.images-amazon.com/images/I/515pMJlul8L.jpg');
foreach($images as $name=>$image) {
//get image
$imageData = file_get_contents($image); //$image variable is the url from your array
$name = explode("/", $image);
$handle = fopen("images/".$name[5],"x+");
fwrite($handle,$imageData);
fclose($handle);
}