I want to send a POST request in a PHP script to another server and not wait for the response in any way.
I believe this does not work with curl (there is a async mode, but the PHP script would not return directly and still wait for the response) and I also don't want to introduce a curl dependency.
This answer works very well but works only for HTTP connections.
I have created a test script which I can access with HTTP (for testing) and HTTPS:
file_put_contents('/tmp/log', date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
$entityBody = file_get_contents('php://input');
file_put_contents('/tmp/log', var_export($_POST,true) . PHP_EOL, FILE_APPEND);
file_put_contents('/tmp/log', $entityBody . PHP_EOL, FILE_APPEND);
sleep(5000);
The sleep is there to test if the calling script really does not wait for the response.
And modified the code from the above answer to use port 443 by inserting:
if ($parts['scheme'] === 'https') {
$port = $parts['port'] ?? 443;
} else {
$port = $parts['port'] ?? 80;
}
So the full code is:
private function sendRequestAndForget(string $method, string $url, array $params = []): void
{
$parts = parse_url($url);
if ($parts === false)
throw new Exception('Unable to parse URL');
$host = $parts['host'] ?? null;
if ($parts['scheme'] === 'https') {
$port = $parts['port'] ?? 443;
} else {
$port = $parts['port'] ?? 80;
}
$path = $parts['path'] ?? '/';
$query = $parts['query'] ?? '';
parse_str($query, $queryParts);
if ($host === null)
throw new Exception('Unknown host');
$connection = fsockopen($host, $port, $errno, $errstr, 30);
if ($connection === false)
throw new Exception('Unable to connect to ' . $host);
$method = strtoupper($method);
if (!in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
$queryParts = $params + $queryParts;
$params = [];
}
// Build request
$request = $method . ' ' . $path;
if ($queryParts) {
$request .= '?' . http_build_query($queryParts);
}
$request .= ' HTTP/1.1' . "\r\n";
$request .= 'Host: ' . $host . "\r\n";
$body = json_encode($params);
if ($body) {
$request .= 'Content-Type: application/json' . "\r\n";
$request .= 'Content-Length: ' . strlen($body) . "\r\n";
}
$request .= 'Connection: Close' . "\r\n\r\n";
$request .= $body;
// Send request to server
fwrite($connection, $request);
fclose($connection);
}
When using http it works fine, when using https URLs it does not.