Copy Multiple Images From Remote Server - php

I am trying to copy multiple images from a remote host (using a URL) to my local box (using XAMPP on my local box to execute the script).
I am using copy(). When I go to execute the copy(), only the LAST image in the array is created. So, if I have 5 image links, only the 5th image gets created and nothing prior even gets a file created.
I have tried CURL and FOpen and then both create all of the files, but all of the files are blank except, again, the last file which is perfectly fine.
$txt_file = file_get_contents('urls_for_images.txt');
if(!empty($txt_file)){
$image_links = explode("\n", $txt_file);
$i = 1;
foreach($image_links as $image_link){
$file_info = pathinfo($image_link);
copy($image_link, 'images/00' . $i . '_original.' . $file_info['extension']);
$i++;
}
}
I am not sure where the problem is occurring, but it seems odd to me that it will copy the last image in the text file, but not any of the others.
Thanks for the help in advance!

The i variable never changes, therefore the code tries to copy a file with the same name over and over again and only the last file is saved.
Try modifying your code this way:
$txt_file = file_get_contents('urls_for_images.txt');
if(!empty($txt_file)){
$image_links = explode("\n", $txt_file);
$i = 1;
foreach($image_links as $image_link){
$file_info = pathinfo($image_link);
copy($image_link, 'images/00' . $i . '_original.' . $file_info['extension']);
$i++;
}
}

You'd be better off with just file(), which reads the file into an array automatically:
$files = file('urls_for_images.txt', FILE_IGNORE_NEW_LINES);
foreach($files as $remote_file) {
$local_file = ....;
copy($remote_file, $local_file);
}

It appears the problem is the text file which line endings are \r\n and you are exploding with only \n. The quickest way to fix this is either explode by \r\n; or trim with default parameters to remove \r from the end of each line.
foreach($image_links as $image_link){
$image_link = trim($image_link);
$file_info = pathinfo($image_link);
...
}
However, the cleanest way to do this is to use file function, which handles line endings automatically. I recommend you to use this approach.

Related

How to download images from various URL (same path)

I want to download about 200 images from an URL. For instance: Fetch www.web.com/images/001.png and download, fetch www.web.com/images/002.png and download and finish in 200.png.
I've read Grab/download images from multiple pages using php preg_match_all & cURL but I don't know how to modify the PHP to do that thing.
I'll be very appreciated if you can help me. Thank you so much
The simplest way that comes to mind, is to create a for loop, which counts from 1 to 200 and for every count, it then does a request for the image and saves it to the disk (I assume you want to save the image to your disk). Working example can be found at the bottom.
Let's start by settings some variables:
$baseUrl = 'http://www.web.com/';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 200;
The first variable $baseUrl defines where the images will be loaded from. The second defines your local directory in which the images will be saved. Please make sure that this directory exists before running the code, because it will not be automatically generated. The last variable, $maxImageNumber stores the largest image number, which we will need for the for loop.
After setting the variables, we can write the for loop. Separated by semicolons ; there are three parts in the brackets. First one being the starting point of the number we will be counting upwards. The second makes sure we don't go over our limit and the last one just states that the number will be counted up, using the ++ shorthand.
for($imageNumber = 1; $imageNumber <= $maxImageNumber; $imageNumber++) {
// code goes here
}
Inside this for loop we can now generate our file name and download/save the image to the disk. The first line uses the function str_pad() to add leading 0s to the image file (just like in your example) and then adds the extension .png to the name. This allows us to reuse the file name for loading as well as for saving. Second line loads the image with the function file_get_contents() by combining the base and the image file name. In the last line we use file_put_contents() to save the $fileData, we loaded just before, to the disk (using the local directory and the image file name).
$imageFileName = str_pad($imageNumber, 3, '0', STR_PAD_LEFT) . '.png';
$fileData = file_get_contents($baseUrl . $imageFileName);
file_put_contents($localDirectory . $imageFileName, $fileData);
The complete code should look like this:
<?php
$baseUrl = 'http://www.web.com/images/';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 10;
for($imageNumber = 1; $imageNumber <= $maxImageNumber; $imageNumber++) {
$imageFileName = str_pad($imageNumber, 3, '0', STR_PAD_LEFT) . '.png';
$fileData = file_get_contents($baseUrl . $imageFileName);
file_put_contents($localDirectory . $imageFileName, $fileData);
}
In the unlikely event that this all should not work, there are a few things you can try
check that the $localDirectory exists and is writable.
if the file_get_contents() should not work, you can use curl instead
make sure the computer this code is executed on can access the remote server
Thank you so much but imagine that pics are in www.web.com/image_0001_big.png and www.web.com/image_002_big.png and so on... (last will be web.com/image_0200_big.png)
This doesn't work (i don't know why)
<?php
$baseUrl = 'http://www.web.com/images';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 200;
$input='image_';
for($imageNumber = 001; $imageNumber <= $maxImageNumber; $imageNumber++) {
$imageFileName = str_pad($input, $imageNumber, 4, '_big', STR_PAD_LEFT) . '.png';
$fileData = file_get_contents($baseUrl . $imageFileName);
file_put_contents($localDirectory . $imageFileName, $fileData);
}
Thanks. You're amazing! Thanks for the help! I'm learning PHP and I'm a beginner yet:(
My error:
Warning: str_pad() expects at most 4 parameters, 5 given in C:\xampp\htdocs\auto.php on line 9
Warning: file_get_contents(http://www.web.com/images/.png): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in C:\xampp\htdocs\auto.php on line 10
I've found a semi-solution:_
<?php
$baseUrl = 'http://web.com/images';
$localDirectory = 'downloaded_images/';
$maxImageNumber = 400;
$input='image0';
$input2='big';
$extension ='.png';
for($imageNumber = 100; $imageNumber <= $maxImageNumber; $imageNumber++) {
$fileData = file_get_contents($baseUrl . $input . $imageNumber . $input2 . $extension);
file_put_contents($localDirectory . $imageNumber, $fileData);
}
?>
The problem is when... 0001 0009 0010 !! I want to tell php "hey, always 4 digits"

How can I add variable names to the end of a file?

I have created a form that submits the data to a filename on the server. The form submit is working fine, it generates the requested file called "we_input_.sts".
I am trying to use the following code to grab two variables from the form "bfstnme" and "gfstnme"and attach them to the filename eg "wed_import-Jane_Bill.sts
This is the amended code: However I am still unable to get it to work.
I am trying different ideas to get this to work correctly. I have tried moving the code around but I'm still obviously missing something. The last line before the $savestring== is "$fp=fopen("wed-import-.sts", "a+");
The last lines after the $savestring are : fwrite($fp,$savestring); fclose($fp);
<?php
$bfirstname = $_POST['bfstnme'];
$gfirstname = $_POST['gfstnme'];
$file = 'wed_import_.sts';
$current = file_get_contents($file);
$new_file = 'wed_input_'.$bfirstname.'&'.$gfirstname.'.sts';
file_put_contents($new_file, $current);
?>
Here is the way I have solved it using the valuable assistance of all concerned.
$names .= ("$bfstnme" . "$gfstnme");
$fp = fopen("wed_import_($names).sts", "a+");
The results of the above give me a filename called:
"wed_Import_[JaneBill].sts. I only need to work out how to put an amperstand (&) betwen the names.
Thank you to all.
If you want put the info inside the file you must change the + by a . like this:
$current .= ("gfirstname" . "bfirstname");
If you want change the name, you must do something like #Jay_P says
Why you don't name the file before writing to it?
<?php
$gfirstname = $_POST['gname'];
$bfirstname = $_POST['bname'];
$file = 'wed_input_Bride_Groom.sts';
// Opens the file to get existing content hopefully
$current = file_get_contents($file);
// Appends bride and groom first names to the file hopefully
$current .= ("gfirstname" . "bfirstname");
$new_file = 'wed_input_'.$gfirstname.'_'.$bfirstname.'.sts';
// Write the contents back to the file
file_put_contents($new_file, $current);
?>
Let's assume you have the names in a variable called $names. You can easily append the text with the FILE_APPEND flag like this:
file_put_contents('wed_input_Bride_Groom.sts', $names, FILE_APPEND);

remove new line from txt file after insert value

i create a txt file from a folder in that way:
$fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp,$value."\n");
}
and it create inside the txt each items, one per line, BUT it also add a newline at the end of the file.
This is the content of mylist.txt:
foldelr/file1.mp3
folder/file2.mp3
(BLANK NEWLINE)
I tried to remove the blank newline at the end of the txt file, in this way:
$filetxt = fopen("mylist.txt","r");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("newfile.txt", $rtrim);
But it doesn't work, because in the "newfile.txt", i still have the newline blank after last file name.
I tried to convert file in array, use "array_diff()" to remove the last line, but it fail.
I tried also all the suggestions in this thread: remove new line characters from txt file using php but not fix my problem.
Does anyone can please help me to understand what i'm missing or mistaken?
Kind Regards
Brus
Use file_get_contents method it works fine for me
$fp = fopen("mylist.txt","rw+");
foreach (glob("test/*.*") as $value) {
fwrite($fp, $value . "\n");
}
$filetxt = file_get_contents("mylist.txt");
$rtrim = rtrim($filetxt, "\n");
$newfile = file_put_contents("mylist.txt", $rtrim);
Or You can also remove the last newline by using the array count.
$fp = fopen("mylist.txt","rw+");
$i =0;
foreach(glob("folder/*.*") as $value){
$i++;
if($i < count(glob("folder/*.*")))
fwrite($fp,$value."\n");
else
fwrite($fp,$value);
}
Have you tried to first write new line and only than value (assuming you already have content in file)?
fp = fopen("mylist.txt","rw+");
foreach(glob("folder/*.*") as $value){
fwrite($fp, "\n".$value);
}

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

How to update csv column names with database table header

I am facing this problem some past days and now frustrate because I have to do it.
I need to update my CSV file columns name with database table header. My database table fields are different from CSV file. Now the problem is that first I want to update column name of CSV file with database table headers and then import its data with field mapping into database.
Please help me I don't know how I can solve this.
This is my php code:
$file = $_POST['fileName'];
$filename = "../files/" . $file;
$list = $_POST['str'];
$array_imp = implode(',', $list);
$array_exp = explode(',', $array_imp);
$fp = fopen("../files/" . $file, "w");
$num = count($fp);
for ($c = 0; $c < $num; $c++) {
if ($fp[c] !== '') {
fputcsv($fp, $array_exp);
}
}
fclose($fp);
require_once("../csv/DataSource.php");
$path = "../files/test_mysql.csv";
$dbtable = $ext[0];
$csv = new File_CSV_DataSource;
$csv->load($path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{ print_r($key[1]);
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into tablename($myKey)values($myVal)";
$res= mysql_query($query);
You have got an existing file of which the first line needs to be replaced.
This has been generally outlined here:
Overwrite Line in File with PHP
Some little explanation (and some tips that are not covered in the other question). Most often it's easier to operate with two files here:
The existing file (to be copied from)
A new file that temporarily will be used to write into.
When done, the old file will be deleted and the new file will be renamed to the name of the old file.
Your code does not work because you are already writing the new first line into the old file. That will chop-off the rest of the file when you close it.
Also you look misguided about some basic PHP features, e.g. using count on a file-handle does not help you to get the number of lines. It will just return 1.
Here is step by step what you need to do:
Open the existing file to read from. Just read the first line of it to advance the file-pointer (fgets)
Open a new file to write into. Write the new headers into it (as you already successfully do).
Copy all remaining data from the first file into the new, second file. PHP has a function for that, it is called stream_copy_to_stream.
Close both files.
Now check if the new file is what you're looking for. When this all works, you need to add some more steps:
Rename the original file to a new name. This can be done with rename.
Rename the file you've been written to to the original filename.
If you want, you then can delete the file you renamed in 5. - but only if you don't need it any longer.
And that's it. I hope this is helpful. The PHP manual contains example code for all the functions mentioned and linked. Good luck. And if you don't understand your own code, use the manual to read about it first. That reduces the places where you can introduce errors.
If you are managing to insert the table headers then you're half way there.
It sounds to me like you need to append the data after the headers something like:
$data = $headers;
if($fp[c]!=='')
{
$data .= fputcsv($fp, $array_exp);
}
Notice the dot '.' before the equals '=' in the if statement. This will add none blank $fp[c]values after the headers.

Categories