How to find the origin of the request in PHP?

Asked

Viewed 2,958 times

3

Hello, I have a PHP page that receives ajax requests from another page, in another hosting, this was possible using header('Access-Control-Allow-Origin: *');
So far so good, but I’d like to know where the requisition comes from, that’s possible?

Example: I have the page on server1.com that received the request for a page on server2.com, would like to know that was server2.com who sent.

  • 1

    You can look at the REFERER, but it can be forged easily. The ideal would be to make a DNS request to the server, get its IP, and compare with the IP of the request (or directly register the IP of the server in your application)

2 answers

6


The most efficient method is to make a type of registration of your servers and then compare the IP, this you can do in several ways, some very ingenious, but the objective here is to give a base.

<?php

$ip = (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';

$servers = [
    'server_1' => '209.244.0.3',
    'server_2' => '208.67.220.220',
    'server_3' => '189.38.95.95'
];

$result = array_search($ip, $servers);
var_dump($result);

In the variable $ip, We use two ternary operators to capture the IP of who made the request. It’s basically an extra validation to avoid errors, and in case you’re using Cloudflare on the target server, it takes the real IP and not the Cloudflare IP.

Then we have an array $servers with the list of servers where the server name is in the key and the value of the key, the corresponding IP. This would be our "register" of servers. You can do this database if you want, for example.

The function array_search will search for the IP we took inside our array and, if found, will return the server name, if not found, will return false.

That’s it.

  • 2

    It’s worth saying that if it’s just so he knows whether or not he’s on the list, he can use the in_array (if knowing the server name makes no difference).

2

The trickiest part is getting the right IP address.

I suggest you check the following parameters to get the IP:

$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_PROXY']
$_SERVER['HTTP_CF_CONNECTING_IP']

Implementation:

$ip = array(
    'REMOTE_ADDR' = null,
    'REMOTE_PROXY' = null,
    'HTTP_CF_CONNECTING_IP' = null
)
if (isset($_SERVER['REMOTE_ADDR'])) {
    $ip['REMOTE_ADDR'] = trim($_SERVER['REMOTE_ADDR']);
}
if (isset($_SERVER['REMOTE_PROXY'])) {
    $ip['REMOTE_PROXY'] = trim($_SERVER['REMOTE_PROXY']);
}
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    $ip['HTTP_CF_CONNECTING_IP'] = trim($_SERVER['HTTP_CF_CONNECTING_IP']);
}


/*
Aqui você decide qual desses valores deseja consultar.
Comece pelo proxy, pois é o que retorna o "IP real", caso a conexão esteja sendo feita via proxy. Quando um cliente usa um proxy, `REMOTE_ADDR` assume o IP do proxy. Se o proxy for transparente, `REMOTE_PROXY` retornará o IP real do cliente. Isso é também muito útil para pegar "hackerzinho" que usa qualquer proxy pensando estar protegido.
*/
if (!empty($_SERVER['REMOTE_PROXY'])) {
    $rs = $_SERVER['REMOTE_PROXY'];
} else if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
    $rs = $_SERVER['HTTP_CF_CONNECTING_IP'];
} else {
    $rs = $_SERVER['REMOTE_ADDR'];
}

/*
As vezes o IP pode vir acompanhado de múltiplos IPs.
exemplo: 192.168.0.1, 127.0.0.1
Para detectar esses casos, é recomendado fazer uma verificação:
*/
if (strpos($rs, ', ')) {
    $ips = explode(', ', $rs);
    /*
    Você pode querer checar 1 por 1. Mas isso varia de acordo com a necessidade de cada caso.
    Aqui vamos pegar somente o primeiro do array para simplificar a didática
    */
    $rs = $ips[0];
}

/*
Faz um IP lookup reverse.
Obtém nome do domínio, caso exista.
*/
$dns = gethostbyaddr($rs);

/*
Imprime o IP e o dns
*/
echo $rs.'<br>'.$dns;

Compare the IP information, obtained from the example script above, with REMOTE_HOST_BY_ADDR and HTTP_REFERER:

$_SERVER['REMOTE_HOST_BY_ADDR']
$_SERVER['HTTP_REFERER']

If the IP returns empty or invalid, the decision on how to proceed will depend on your business model. Usually a restricted system where a minimum identification of who requests, blocks or denies access is required.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.