Solo
Solo

Reputation: 726

Sending a POST request without submitting an HTML form

I am wondering, is it possible to send an HTTP POST in PHP without using an HTML form. Can this be done internally using PHP? If not, maybe using JavaScript or jQuery?

Upvotes: 3

Views: 4511

Answers (4)

ilanco
ilanco

Reputation: 9967

There are several ways to create a POST request in PHP, this one is using bare PHP code, no external libraries required:

<?php
function postRequest($url, $data, $optionalHeaders = null)
{
    $params = array('http' => array(
        'method' => 'POST',
        'content' => $data
    ));
    if ($optionalHeaders !== null) {
        $params['http']['header'] = $optionalHeaders;
    }

    $ctx = stream_context_create($params);
    $fp = @fopen($url, 'rb', false, $ctx);
    if (!$fp) {
        throw new Exception("Problem with $url, $errormsg");
    }
    $response = @stream_get_contents($fp);
    if ($response === false) {
        throw new Exception("Problem reading data from $url, $errormsg");
    }

    return $response;
}

Upvotes: 4

Julian
Julian

Reputation: 4676

You can use cURL php extension. Below you can examine the code:

<?php
function httpPost($url,$params){
  $postData = '';
   //create name value pairs seperated by &
   foreach($params as $k => $v)
   {
      $postData .= $k . '='.$v.'&';
   }
   rtrim($postData, '&');


$ch = curl_init(); 

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);   

$output=curl_exec($ch);

curl_close($ch);
return $output;


}

$params = array(
   "name" => "Ravishanker Kusuma",
   "age" => "32",
   "location" => "India"
);

echo httpPost("http://www.jmediatechnology.eu/script.php",$params);
?>

More examples here: http://hayageek.com/php-curl-post-get/#curl-post

Upvotes: 0

olovholm
olovholm

Reputation: 1392

yes. It is possible to send an HTTP POST or GET request using almost any language. I am no expert in PHP, but try looking for a method which deals with HTTPRequests and add the POST-data to a request using methods of such a library.

Upvotes: 0

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26739

Yes, you can. The simpler solution is to use curl. Also, you can just open a socket to the remote server and send raw HTTP request.

See curl examples in the documentation

Upvotes: 6

Related Questions