The example in this article describes how to accurately obtain the server IP address in PHP. Share it with everyone for your reference. The specific analysis is as follows:
In php, we usually use $_SERVER['HTTP_HOST'] to obtain the domain name or IP address of the website in the URL.
The explanation in the php manual is as follows:
"HTTP_HOST"
Contents of the Host: header of the current request.
Generally speaking, you will not encounter any problems this way. Some common PHP frameworks, such as PFC3 and FLEA, are also based on this predefined variable.
However, in a project I was working on recently, when the program was handed over to the customer for testing, I found that the jump of the program always went wrong.
Finally find out the reason: In the customer's environment, the value obtained by $_SERVER['HTTP_HOST'] is always the IP value of the server where the program is located in its LAN.
The reason is that the customer's company is connected to the Internet through a server, and the server where our program is located is mapped through the domain name, that is, there is a "proxy" process in the middle.
Therefore, in such an environment, the value obtained by $_SERVER['HTTP_HOST'] is always the IP value of the server where the program is located in its LAN.
Finally, I checked a lot of information and found an alternative implementation method in the symfony framework:
Copy the code as follows: $host = $_SERVER['HTTP_HOST'];
Replace with:
Copy code The code is as follows: $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
I hope this article will be helpful to everyone’s PHP programming design.