Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Copy command failing when spaces?

Tags:

php

copy

I am executing the following commands:

<?php
copy ("http://localhost/.../DSCF8253.JPG" , "sites/default/files/DSCF8253.JPG"); // Success!
copy ("http://localhost/.../DSCF8260.JPG" , "sites/default/files/DSCF8260.JPG"); // Success!
copy ("http://localhost/.../HERMAN 085.jpg" , "sites/default/files/HERMAN 085.jpg" ); // Fail!
?>

The first two copy fine, but not the last one. Why?

It must have something to do with the filenames (the last one has a SPACE before the 085).

Any help would be greatly appreciated!

like image 792
coderama Avatar asked Oct 13 '10 16:10

coderama


3 Answers

http://localhost/.../HERMAN 085.jpg

Should be

http://localhost/.../HERMAN%20085.jpg

Copy & the http wrappers are less forgiving then browsers / user-agents when it comes to invalid urls. A space in an url is invalid, so it should be urlencode'd.

like image 187
Wrikken Avatar answered Nov 12 '22 21:11

Wrikken


//i used this code once i tried to copy images to a wordpress site and set post featured image
//i only mentioned the part you want and did not mention other parts
$image_url = 'http://example.com/images/my image with spaces.jpg';
try {
    //throw exception if can't move the file

    if (!copy(str_replace(" ","%20",$image_url),$file)) {
        $errors = error_get_last();
        throw new Exception('Could not copy file');
    }   

} catch (Exception $e) {
    echo $e->getMessage();
}
 //using urlencode will corrupt the url if used with the full url
 //it will generate something like http%dsf%swdfablablabla
 //if you need to encode you will encode anything after http://yoursite.com/{encode only works here}
like image 29
ashraf mohammed Avatar answered Nov 12 '22 22:11

ashraf mohammed


Strangest thing: the %20 way doesn't seem to do the trick, but after some trying in vain (first with %20, then quoting the filename, then double-quoting, then protecting spaces, tell me if I missed something), now the original version works flawlessly. This is Windows 10, PHP 5.5.12 and we are in year 2016. Good luck with all these deterministic, finite-state systems :)

A possible solution btw, is to use exec() and do a copy on the operating system level. Then again, it's OS specific.

like image 1
dkellner Avatar answered Nov 12 '22 23:11

dkellner