[thelist] POST data with PHP

Kasimir K evolt at kasimir-k.fi
Thu Aug 12 04:15:16 CDT 2004



Richard Livsey wrote on 12/08/2004 4:52:
> A tricky one this, and I'm not sure if it is at all possible, but here goes.
> 
> 1. I have a form which points to a PHP script.
> 2. When the script receives the POST data, it validates it.
> 3. If the data doesnt validate, a page is displayed with details.
> 4. If the data validates, then the POST data wants to be sent on to 
> another page which may not be on the same server.
> 
> Is step 4 possible?

I haven't done this myself, but it should be possible. Below is a 
function I use to make GET requests, it's fairly easy to change it for 
POST's.

So your script would:
1. receive POST data
2. validate it
3. if not valid, output stuff and exit
    else
4. make a POST request, and read the response
5. output the response

In the following function $file_path contains all variables to be sent 
in GET request: scriptdir/script.ext?var1=foo&var2=bar

Have a look at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5
for info on HTTP requests.

With GET you use only Request-line, with POST you use also a 
message-body, in which you have the data to pass. With POST you may need 
some headers too: e.g. Content-Length.

At
http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4
it says that:
"For compatibility with HTTP/1.0 applications, HTTP/1.1 requests 
containing a message-body MUST include a valid Content-Length header 
field unless the server is known to be HTTP/1.1 compliant."

So your request would then look something like this:

POST /scriptdir/script.ext HTTP/1.0
Content-Length: 17

var1=foo&var2=bar


hth,
.k

=============================================================================

function http_get_request($host, $file_path)
{
	$error = false;
	$response = '';
	$service_port = 80;
	$address = gethostbyname($host);
	$request = "GET /".$file_path." HTTP/1.0\r\n\r\n";
	
	$socket = socket_create(AF_INET, SOCK_STREAM, 0)
		or $error .= 'socket_create()  failed: 
'.socket_strerror(socket_last_error());
	$connected = socket_connect($socket, $address, $service_port)
		or $error .= 'socket_connect() failed: 
'.socket_strerror(socket_last_error());
	if ($connected)
	{
		socket_write($socket, $request, strlen($request));
		while ($read = socket_read($socket, 2048, PHP_BINARY_READ))
		{
			$response .= $read;
		}
	}
	socket_close ($socket);
	
	//	there are two CRLFs before message-body:
	$response = preg_split('/\r\n\r\n/', $response, -1, PREG_SPLIT_NO_EMPTY);
	$response['header'] = $response[0];	
	$response['content'] = $response[1];
	$response['status_code'] = substr($response['header'], 
strpos($response['header'],' ') + 1, 3);
	$response['error'] = $error;
	
	return $response;
}


More information about the thelist mailing list