in Web and Tech, Work

PHP: Passing POST data from script to script

This is how to pass data via POST to another processing script but not via the usual HTML form submission. Say a data from a form is submitted and is passed through an initial processing script and then you now want to pass the processed data onto another script. 

Non-CURL solution:

$url = 'http://server.com/path';
$data = array('key1' => 'value1', 'key2' => 'value2');

// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

CURL solution:

//The url you wish to send the POST request to
$url = $file_name;

//The data you want to send via POST
$fields = [
'__VIEWSTATE ' => $state,
'__EVENTVALIDATION' => $valid,
'btnSubmit' => 'Submit'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
echo $result;

CURL is deemed to be the more optimal solution here but there are environments where CURL is not enabled, hence, the non-CURL solution.

References:
https://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php
https://www.php.net/manual/en/context.http.php
https://www.php.net/manual/en/function.stream-context-create.php

Write a Comment

Comment