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

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:
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.
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;
}

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);

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.

Related

Uploading a file from url

Hello guys :) how can i upload a file from an url ? (i read a lot of questions talking of this but nothing its working ...) here is my code :
$url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
$file = file_get_contents($url);
if ($file != NULL) {
$fileName = md5(uniqid()) . '.' . $file->guessExtension();
$file->move(
$this->getParameter('image_directory'), $fileName
);
}
Here i just want to download the image from url and move it to a directory (i will save the path in the database after), but with this code i have this error :
Call to a member function guessExtension() on string
This simple code will download and save the image to a file
<?php
$url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
$file = file_get_contents($url);
if ($file != NULL) {
$pathToFolder = 'images/png/'; // just an example folder location
$fileName = $pathToFolder . md5(uniqid()) . 'png';
file_put_contents($fileName,$file);
} else {
echo 'File downlaod error';
}
file_get_contents is to read the content of a file (txt, xml, etc).
Instead, you should use linux command wget. You can run it with PHP function exec.
$url = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
//Execute wget
$file=exec("wget http://www.example.com/file.xml");
if ($file != NULL) {
$fileName=md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('image_directory'), $fileName);
}

Php copy : Invalid argument error only on inside while loop and working for last record

Reading the file for the image url and calling the copy function.
imagecopy.txt
https://server.com/2017/12/check.png
https://server.com/2017/12/contacts.png
https://server.com/2018/06/CDP.bmp
https://server.com/module-acculturation-1.png
While copying the files from the url, getting the failed to open stream: Invalid argument error only on inside while loop. but works for the last record if the file has more files.
<?php
$file=fopen("imagecopy.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
$source = fgets($file);
$imagename = explode("/", $source);
$pathname = 'uploads/' . date("Y") . '/' . date("m") . '/';
if (!is_dir($pathname))
{
mkdir($pathname, 0777, true);
}
$destination = $pathname.end($imagename);
copyimageURL($source, $destination);
}
fclose($file);
function copyimageURL($source, $destination)
{
echo $source;
echo "<br>";
echo $destination;
copy($source, $destination);
}
?>
1.Working fine with singe record
2.Copying the last image only if the file has more images list.
I'm guessing imagecopy.txt you're reading ends in a newline, which makes the last line of the file blank.
If you change
$source = fgets($file);
to
$source = trim(fgets($file));
if( empty($source) ) continue;
it should work fine
Try this:
if ($file) {
while (($name = fgets($file)) !== false) {
$imagename = basename($name);
$pathname = 'uploads/' . date("Y") . '/' . date("m") . '/';
if (!is_dir($pathname))
mkdir($pathname, 0777, true);
$destination = $pathname.$imagename;
copyimageURL(trim($name), $destination);
}
fclose($file);
}

Create html file with php script

I want to create a php script that will check if a certain html file exist or not. if it doesn't exist, then create a new one and give it a name.
I have tried the code below, but still not working.
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
$filepath = dirname(__DIR__).'/views/sd_reports/'.$filename;
write_file($filepath, $file);
if(! file_exists ($filename))
{
$fp = fopen($filename, 'w');
fwrite($fp, $file);
fclose($fp);
}
I'm not familiar with the method you're using called 'site_url'. From a quick google search it looks like it's a method in Word Press. Ignoring the site_url method, you might want to test using a specific url, like http://ted.com for example. I've specified is_file rather than file_exists because file_exists will return true even if the path you've specified is a directory, whereas is_file will only return true if the path is an actual file. Try this code, setting the $site variable to a site url or path to a file.
I've also switched some code around, doing a check first to see if the file exists before attempting to read in the contents of $site. This way, if the file already exists, you're not needlessly reading in the contents of $site.
$filename = "Service_delivery_report_" . date("Y-m-d",
time()). ".html";
$filepath = realpath("./") . "/views/sd_reports/" . $filename;
if (!is_file($filepath))
{
$site = "http://somesite.com/somepage";
if ($content = file_get_contents($site))
{
file_put_contents($filepath,
$content);
}
else
{
echo "Could not grab the contents of some site";
}
}
Use file_exists();
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Then, if it doesn't exist, create a file with fopen();, like so:
$handle = fopen($filename, "w");
Try this
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
if(! file_exists ($filename))
{
$f = fopen($filename, "w");
fwrite($f, $file);
fclose($f);
}
else
echo "file already exist";

PHP fileupload: keep both files if same name

is there any pretty solution in PHP which allows me to expand filename with an auto-increment number if the filename already exists? I dont want to rename the uploaded files in some unreadable stuff. So i thought it would be nice like this: (all image files are allowed.)
Cover.png
Cover (1).png
Cover (2).png
…
First, let's separate extension and filename:
$file=pathinfo(<your file>);
For easier file check and appending, save filename into new variable:
$filename=$file['filename'];
Then, let's check if file already exists and save new filename until it doesn't:
$i=1;
while(file_exists($filename.".".$file['extension'])){
$filename=$file['filename']." ($i)";
$i++;
}
Here you go, you have a original file with your <append something> that doesn't exist yet.
EDIT:
Added auto increment number.
Got it:
if (preg_match('/(^.*?)+(?:\((\d+)\))?(\.(?:\w){0,3}$)/si', $FILE_NAME, $regs)) {
$filename = $regs[1];
$copies = (int)$regs[2];
$fileext = $regs[3];
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
while(file_exists($fullfile) && !is_dir($fullfile))
{
$copies = $copies+1;
$FILE_NAME = $filename."(".$copies.")".$fileext;
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
}
}
return $FILE_NAME;
You can use this function below to get unique name for uploading
function get_unique_file_name($path, $filename) {
$file_parts = explode(".", $filename);
$ext = array_pop($file_parts);
$name = implode(".", $file_parts);
$i = 1;
while (file_exists($path . $filename)) {
$filename = $name . '-' . ($i++) . '.' . $ext;
}
return $filename;
}
Use that function as
$path = __DIR__ . '/tmp/';
$fileInput = 'userfile';
$filename = $path .
get_unique_file_name($path, basename($_FILES[$fileInput]['name']));
if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $filename)) {
return $filename;
}
You can get working script here at github page
Use file_exists() function and rename() function to achieve what you're trying to do!

Uploading images from a url naming dilemma

Let's say I have an image URL
http://website.com/content/image.png
I want to grab that image and place it in my own server, but I want to rename it beforehand so I can store the location in the database.
I am using the following code:
$url = 'http://website.com/content/image.png';
/* Extract the filename */
$filename = substr($url, strrpos($url, '/') + 1);
/* Save file wherever you want */
file_put_contents('upload/'.$filename, file_get_contents($url));
If I want to rename the file to something entirely new, but keep the extension in tact, how can I accomplish that? Also will this work if there is more content in the url?
For example instead of:
url here/content/image.png
It would be:
url here/content/stuff/images/image.png
I am basically trying to write a universal function that will take a URL to an image, upload it to my server, and rename that image to what I want while keeping the extension in tact.
First- You need to check if your webserver can access URL's from another server.
Second- Assuming you can:
$url = 'http://website.com/content/image.png';
$extension = end(explode(".", $url));
$filename = "the_filename_you_want.".$extension;
file_put_contents('upload/'.$filename, file_get_contents($url));
<?php
$url = 'http://www.bla.org/img/derp.jpg';
$extension = end(explode('.', $url));
file_put_contents('/tmp/image.'.$extension, file_get_contents($url));
$filename = substr($url, strrpos($url, '.'));
You need pathinfo:
$url = 'http://website.com/content/image.png';
$path = parse_url($url, PHP_URL_PATH);
/* Extract the filename and extension */
$filename = pathinfo($path, PATHINFO_FILENAME);
$extension = pathinfo($path, PATHINFO_EXTENSION);
/* Save file wherever you want */
file_put_contents('upload/' . $filename . '.' . $extension, file_get_contents($url));
You might want to look at parse_url() function to get at the various URL components.
Like:
$url_parts = parse_url($url);
$uri = $url_parts['path'];
Then use pathinfo() to break up the components of the URI into path, filename, extension, etc.
$uri_info = pathinfo($uri);
$dir_name = $uri_info['dirname'];
$file_name = $uri_info['filename'];
$file_basename = $uri_info['basename'];
$file_extension = $uri_info['extension'];

Categories