Bernd82
Bernd82

Reputation: 33

Call a PHP from another PHP (without cURL)

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?

Upvotes: 2

Views: 1004

Answers (3)

Bernd82
Bernd82

Reputation: 33

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!

Upvotes: 0

Fred Koschara
Fred Koschara

Reputation: 355

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.

Upvotes: 0

Robert
Robert

Reputation: 20286

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']

Upvotes: 2

Related Questions