[PHP]使用file_get_content來進行post request

在 php 程式中, 使用 curl 來進行 web request 是常用的方式, 不過由於在 https://repl.it/ 這個服務中, php webserver 並未安裝 curl, 所以需要改用 file_get_content()這個函數來進行 web request, 然而若為一般的 get request, 直接將網址傳入即可, 但若需要進行 post request 要如何操作呢?

這時會用到一個 http context options:

https://www.php.net/manual/en/context.http.php

範例程式如下:

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

也就是利用了 http context options 來組合出要傳遞的參數. 如此一來便能很快速地應用在僅有 file_get_contents() 環境而沒有 curl 的 php webserver 環境來進行 post request.

參考資料:

https://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents

https://www.php.net/manual/en/context.http.php