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 SPA开发者_运维技巧CE before the 085).
Any help would be greatly appreciated!
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.
//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}
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.
精彩评论