0

file_get_contents();我已经编写了一个脚本,在使用相对文件路径时使用此方法将图像文件上传到服务器,例如。/var/test/image1.jpg以及当我使用远程网址时,例如。http://domain.com/test/image1.jpg.

但是,它不适用于本地路径,即。file://C:/Users/me/Pictures/image1.jpg。我得到,“ file_get_contents(file://C:/Users/me/Pictures/image1.jpg)[function.file-get-contents]:无法打开流:没有这样的文件或目录”或“不支持远程主机文件访问”。

我真的需要它来处理本地路径,以便远程客户端可以通过 API 将他们的本地图像上传到我的服务器。因此,我不能使用表单,需要使用此处指定的 PUT 方法([http://www.php.net/manual/en/features.file-upload.put-method.php][1])但是如何我访问文件?

我的 API 的代码如下,但我试图弄清楚如何从客户端本地机器获取文件内容:

if($_SERVER['REQUEST_METHOD'] == 'PUT') {
    $input = file_get_contents("php://input"); //filepath passed from client in XML

//Convert the XML to an object we can deal with
$xml = simplexml_load_string($input);   

$file_path = $xml->image->filepath; 

if  (file_exists($file_path) ){

    $file_data = file_get_contents($file_path);

    //Initialise the Curl Instance
    $ch = curl_init();

    //Set our Curl Options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $file_data);

    //Execute the request
    $response = curl_exec($ch);

    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    //Close the Handle
    curl_close($ch);
}
4

2 回答 2

4

您不应该指定file:// 要访问本地路径,您可以直接执行

file_get_contents('C:/Users/me/Pictures/image1.jpg');

您还可以使用../以下基于导航的方式相对于当前目录进行导航

file_get_contents('../../../somefile.xyz');

编辑:如果您尝试访问客户端文件,即远程路径,那将无法正常工作。您需要诸如 HTTP、FTP 之类的东西来传输您的文件。仅仅给出一个本地文件系统地址是不够的。

端点需要以某种方式使文件可用(HTTP/FTP 服务器),或者您需要让客户端通过浏览器和字段上传文件。<input>

于 2012-11-15T12:00:05.263 回答
1

您无法file_get_contents()从远程客户端的计算机上打开任何文件,除非它们在本地运行(他们还需要为此设置 PHP)然后以某种方式将其提交到您的服务器。

file_get_contents()允许您打开与您的脚本在同一台机器上的文件,而不是在不同的机器上

您可以查看http://www.tizag.com/phpT/fileupload.php以获取文件上传器的简单示例

于 2012-11-15T12:10:10.007 回答