Making http request using pure PHP - php

I was trying to make my php code send http request with its own (I don't want to use external libraries like CURL for now),but I can't find the right tag or I don't know how to use $_POST for this purpose. Any help please

If it's a GET request, using file_get_contents, maybe you can try something like this:
<?php
$test = file_get_contents("http://example.com/");
var_dump($test);
?>
If it's a POST request, using fsock, maybe you can try something like this:
<?php
$domain = 'dummy.restapiexample.com';
$fp = fsockopen($domain, 80);
$vars = array(
'name' => 'test',
'salary' => '123',
'age' => '23'
);
$content = http_build_query($vars);
fwrite($fp, "POST /api/v1/create HTTP/1.1\r\n");
fwrite($fp, "Host: $domain\r\n");
fwrite($fp, "Content-Type: application/json\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
header('Content-type: text/plain');
while (!feof($fp)) {
echo fgets($fp, 1024);
}
?>

Related

How to POST to an XML API?

We are integrating the travel API of www.transhotel-dev.com.
The code is like this:
<?php
$servletHOST = "www.transhotel-dev.com";
$servletPATH = "/interfaces/SController";
$pXML = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><Login><Username>Username</Username><Password>Password</Password></Login>";
$pCall = "Login";
$postdata = "pXML=" . urlencode($pXML) . "&pCall=" . urlencode($pCall);
$fp = pfsockopen($servletHOST, 1184);
if ($fp) {
fputs($fp, "POST $servletPATH HTTP/1.0\n");
fputs($fp, "Accept: */*\n");
$strlength = strlen( $postdata );
fputs($fp, "Content-length: " . $strlength . "\n\n");
fputs($fp, $postdata . "\n" );
$output = "";
while (!feof($fp)) {
$output .= fgets($fp, 1024);
}
fclose($fp);
echo $output;
}
?>
HTTP compression and POST method are required to go beyond this point. Can anybody help?
The following calls require the use of https secure protocol
(https://www.transhotel-dev.com:1449/interfaces/SController):
Login
AddAmountCardHPlus
GetNifInvoices
NifAgencyReservations
NifHotelReservations
ConfirmReservation (When contain the data of a credit card)
BuildSearchForm
LoginRQ
LoginB2B
CreateAgency
NifActivitiesReservations
GetActivitiesProvider
NifTransfersReservations
GetTransfersProvider
LoginHPlus
UserLogInHPlus
so you should use ssl protocol for login action:
$fp = pfsockopen("ssl://www.transhotel-dev.com", 1449);

Parameters not posted when using fsockopen and fwrite

I am trying to post parameters from php to another server. When creating the link manually and opening it in the browser it works fine. But when trying to do it from my php-script it doesn't work. The file I am accessing is accessed, but the parameter is not posted.
I guess the problem has to do with how I define and post the parameter ($post_data .= "?companyid=banane";). What is my problem and how do I solve it?
<?php
$fp = fsockopen("192.168.1.102", 80, $errno, $errstr, 30);
error_log("write done");
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$post_data = "GET /cgi-bin/new_instance.pl HTTP/1.1\r\n";
$post_data .= "Host: 192.168.1.102\r\n";
$post_data .= "Connection: Close\r\n\r\n";
$post_data .= "?companyid=banane";
error_log("OUT - - - ".$post_data);
fwrite($fp, $post_data);
error_log("write done");
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
Or am I using the wrong approach? I'm thinking, if this is the correct approach then I should be able to find some good examples when googling around.
Try this as the first line instead:
GET /cgi-bin/new_instance.pl?companyid=banane HTTP/1.1\r\n

Making a REST API request in PHP

Apologies for newbishness of this question. I'm looking into integrating one website's API into my own website. Here's some quotes from their documentation:
At the moment we only support XML,
when calling our API the HTTP Accept
header content type must be set to
“application/xml”.
The API uses the PUT request method.
I have the XML I want to send, and I have the URL I want to send it to, but how do I go about constructing a suitable HTTP Request in PHP that will also grab the XML that's returned?
Thanks in advance.
You can use file_get_contents and stream_context_create to create a request and read the response. Something like this will do it:
$opts = array(
"http" => array(
"method" => "PUT",
"header" => "Accept: application/xml\r\n",
"content" => $xml
)
);
$context = stream_context_create($opts);
$response = file_get_contents($url, false, $context);
This is actually what worked for me:
$fp = fsockopen("ssl://api.staging.example.com", 443, $errno, $errstr, 30);
if (!$fp)
{
echo "<p>ERROR: $errstr ($errno)</p>";
return false;
}
else
{
$out = "PUT /path/account/ HTTP/1.1\r\n";
$out .= "Host: api.staging.example.com\r\n";
$out .= "Content-type: text/xml\r\n";
$out .= "Accept: application/xml\r\n";
$out .= "Content-length: ".strlen($xml)."\r\n";
$out .= "Connection: Close\r\n\r\n";
$out .= $xml;
fwrite($fp, $out);
while (!feof($fp))
{
echo fgets($fp, 125);
}
fclose($fp);
}

Getting Results from an url with sending it url variables

i need to send get command and take it's results. Sorry about my bad english.
i need to get result from a file whish sended url parameters
for example:
<?php
$adata["command1"] = "testcommand1";
$adata["command2"] = "testcommand2";
$getresult = sendGetCommand("https://website.com/api.html", $arrayofdata);
echo "["; // for json data;
$arrayresult = explode("\n",$getresult);
foreach ($getresult in $line) {
$arrayline = explode("\n",$line);
echo "{ ";
foreach ($arrayline in $cmdid => $cmd) {
echo "'".$cmdid."' : '".$cmd."',";
}
echo "{";
}
?>
somethink like this..
url is like:
"https://website.com/api.html?command1=testcommand1&command2=testcommand2"
url result is like:
command1,testcommand1,,yes
command2,testcommand2,,error,error text here
i'll explode the data line by line and then get the data from JavaScript
this is a domain search api.
another question:
explode("\n",$string) can be used for read it line by line? (windows os)
are you talking about file_get_contents? you can create the url with something like:
$url = "https://website.com/api.html?command1=".$adata["command1"]."&command2=".$adata["command2"];
$getresult = file_get_contents($url);
good luck;
for reading the result, you should take a look at str_getcsv and/or fgetcsv instead of doing this by hand using explode.
EDIT: for sending a get-request, you should take a look at fsockopen and its examples. you could use a function like this (just change POST to GET and the content-type like you need it):
function _get($type,$host,$port='80',$path='/',$data='') {
$_err = 'lib sockets::'.__FUNCTION__.'(): ';
switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port');
if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1);
$fp = fsockopen($host,$port,$errno,$errstr,$timeout=30);
if(!$fp) die($_err.$errstr.$errno); else {
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ".strlen($str)."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $str."\r\n\r\n");
while(!feof($fp)) $d .= fgets($fp,4096);
fclose($fp);
} return $d;
}

PHP Post data with Fsockopen

I am attempting to post data using fsockopen, and then returning the result.
Here is my current code:
<?php
$data="stuff=hoorah\r\n";
$data=urlencode($data);
$fp = fsockopen("www.website.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "POST /script.php HTTP/1.0\r\n";
$out .= "Host: www.webste.com\r\n";
$out .= 'Content-Type: application/x-www-form-urlencoded\r\n';
$out .= 'Content-Length: ' . strlen($data) . '\r\n\r\n';
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
It is supposed to echo the page, and it is echoing the page, but here is the script for script.php
<?php
echo "<br><br>";
$raw_data = $GLOBALS['HTTP_RAW_POST_DATA'];
parse_str( $raw_data, $_POST );
//test 1
var_dump($raw_data);
echo "<br><br>":
//test 2
print_r( $_POST );
?>
The outcome is:
HTTP/1.1 200 OK Date: Tue, 02 Mar 2010
22:40:46 GMT Server: Apache/2.2.3
(CentOS) X-Powered-By: PHP/5.2.6
Content-Length: 31 Connection: close
Content-Type: text/html; charset=UTF-8
string(0) "" Array ( )
What do I have wrong? Why isn't the variable posting its data?
There are many small errors in your code. Here's a snippet which is tested and works.
<?php
$fp = fsockopen('example.com', 80);
$vars = array(
'hello' => 'world'
);
$content = http_build_query($vars);
fwrite($fp, "POST /reposter.php HTTP/1.1\r\n");
fwrite($fp, "Host: example.com\r\n");
fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($fp, "Content-Length: ".strlen($content)."\r\n");
fwrite($fp, "Connection: close\r\n");
fwrite($fp, "\r\n");
fwrite($fp, $content);
header('Content-type: text/plain');
while (!feof($fp)) {
echo fgets($fp, 1024);
}
And then at example.com/reposter.php put this
<?php print_r($_POST);
When run you should get output something like
HTTP/1.1 200 OK
Date: Wed, 05 Jan 2011 21:24:07 GMT
Server: Apache
X-Powered-By: PHP/5.2.9
Vary: Host
Content-Type: text/html
Connection: close
1f
Array
(
[hello] => world
)
0
At no point is $data being written to the socket. You want to add something like:
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fwrite($fp, $data);
Try this instead
$out .= 'Content-Length: ' . strlen($data) . '\r\n';
$out .= "Connection: Close\r\n\r\n";
$out .= $data;
Try this:
<?php
$data="stuff=hoorah\r\n";
$data=urlencode($data);
$fp = fsockopen("www.website.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "POST /script.php HTTP/1.0\r\n";
$out .= "Host: www.webste.com\r\n";
$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
$out .= 'Content-Length: ' . strlen($data) . "\r\n\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fwrite($fp, $data);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>
Some character escapes such as \n do not work in single quotes.
Nice one Tamlyn, works great!
For those that also need to send get vars along with the url,
//change this:
fwrite($fp, "POST /reposter.php HTTP/1.1\r\n");
//to:
$query = 'a=1&b=2';
fwrite($fp, "POST /reposter.php?".$query." HTTP/1.1\r\n");
Try this in reposter.php
$raw_data = $GLOBALS['HTTP_RAW_POST_DATA'];
parse_str( $raw_data, $_POST );
print_r( $_POST );
Because, the data wasn't in the $_POST[] variables but it was in the $GLOBALS['HTTP_RAW_POST_DATA'] variable.
you can use this technique it will help to call as many as pages you like all pages will run at once independently without waiting for each page response as asynchronous.
cornjobpage.php //mainpage
<?php
post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue");
//post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue2");
//post_async("http://localhost/projectname/otherpage.php", "Keywordname=anyValue");
//call as many as pages you like all pages will run at once independently without waiting for each page response as asynchronous.
?>
<?php
/*
* Executes a PHP page asynchronously so the current page does not have to wait for it to finish running.
*
*/
function post_async($url,$params)
{
$post_string = $params;
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "POST ".$parts['path']."?$post_string"." HTTP/1.1\r\n";//you can use GET instead of POST if you like
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
}
?>
testpage.php
<?
echo $_REQUEST["Keywordname"];//case1 Output > testValue
?>
PS:if you want to send url parameters as loop then follow this answer :https://stackoverflow.com/a/41225209/6295712
Curl is too heavy in some case, to use post_to_host():
//GET:
$str_rtn=post_to_host($str_url_target, array(), $arr_cookie, $str_url_referer, $ref_arr_head, 0);
//POST:
$arr_params=array('para1'=>'...', 'para2'=>'...');
$str_rtn=post_to_host($str_url_target, $arr_params, $arr_cookie, $str_url_referer, $ref_arr_head);
//POST with file:
$arr_params=array('para1'=>'...', 'FILE:para2'=>'/tmp/test.jpg', 'para3'=>'...');
$str_rtn=post_to_host($str_url_target, $arr_params, $arr_cookie, $str_url_referer, $ref_arr_head, 2);
//raw POST:
$tmp=array_search('uri', #array_flip(stream_get_meta_data($GLOBALS[mt_rand()]=tmpfile())));
$arr_params=array('para1'=>'...', 'para2'=>'...');
file_put_contents($tmp, json_encode($arr_params));
$arr_params=array($tmp);
$str_rtn=post_to_host($str_url_target, $arr_params, $arr_cookie, $str_url_referer, $ref_arr_head, 3);
//get cookie and merge cookies:
$arr_new_cookie=get_cookies_from_heads($ref_arr_head)+$arr_old_cookie;//don't change the order
//get redirect url:
$str_url_redirect=get_from_heads($ref_arr_head, 'Location');
post to host php project location: http://code.google.com/p/post-to-host/
Is using cURL and option?
Sorry for refresh, but for people who still have problem like this, change HTTP/1.0 to HTTP/1.1 and it will work.

Categories