Subversion Repositories php_utils

Rev

Rev 2 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 daniel-mar 1
<?php
2
 
3
/*
4
 * IP functions
5
 * Copyright 2015 Daniel Marschall, ViaThinkSoft
6
 * Version 2015-10-27
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
 
21
function get_real_ip() {
22
        /* Eindeutige IP Adresse erhalten, auch bei Proxies und (neu:) von SSH connections im CLI modus */
23
        // http://lists.phpbar.de/pipermail/php/Week-of-Mon-20040322/007749.html
24
        // Modificated by VTS
25
        // Version: 2015-10-27
26
 
27
        // TODO: ipv6
28
 
29
        if (isset($_SERVER['SSH_CLIENT']))     { $ary = explode(' ', $_SERVER['SSH_CLIENT']);     return $ary[0]; }
30
        if (isset($_SERVER['SSH_CONNECTION'])) { $ary = explode(' ', $_SERVER['SSH_CONNECTION']); return $ary[0]; }
31
 
32
        $client_ip       = (isset($_SERVER['HTTP_CLIENT_IP']))       ? $_SERVER['HTTP_CLIENT_IP']       : '';
33
 
34
        // It is not secure to use these, since they are not validated: http://www.thespanner.co.uk/2007/12/02/faking-the-unexpected/
35
        // $x_forwarded_for = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
36
        $x_forwarded_for = '';
37
 
38
        $remote_addr     = (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : '';
39
 
40
        if (!empty($client_ip)) {
41
                $ip_expl = explode('.', $client_ip);
42
                $referer = explode('.', $remote_addr);
43
                if ($referer[0] != $ip_expl[0]) {
44
                        $ip = array_reverse($ip_expl);
45
                        $return = implode('.', $ip);
46
                } else {
47
                        $return = $client_ip;
48
                }
49
        } else if (!empty($x_forwarded_for)) {
50
                if (strstr($x_forwarded_for, ',')) {
51
                        $ip_expl = explode(',', $x_forwarded_for);
52
                        $return = end($ip_expl);
53
                } else {
54
                        $return = $x_forwarded_for;
55
                }
56
        } else {
57
                $return = $remote_addr;
58
        }
59
        unset ($client_ip, $x_forwarded_for, $remote_addr, $ip_expl);
60
        return $return;
61
}