In PHP, I need to make a POST request, but one of the variables must be a text file. How do I do it?
Here's what I need to do. In my PHP script, I need to make a POST request, but one of the arguments must be sent as a text file named data.txt. I already wrote a little script that will send the POST request and send the arguments. The server expects an argument that's an array with two elements, arg0 and arg1. arg0 is a regular string, but arg1 must be a text file. The contents of this file is serialized data that's in a variable. I was able to save the contents of this variable to a local开发者_如何学JAVA text file, but how do I load this file as the arg1 item of the array?
Any help would be appreciated.
If you're using HttpRequest (PHP 5.3) there is a method called addPostFile that you can use. See the documentation here: http://us2.php.net/manual/en/function.httprequest-addpostfile.php
You don't specify how you're making the POST request, but if you want to use the contents of the file as an argument in the request, then when you construct the data, you can use something like this:
$filecontents = file_get_contents('/path/to/your_file.txt');
$data = "arg0=foo&arg1=$filecontents";
You could pass the file name as arg1, and then on the receiving end, open it with
$contents = file_get_contents($_POST['filename']);
Do you have access to CURL on this server?
$c = curl_init();
curl_setopt($c, CURLOPT_POST, TRUE);
curl_setopt($c, CURLOPT_URL, 'http://server.you/want/to/upload/to');
curl_setopt($c, CURLOPT_POSTFIELDS, "arg0=some+data+in+urlencoded+format&arg1=@name_of_file_with_full_path");
$res = curl_exec($c);
if($res === FALSE) {
die("CURL failed: " . curl_error());
}
If that's not possible, but you can still build and the POST query by some other method, you can always build a full 'multipart/form-data' message yourself and paste in the file's contents in the right spot.
精彩评论