dongwupu5991
dongwupu5991
2015-02-07 20:02

文件名中的特殊字符导致问题

已采纳
$imageURL = 'http://www.cnsnews.com/sites/default/files/images/OBAMA-AP%20PHOTO_8.jpg';

$imageInfo = pathinfo($imageURL);
$imageName = clean(basename($imageURL,'.'.$imageInfo['extension']));
$fileName =  $imageName.'.'.$imageInfo['extension'];// file name

$content = file_get_contents($imageURL);

file_put_contents(UPLOAD_DIR.$fileName, $content);   
$product_file = UPLOAD_DIR.$fileName;


function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

.. although almost all urls I've tried work fine except this one, probably because of the special chars in OBAMA-AP%20PHOTO_8.jpg? even though I'm cleaning it?

The image doesn't get downloaded.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • duan5801 duan5801 6年前

    (editing my previous answer, it wasn't very helpful)

    triage the problem -- does the file_get_contents($imageURL) return data? Print the length of the returned string to test, echo strlen($contents);

    Can you create a file that contains a '%' in the filename?

    I can download the imageURL as typed, so you're most likely right, it's the % in the save-to filename that's going to be the problem.

    点赞 评论 复制链接分享
  • douzao5487 douzao5487 6年前

    Before cleaning the image name, you should urldecode it:

    function clean($string) {
       $string = urldecode($string);
       $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
       $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    
       return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
    }
    
    点赞 评论 复制链接分享