There are ways to send a POST request to a page, between the more usual HTML submit a form
Assuming that you want to send information to another page, you would do the following:
<form name='ViniciusTest' method='POST' action='make_action.php'> <input type='hidden' name='field1' value='Value1'> <input type='text' name='field2'> <input type='text' name='field3'> <input type='submit'> </form>
But what if you wanted to send it directly by PHP without passing it by the user accessing the application?
I’ve seen a lot of “ workaround ” to do such a simple thing, the company where I am now (Netmake http://www.scriptcase.net/ ), it’s incredible imagination to do so.
Well, there are several ways to do this, not saying that there is the right and wrong … but there are certainly simple.
The same as the above HTML code would submit, you could use the code:
$content = http_build_query (array ( 'field1' => 'Value1', 'field2' => 'Value2', 'field3' => 'Value3' )); $context = stream_context_create (array ( 'http' => array ( 'method' => 'POST', 'content' => $content, ) )); $result = file_get_contents('http://exemplo/make_action.php', null, $context);
Explaining the code
The first line code
$content = http_build_query(array(
, the http_build_query says as php Gera’s own documentation the query string (query) in URL format http://br1.php.net/http_build_query , in short, the function will transform an array of data, in a form of query, in case it would be something like:
In the sixth line we find the stream_context_create http://php.net/stream_context_create , we will create a streaming context, ie the request will prepare the same way as is done by the browser before sending to php when we submit the form.
And finally the file_get_contents , one of my favorite features in php (already swept much to her site). She will make the request for the page, in case http://exemplo/make_action.php , sending the generated context in stream_context_create , and will take the output of the page and putting in $ variable result;
Simple huh? This is my favorite way, however there are others, if you are interested search for curl
If you wish to receive more information and tips on PHP and linux, subscribe to our list here ! In the next post to learn some tips on writing and reading files with only two functions and a very easy way. If liked, like the one on the page, and / or comment below.