【问题标题】:PHP Copy command failing when spaces?空格时PHP复制命令失败?
【发布时间】:2011-04-24 22:56:29
【问题描述】:

我正在执行以下命令:

<?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!
?>

前两个副本很好,但不是最后一个。为什么?

它必须与文件名有关(最后一个在 085 之前有一个空格)。

任何帮助将不胜感激!

【问题讨论】:

  • error_reporting(E_ALL); 说什么?
  • 您是否尝试通过在 URL 中将其替换为 %20 来转义空间?
  • 源目录一样吗?
  • 另外,您知道在本地主机上时,您可以使用文件路径而不是使用慢速 http 传输(这可能也适用于空格)?
  • @Pekka:我实际上是从一个网站复制到另一个网站。我希望我可以使用文件路径,但我不能因为我正在做的事情。

标签: php copy


【解决方案1】:
http://localhost/.../HERMAN 085.jpg

应该是

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

当涉及到无效的 url 时,复制和 http 包装器不如浏览器/用户代理那么宽容。 url中的空格无效,所以应该是urlencode'd。

【讨论】:

  • 仍然无法正常工作,但您肯定在正确的道路上。我没有运气使用 urlencode。还有其他建议吗?
  • 如果这不起作用,我会检查网络服务器的访问日志以检查请求是否正常并返回数据。如果仍然失败,我会查看 cURLhttprequest 之类的软件包,看看它们是否可以管理。
  • CURL 最终成为最佳解决方案。
  • 有点。如果您对整个 URL 进行完全 urlencode,它也会失败。据我从测试中得知,空格是少数几个无法正确解释的字符之一。 Ghetto,但我建议执行 str_replace 将空格更改为 %20。
  • 查看rawurlencode,它在这种情况下解决了我的问题。 stackoverflow.com/questions/4744888/…
【解决方案2】:
//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}

【讨论】:

    【解决方案3】:

    最奇怪的事情: %20 方法似乎没有奏效,但经过一番尝试 徒劳(首先使用 %20,然后引用文件名,然后双引号,然后 保护空间,如果我错过了什么,请告诉我),现在原始版本完美无缺。这是 Windows 10,PHP 5.5.12,我们在 2016 年。 祝所有这些确定性的有限状态系统好运:)

    一个可能的解决方案顺便说一句,是使用 exec() 并在操作上做一个副本 系统级。再说一遍,它是特定于操作系统的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 2018-04-18
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 2021-07-17
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多