file_get_contents()経由でPOSTを送信します

Webページのコンテンツを取得するには、file_get_contents()、たとえばfile_get_contents( 'http://www.habrahabr.ru/')を使用して、誰もが喜んでfile_get_contents()を使用します。 しかし、POSTの送信に関しては、開発者はCURLまたはopen socketsを使用することを長い間観察してきました。 これが悪いとか、そうする必要はないと思います。単純な解決策を使用して単純な問題を解決できます。

PHPでストリーミング操作コンテキストの概念に出くわすまで、私自身もこれを実行しました。 コンテキストを使用すると、追加のパラメーターをストリームハンドラーに渡すことができます。 たとえば、httpの場合、POST要求を構成するか、追加のヘッダーを渡すことができます。

file_get_contents()は、「context」パラメーターで3を受け入れます。これは、実際に要求自体を構成します。
以下は、そのようなリクエストまたは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 .


次のファイル関数はコンテキストを受け入れます。


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


All Articles