0

I have visited this article previously and found it useful, but i would like to add more functionality to it by having it save an image file name according to the URL name.

This is what I've done so far and it works.

$contents=file_get_contents('http://www.domain.com/logo.png');
$save_path="C:/xampp/htdocs/proj1/download/[logo.png]";
file_put_contents($save_path,$contents);

Basically, where I have put square brackets around I want to have that dynamic based on the URL file name. For example, if i have an image url such as this: https://cf.dropboxstatic.com/static/images/brand/glyph-vflK-Wlfk.png, I would like it to save the image into the directory with that exact image name which in this case is glyph-vflK-Wlfk.png.

Is this possible to do?

Community
  • 1
  • 1
Jeiman
  • 1,121
  • 9
  • 27
  • 50

3 Answers3

0

From what I understand, what you're trying to do is the following :

$url = 'http://www.domain.com/logo.png';
$contents=file_get_contents($url);

$posSlash = strrpos($url,'/')+1);
$fileName = substr($url,$posSlash);

$save_path="C:/xampp/htdocs/proj1/download/".$fileName;
file_put_contents($save_path,$contents);
Nirnae
  • 1,315
  • 11
  • 23
0

There is a function for that, basename():

$url="http://www.domain.com/logo.png";
$contents=file_get_contents($url);
$save_path="C:/xampp/htdocs/proj1/download/".basename($url);
file_put_contents($save_path,$contents);

You might want to check if it already exists with file_exists().

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

I would do this way

$url = "http://www.domain.com/logo.png";

$file = file_get_contents($url);
$path = "C:/xampp/htdocs/proj1/download/". basename($url);

return !file_exists($path) ? file_put_contents($path, $file) : false;
André Ferraz
  • 1,511
  • 11
  • 29
  • Didnt know there was a function called `basename`. However, I may have an issue though, what if the image file name is the same, but I still want to store it? Do i have to create a folder then for each image I download that may have the same name? – Jeiman Oct 30 '15 at 16:55
  • Well you can do many things, add number incrementing to picture with the same name, honestly there is a ton of things you can do, maybe you could get the domain name and put it as a folder and then all image associated to the domain name into that folder, there is a ton of thing you can do. Just put your logic where false is or put it in a if statement block. – André Ferraz Oct 30 '15 at 21:36