📜 ⬆️ ⬇️

Send POST via file_get_contents ()

To get the contents of a web page, everyone is happy to use file_get_contents (), for example file_get_contents ('http://www.habrahabr.ru/'). But I’ve been observing for a long time that, as it comes to sending POST, developers use either CURL or open sockets . I do not think that this is bad or that it is not necessary to do so, just for solving simple problems, you can use simple solutions.

I did it myself before, until I came across the concept of streaming context contexts in PHP. Context allows you to pass additional parameters to the streaming handler. For http, for example, you can configure a POST request or send additional headers.

file_get_contents () takes 3 parameters "context", which actually configures the request itself.
Below is an example of such a request or RTFM
')


<?php
error_reporting(E_ALL);
require_once 'simpletest/unit_tester.php' ;
require_once 'simpletest/default_reporter.php' ;

define( 'PARAM_NAME' , 'var' );
define( 'PARAM_VALUE' , 'testData' );
define( 'QUERY' , 'var=testData' );

/**
*
*/
class FileGetContentsTest extends UnitTestCase {

/**
* , POST
*/
public function testIsPost() {
$ this ->assertEqual( 'POST' , $_SERVER[ 'REQUEST_METHOD' ],
'Expected POST request' );
$ this ->assertTrue(isset($_POST[PARAM_NAME]) && $_POST[PARAM_NAME] == PARAM_VALUE,
'Expected POST contains ' . QUERY);
}
}

/**
* POST
*/
if (!$_SERVER[ 'QUERY_STRING' ]) {

// POST
$context = stream_context_create(array(
'http' => array(
'method' => 'POST' ,
'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL,
'content' => QUERY,
),
));

// ,
//
echo file_get_contents(
$file = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}?runTests" ,
$use_include_path = false ,
$context);

/**
*
*/
} else {
$suite = new FileGetContentsTest;
$suite->run( new DefaultReporter());
}

* This source code was highlighted with Source Code Highlighter .


The following file functions accept contexts:


Source: https://habr.com/ru/post/48726/


All Articles