views:

54

answers:

4

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 text file, but how do I load this file as the arg1 item of the array?

Any help would be appreciated.

A: 

You could pass the file name as arg1, and then on the receiving end, open it with

$contents = file_get_contents($_POST['filename']);
hookedonwinter
I can't read the contents of the original file from the other server, the file itself must be sent as part of the POST request.
Daniel
+2  A: 

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

Brian Driscoll
Thanks but I don't have that PECL extension installed on this server and don't have rights to install it either. :-(
Daniel
+2  A: 

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";
Sam Starling
I actually don't have a file at all. The info I need to send is serialized data that's in a variable, however the server will not accept that, it will only accept a text file named data.txt with the serialized data in it. So I need to convert the contents of this variable into a text file named data.txt and then send the text file as part of the POST request. I already created the local text file data.txt, but I'm not sure how I can include it in the POST request.
Daniel
@Daniel can you just send the filename across (see my answer) and then read the contents there?
hookedonwinter
Daniel, are you saying that it must work in a similar way to how a file upload in a form might work?
Sam Starling
A: 

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.

Marc B