Call a PHP from another PHP (without cURL) - php

I have a HTML page that has to call a PHP on another domain. The "Same-Origin-Rule" of most browsers prohibits that call. So I want to call a PHP on my domain to call a PHP on the target domain. I want to avoid cURL so I decided to use fopen in that pass-through PHP using $context:
$params = array('http' => array('method'=>'POST',
'header'=>'Content-type: application/json',
'content'=>json_encode($_POST)));
$ctx = stream_context_create($params);
$fp = fopen('https://other_domain.com/test.php', 'rb', false, $ctx);
$response = stream_get_contents($fp);
echo $response;
But the incoming $_POST in test.php seems to be empty. Any ideas?

Try to build params with http_build_query()
$postdata = http_build_query(
array(
'json' => json_encode($_POST),
)
);
and then
$params = array('http' => array('method'=>'POST',
'header'=>'Content-type: application/x-www-form-urlencoded',
'content'=> $postdata));
On the other site get it via $_POST['json']

Unless you have a server that supports application/json as a POST content type, your code isn't going to work: HTTP servers expect POST data to always be one of application/x-www-form-encoded or multipart/form-data. You need to rewrite your code to send the POST data in one of the supported types.

I managed it this way:
$postData = file_get_contents('php://input');
$params = array('http' => array('method'=>'POST',
'header'=>'Content-type: application/x-www-form-urlencoded',
'content'=>$postData));
$ctx = stream_context_create($params);
$url = 'https://other_domain.com/test.php';
$fp = fopen($url, 'rb', false, $ctx);
$response = stream_get_contents($fp);
echo $response;
This easily hands trough all incoming POST data and also forwards any responses. Thanks for all your posts!

Related

PHP : file_get_contents not working properly

I have a html page which sends a get request to php.
This is the code snippet in the php file
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>'GET',
)
);
$context = stream_context_create($opts);
//echo("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token={$_GET['token']}&agencyName={$_GET['agency']}&stopName={$_GET['stopname']}");
// Open the file using the HTTP headers set above
$file = file_get_contents("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token={$_GET['token']}&agencyName={$_GET['agency']}&stopName={$_GET['stopname']}", false, $context);
//$file = file_get_contents("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token=123-456-789&agencyName=SF-MUNI&stopName=The%20Embarcadero%20and%20Folsom%20St", false, $context);
echo(json_encode(simplexml_load_string($file)));
?>
Developer Console Output :
Warning: file_get_contents(http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?token=123-456-789&amp;agencyName=BART&amp;stopName=Powell St. (SF)): failed to open stream: HTTP request failed! HTTP/1.1 400 BAD_REQUEST
As you can see from the developer console output, in the url request sent there are BART&amp;stopName amp;amp; being inserted in the url which I'm not doing. The request fails due to this. Any solution around this?
Try the below code, this will make sure that you're stuff is properly URI encoded.
$params = [
'token' => $_GET['token'],
'agencyName' => $_GET['agency'],
'stopName' => $_GET['stopname']
];
$file = file_get_contents(sprintf("http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?%s", http_build_query($params));
echo(json_encode(simplexml_load_string($file)));
Try this one:
$data = array('token'=>$_GET['token'],
'stopname'=>$_GET['stopname'],
'agency'=>$_GET['agency'],
);
$url = "http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?".$data;
$file = file_get_contents($url, false, $context);
echo(json_encode(simplexml_load_string($file)));
Note: I have modified my answer base on your comment.
You can try this way to clean out the url:
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>'GET',
)
);
$context = stream_context_create($opts);
$url= "http://services.my511.org/Transit2.0/GetNextDeparturesByStopName.aspx?";
$query = array(
"token" =>$_GET['token'],
"agencyName"=>$_GET['agency'],
"stopName"=>$_GET['stopname']
);
$url = $url.http_build_query($query);
$url = rawurldecode($url);
print_r($url);
$file = file_get_contents($url, false, $context);
echo(json_encode(simplexml_load_string($file)));
?>

using a context-stream resource with file_get_contents returns a NULL string

I'm using PHP 4.3.9 and am trying to POST to a url without a form using stream_context_create like below:
function do_post_request($url, $postdata) {
$content = "";
foreach($postdata as $key => $value)
$content .= "$key=$value&";
$content = urlencode($content);
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $content
));
$ctx = stream_context_create($params);
$result = file_get_contents($url, false, $ctx);
var_dump($result);
This code is taken almost word for word from the php manual and I've seen it in several places here on stackoverflow as well.
If I do file_get_contents without $ctx, var_dump($results) will display the $url properly (but without the necessary changes $_POST would cause, of course). With $ctx, var_dump($result) is NULL. So something is wrong with $ctx but I have no idea what. Am I setting up my $params incorrectly or something?
Any insight would be appreciated. If there is another way to pass POST data to a url I wouldn't mind hearing that either. But I cannot use cURL (or anything that needs installation) and I'm using an older version of php so my choices are limited.
Thanks

Can't send data in post request via file_get_contents

Need to request some code two times in my app. Fist request url as ajax call, and also need to request this url in controller (something like hmvc). I know how to develop this via curl but I found another kind of idea how to implement this, just use function file_get_contents with before prepared params. This my code:
// Setup limit per page
$args['offset'] = $offset;
$args['limit'] = $this->_perpage;
// --
// Convert search arguments to the uri format
$data = http_build_query($args);
// Define request params
$options = array(
'http' => array(
'header' => 'Content-type: application/json' . PHP_EOL .
'Content-Length: ' . strlen($data) . PHP_EOL,
'method' => 'POST',
'content' => $data,
),
);
$context = stream_context_create($options);
$result = file_get_contents(
'http://'.$_SERVER['HTTP_HOST'].'/search/items', FALSE, $context
);
Request method was detected ok in requested uri, but params wasn't passed. Why this is not pass arguments to request? Where is bug in my code? Many thanks for any answers.
http_build_query builds application/x-www-form-urlencoded content. (not application/json)
There is a full example:
How to post data in PHP using file_get_contents?
Content type should be application/x-www-form-urlencoded. If you want to stay with application/json, try to get posted data using file_get_contents("php://input").

HTTP POST from PHP, without cURL

I am using the example function given in this post:
<?php
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
?>
I also tried a similar approach using file_get_contents(), like this:
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(
array(
'arg1'=>'arg_data_1',
'oper'=>'get_data',
'arg2'=>'arg_data_2',
'id_number'=>'7862'
),'','&'
)
));
$context = stream_context_create($options);
$refno = file_get_contents('/path/to/script/script.php',false,$context);
var_dump($refno);
With both these scripts, the response from the server script is the same, and it is the TEXT of the script.php. The code of the server script is never begin executed, and the text content (the PHP code) of the script is being returned to the original script.
A little strange that it doesn't return all the text, but just certain pieces... I tried making a test script (test.php) that just contains:
<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>
but that doesn't return anything from the POST request, so I didn't include that. The script.php is a must longer script that does a lot of logic and MySQL queries then returns a JSON object.
The desired output will be to have the PHP code execute and return a JSON object (the way it works with ajax).
What am I doing wrong?
You are trying access script localy.
You must call it like any other external script like
$refno = file_get_contents('http://yourhost/path/to/script/script.php',false,$context);

Sending httprequest from localhost

function PostRequest($url) {
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Cookie: testcookie=blah; testcookie2=haha;'
)
);
//$context = stream_context_create($opts);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
return $result;
}
After I sent out the cookies, I still return by a message non login. but when I surf the pages with browser, I am login.
I sent request with localhost then I tried to used ajax to sent the request, but return status 0......
Is there any way to sent out the request?
If you want to play with HTTP scripting, i have library which you can use. https://github.com/toopay/CI-Proxy-Library, its orriginally written for CodeIgniter, but with little tweak, you should can use it on any PHP script.

Categories