POST with file_get_contents in PHP

Typically, when you use the file_get_contents() function in PHP you make a GET request. It is possible, however, to make a POST request using the same tool.

	// Set the POST data
	$postdata = http_build_query(
		array(
			'email' => 'user@example.com',
			'name' => 'Some User'
		)
	);
 
	// Set the POST options
	$opts = array('http' => 
		array (
			'method' => 'POST',
			'header' => 'Content-type: application/xwww-form-urlencoded',
			'content' => $postdata
		)
	);
 
	// Create the POST context
	$context  = stream_context_create($opts);
 
	// POST the data to an api
	$url = 'http://www.example.com/api/do/something/';
	$result = file_get_contents($url, false, $context);
comments powered by Disqus
php/post_with_file_get_contents_from_php.txt · Last modified: 2020/06/01 22:53 (external edit)