Light
Light

Reputation: 1677

PHP copy image from url to server and echo the final url

I am trying to write a code that will copy an image from URL to a relative path on my server with a random file name and echo back the final url. I have 2 problems:

  1. It doesn't work with relative path. If I don't declare the path, the function works but the image is being saved on the same folder of the PHP file. If I do specify the folder, it doesn't return any error but I don't see the image on my server.
  2. The echo function always return an empty string.

I am a client side programer so PHP is not my thing... I would appreciate any help.

Here is the code:

<?php

$url = $_POST['url'];
$dir = 'facebook/';
$newUrl;

copy($url, $dir . get_file_name($url));

echo $dir . $newUrl;

function get_file_name($copyurl) {
    $ext = pathinfo($copyurl, PATHINFO_EXTENSION);
    $newName = substr(md5(rand()), 0, 10) . '.' . $ext;
    $newUrl = $newName;
    return $newName;
}

EDIT:

Here is the fixed code if anyone is interested:

<?php

$url = $_POST['url'];
$dir = 'facebook/';
$newUrl = "";

$newUrl = $dir . generate_file_name($url);

$content = file_get_contents($url);
$fp = fopen($newUrl, "w");
fwrite($fp, $content);
fclose($fp);

echo $newUrl;

function generate_file_name($copyurl) {
    $ext = pathinfo($copyurl, PATHINFO_EXTENSION);
    $newName = substr(md5(rand()), 0, 10) . '.' . $ext;
    return $newName;
}

Upvotes: 1

Views: 8068

Answers (2)

Pavel Strakhov
Pavel Strakhov

Reputation: 40492

You should use file_get_contents or curl to download the file. Also note that $newUrl inside your function is local and this assignment doesn't alter the value of global $newUrl variable, so you can't see it outside your function. And the statement $newUrl; in 3rd line doesn't make any sense.

Upvotes: 2

jyoti
jyoti

Reputation: 350

Answer Here

Either Use

copy('http://www.google.co.in/intl/en_com/images/srpr/logo1w.png', '/tmp/file.jpeg');

or

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);

Upvotes: 4

Related Questions