J
J
Julia Kovalenko2016-07-20 14:41:44
PHP
Julia Kovalenko, 2016-07-20 14:41:44

How to send send requests through my server?

The bottom line is this: I have a mobile application that sends requests to the main server and receives responses from there.
I want to send requests not directly, but through another additional server.
On an additional server, I wrote a script:

<?php
$curl = curl_init();

$url = substr($_SERVER['REQUEST_URI'], 1);

curl_setopt($curl, CURLOPT_URL,  $url);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, getallheaders());

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $_POST);
}

$res = curl_exec($curl);

$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($res, 0, $header_size);
$body = substr($res, $header_size);

$out = fopen('php://output', 'w');
fputs($out, $headers . PHP_EOL . PHP_EOL . $body);
fclose($out);
curl_close($curl);

die;

But in this case, when sending a response to the application, my additional server sent some kind of headers, and what I threw in php://output was considered everything as the request body. Like this:
8f11b8eddc5445168b9e024ab8e087ea.png
I tried this:
...
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($res, 0, $header_size);
$body = substr($res, $header_size);

$headers = explode(PHP_EOL, trim($headers));

foreach ($headers as $header) {
    header($header);
}

$out = fopen('php://output', 'w');
fputs($out, $body);
fclose($out);
...

But that doesn't work at all. Writes that the server unexpectedly terminated the connection.
How to implement what I need?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Julia Kovalenko, 2016-07-21
@kovalenko_jul_s

$headers = explode(PHP_EOL, trim($headers));
the error was here.
do not need PHP_EOL, but "\r\n";
and also curl_setopt($curl, CURLOPT_HTTPHEADER, getallheaders());
getallheaders() returns an associative array. and you need an array like
['Content-type: text/plain', 'Content-length: 100']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question