Reputation: 6601
I have written a script to upload an image file to a server using file_get_contents();
this works when using a relative file path eg. /var/test/image1.jpg
and also when I use a remote url eg. http://domain.com/test/image1.jpg
.
However, it does not work for local paths ie. file://C:/Users/me/Pictures/image1.jpg. I get, "file_get_contents(file://C:/Users/me/Pictures/image1.jpg)
[function.file-get-contents]: failed to open stream: No such file or directory" or "remote host file access not supported".
I really need this to work for local paths so that remote clients can upload their local images to my server via an API. I therefore cannot use a form and need to use the PUT method specified here ([http://www.php.net/manual/en/features.file-upload.put-method.php][1]) but how to I access the file?
The code for my API is below but am trying to figure out how to get the file contents from a clients local machine:
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);
}
Upvotes: 0
Views: 10185
Reputation: 443
There's no way that you can use file_get_contents()
to open any files from the remote client's computer, unless they run it locally (they would also need to set up PHP for that) and then somehow submit it to your server.
file_get_contents()
allows you to open files that are on the same machine with your script, not on different ones
You can take a look at http://www.tizag.com/phpT/fileupload.php for an easy example of file uploaders
Upvotes: 1
Reputation: 46788
You shouldn't specify file://
To access local paths you can directly do
file_get_contents('C:/Users/me/Pictures/image1.jpg');
You can also navigate relative to current directory, using ../
based navigation like below
file_get_contents('../../../somefile.xyz');
EDIT: If you are trying to access a client-side file, i.e. remote paths that way, that wouldn't work. You need something like HTTP, FTP etc to transfer your file over. Simply giving a local file-system address isn't sufficient.
The end-point needs to somehow make the file available (HTTP/FTP server) or you need to get the client to upload it via the browser and an <input>
field.
Upvotes: 4