Home > Backend Development > PHP Tutorial > PHP code to restrict access to a single IP and IP range

PHP code to restrict access to a single IP and IP range

WBOY
Release: 2016-07-25 09:13:28
Original
1124 people have browsed it
Share two pieces of code in PHP to implement IP access restrictions, which are divided into two examples of codes to restrict access to a single IP and restrict access to IP segments. Friends in need can refer to it.
  1. //Add IP access restrictions
  2. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  3. $userip = getenv(' HTTP_CLIENT_IP');
  4. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  5. $userip = getenv('HTTP_X_FORWARDED_FOR');
  6. } else if(getenv( 'REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  7. $userip = getenv('REMOTE_ADDR');
  8. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER ['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  9. $userip = $_SERVER['REMOTE_ADDR'];
  10. }
  11. $banned_ip = array (
  12. "127.0. 0.1",
  13. "203.0.0.1",
  14. "56.12.50.65",
  15. "192.168.1.88"
  16. );
  17. if (in_array($userip,$banned_ip))
  18. {
  19. die ( "Your IP is block to connect !");
  20. }
  21. echo "Test code! Test";
  22. ?>
Copy code
Example 2, IP segment Restrict , restrict IP segment access.
  1. //Add IP access restrictions
  2. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  3. $userip = getenv(' HTTP_CLIENT_IP');
  4. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  5. $userip = getenv('HTTP_X_FORWARDED_FOR');
  6. } else if(getenv( 'REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  7. $userip = getenv('REMOTE_ADDR');
  8. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER ['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  9. $userip = $_SERVER['REMOTE_ADDR'];
  10. }
  11. $ban_range_low=ip2long("217.0.0.0" ; ;$ban_range_up)
  12. {
  13. print "Banned";
  14. exit();
  15. }
  16. ?>

  17. Copy code



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template