Uploading images from a url naming dilemma - php

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'];

Related

Get Image File Extension with PHP

The file name is known but the file extension is unknown. The images in thier folders do have an extension but in the database their names do not.
Example:
$ImagePath = "../images/2015/03/06/"; (Folders are based on date)
$ImageName = "lake-sunset_3";
Does not work - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath))->getExtension();
echo $Ext;
Does not work either - $Ext is empty:
$Ext = (new SplFileInfo($ImagePath.$ImageName))->getExtension();
echo $Ext;
Does not work either - $Ext is still empty:
$Ext = (new SplFileInfo($ImagePath,$ImageName))->getExtension();
echo $Ext;
$Ext should produce ".jpg" or ".jpeg" or ".png" etc.
So my question is simple: What am I doing wrong?
Now, this is a bit of an ugly solution but it should work. Make sure that all your files have unique names else you'll have several of the same file, which could lead to your program obtaining the wrong one.
<?php
$dir = scandir($imagePath);
$length = strlen($ImageName);
$true_filename = '';
foreach ($dir as $k => $filename) {
$path = pathinfo($filename);
if ($ImageName === $path['filename']) {
break;
}
}
$Ext = $path['extension'];
?>
Maybe this might help you (another brute and ugly solution)-
$dir = '/path/to/your/dir';
$found = array();
$filename = 'your_desired_file';
$files = scandir($dir);
if( !empty( $files ) ){
foreach( $files as $file ){
if( $file == '.' || $file == '..' || $file == '' ){
continue;
}
$info = pathinfo( $file );
if( $info['filename'] == $filename ){
$found = $info;
break;
}
}
}
// if file name is matched, $found variable will contain the path, basename, filename and the extension of the file you are looking for
EDIT
If you just want the uri of your image then you need to take care of 2 things. First directory path and directory uri are not the same thing. If you need to work with file then you must use directory path. And to serve static files such as images then you must use directory uri. That means if you need to check files exists or what then you must use /absolute/path/to/your/image and in case of image [site_uri]/path/to/your/image/filename. See the differences? The $found variable form the example above is an array-
$found = array(
'dirname' => 'path/to/your/file',
'basename' => 'yourfilename.extension',
'filename' => 'yourfilename',
'extension' => 'fileextension'
);
// to retrieve the uri from the path.. if you use a CMS then you don't need to worry about that, just get the uri of that directory.
function path2url( $file, $Protocol='http://' ) {
return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
$image_url = path2url( $found['dirname'] . $found['basename'] ); // you should get the correct image url at this moment.
You are calling a file named lake-sunset_3. It has no extension.
SplFileInfo::getExtension() is not designed to do what you are requesting it to do.
From the php site:
Returns a string containing the file extension, or an empty string if the file has no extension.
http://php.net/manual/en/splfileinfo.getextension.php
Instead you can do something like this:
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
getExtension() only returns the extension from the given path, which in your case of course doesn't have one.
In general, this is not possible. What if there is a file lake-sunset_3.jpg and a file lake-sunset_3.png?
The only thing you can do is scan the directory and look for a file with that name but any extension.
You're trying to call an incomplete path. You could try Digit's hack of looking through the directory for for a file that matches the name, or you could try looking for the file by adding the extensions to it, ie:
$basePath = $ImagePath . $ImageName;
if(file_exists($basePath . '.jpg'))
$Ext = '.jpg';
else if(file_exists($basePath . '.gif'))
$Ext = '.gif';
else if(file_exists($basePath . 'png'))
$Ext = '.png';
else
$Ext = false;
Ugly hacks aside, the question begging to be asked is why are you storing them without the extensions? It would be easier to strip off the extension if you need to than it is try and find the file without the extension

PHP move_uploaded_file dynamic file name - files have no extension

I want to upload some GPX (XML technically) files to the server and rename them with dynamic file names (such as 0.gpx, 1.gpx ... ). I can not figure out how to do this with the move_uploaded_file function as it only creates the files extensionless. I get a 'name' file instead of a 'name.gpx' file.
Shouldn't it use the PATHINFO_EXTENSION of the uploadef file automatically to create the file with the right extension?
I have tried to call the function like this:
$filename = 0;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$filename++;
Even if I try to create a string with the extension it does not work:
$tmp = 0;
$ext = pathinfo($name, PATHINFO_EXTENSION);
$filename = $tmp + "." + $ext;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Help please?
File name should have the extension. This works fine for me to find the extension:
$temp = explode(".", $_FILES["uploadfiles"]["name"]);
$extension = end($temp);
echo $extension; // Display the extension
$tmp = 0;
$filename = $tmp.".".$extension;
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Hope this helps.
I don't think temporary files have an extension.
You could manually add "gpx" to the name :
$tmp = 0;
$filename = $tmp . ".gpx";
move_uploaded_file($_FILES['uploadfiles']['tmp_name'][$f], $filename);
$tmp++;
Or maybe check the mimetype and craft the appropriate extension out of it.
Or take the extension in $_FILES['uploadfiled']['name'], match it in a whitelist, and append it to your final filename.

How to get extension of file name within link

I've set of URLs each one ended with file name that has extension to its type
Example
$link = "http://www.some_site.com/test.vob";
Using PHP i wonder how can i get the extension of the last file name on the link so i wanna get vob.
I've tried this one but it gives the file name itself test but i want the extension vob
$filename = basename($link);
$filename = substr($filename, 0, strpos($filename, '.'));
echo $filename; // test
~ Thanks
Take a look at pathinfo():
$link = "http://www.some_site.com/test.vob";
echo pathinfo($link, PATHINFO_EXTENSION); // vob
Example: http://3v4l.org/oQn3c

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

PHP strip unknown file extension

I understand that using PHP's basename() function you can strip a known file extension from a path like so,
basename('path/to/file.php','.php')
but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?
Thanks in advance!
pathinfo() was already mentioned here, but I'd like to add that from PHP 5.2 it also has a simple way to access the filename WITHOUT the extension.
$filename = pathinfo('path/to/file.php', PATHINFO_FILENAME);
The value of $filename will be file.
You can extract the extension using pathinfo and cut it off.
// $filepath = '/path/to/some/file.txt';
$ext = pathinfo($filepath, PATHINFO_EXTENSION);
$basename = basename($filepath, ".$ext");
Note the . before $ext
$filename = preg_replace('#\.([^\.]+)$#', '', $filename);
You can try with this:
$filepath = 'path/to/file.extension';
$extension = strtolower(substr(strrchr($filepath, '.'), 1));
Try this:-
$path = 'path/to/file.php';
$pathParts = pathinfo( $path );
$pathWihoutExt = $pathParts['dirname'] . DIRECTORY_SEPARATOR . $pathParts['filename'];

Categories