LoginSignup
17
12

More than 5 years have passed since last update.

【PHP】httpリクエストPOST&GET

Last updated at Posted at 2017-04-12

HTTPリクエスト通信(POST通知)

送信側:
  • POST送信処理(送信先URL、送信内容)
  • レスポンス状態チェック
sample
function connectByPost($url, $argary) {
 //$url = "http://localhost/example.php";
 //$argary = array('Apple','Banana','love' => 'Orange');

 // URLエンコードされたクエリ文字列を生成する
 $query_string = http_build_query($argary);

 // HTTP設定
 $options = array (
    'http' => array (
        'method' => 'POST',
        'header' => 'Content-type: application/x-www-form-urlencoded',
        'content' => $query_string,
        'ignore_errors' => true,
        'protocol_version' => '1.1'
        ),
    'ssl' => array (
        'verify_peer' => false,
        'verify_peer_name' => false
        )
    );
 $contents = @file_get_contents($url, false, stream_context_create($options));

 // レスポンスステータス
 $statusCode = http_response_code();
 if($statusCode === 200) {
    // 200 success
 } elseif(preg_match ("/^4\d\d/", $statusCode)) {
    // 4xx Client Error
    $contents = false;
 } elseif(preg_match ('/^5\d\d/', $statusCode)) {
    // 5xx Server Error
    $contents = false;
 } else {
    $contents = false;
 }

 return $content;
}
POST受信側:
  • ログ出力
  • POST内容
  • リクエスト内容
example.php
$path = "../logs/example.log";
$file = fopen($path, "w");

fputs($file, "=========== Example ===========\r\n");
fputs($file, "GET  : " . json_encode ( $_GET ) . "\r\n");
fputs($file, "POST : " . json_encode ( $_POST) . "\r\n");

fputs($file, "=========== Request ===========\r\n");
fputs($file, file_get_contents('php://input'));
fclose($file);

print "<SENBDATA>STATUS=800</SENBDATA>";
結果確認:
  • ログ内容確認
example.log
=========== Example ===========
GET  : []
POST : {0:"Apple",1:"Banana","love":"Orange"}
=========== Request ===========
0=Apple&1=Banana&love=Orange

---I Love PHP (。・ω・。)ノ♡

17
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
12