POST data to a URL in PHP

PhpPost

Php Problem Overview


How can I send POST data to a URL in PHP (without a form)?

I'm going to use it for sending a variable to complete and submit a form.

Php Solutions


Solution 1 - Php

If you're looking to post data to a URL from PHP code itself (without using an html form) it can be done with curl. It will look like this:

$url = 'http://www.someurl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
	
$response = curl_exec( $ch );

This will send the post variables to the specified url, and what the page returns will be in $response.

Solution 2 - Php

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$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);
var_dump($result);

Solution 3 - Php

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBelgin FishView Question on Stackoverflow
Solution 1 - PhpPeter AnselmoView Answer on Stackoverflow
Solution 2 - PhpPhd. Burak ÖztürkView Answer on Stackoverflow
Solution 3 - PhpjfoucherView Answer on Stackoverflow