@@ -386,16 +386,72 @@ function base64DataToImage($imgBase64)
386386 return base64_decode ($ img );
387387}
388388
389+ function getRemoteAddrFromServerArray ($ server )
390+ {
391+ if (empty ($ server ['REMOTE_ADDR ' ])) {
392+ return '' ;
393+ }
394+
395+ $ remoteAddr = trim ($ server ['REMOTE_ADDR ' ]);
396+ if (!filter_var ($ remoteAddr , FILTER_VALIDATE_IP )) {
397+ return '' ;
398+ }
399+
400+ return $ remoteAddr ;
401+ }
402+
403+ function isPrivateOrLoopbackIP ($ ip )
404+ {
405+ if (!filter_var ($ ip , FILTER_VALIDATE_IP )) {
406+ return false ;
407+ }
408+
409+ return !filter_var ($ ip , FILTER_VALIDATE_IP , FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE );
410+ }
411+
412+ function getForwardedClientIpFromServerArray ($ server )
413+ {
414+ $ ipv6 = '' ;
415+ $ headers = [
416+ 'HTTP_X_REAL_IP ' ,
417+ 'HTTP_X_FORWARDED_FOR ' ,
418+ ];
419+
420+ foreach ($ headers as $ header ) {
421+ if (empty ($ server [$ header ])) {
422+ continue ;
423+ }
424+
425+ $ ips = explode (', ' , $ server [$ header ]);
426+ foreach ($ ips as $ ipCandidate ) {
427+ $ ipCandidate = trim ($ ipCandidate );
428+ if (filter_var ($ ipCandidate , FILTER_VALIDATE_IP , FILTER_FLAG_IPV4 )) {
429+ return $ ipCandidate ;
430+ }
431+ if (empty ($ ipv6 ) && filter_var ($ ipCandidate , FILTER_VALIDATE_IP , FILTER_FLAG_IPV6 )) {
432+ $ ipv6 = $ ipCandidate ;
433+ }
434+ }
435+ }
436+
437+ return $ ipv6 ;
438+ }
439+
389440function getRealIpAddr ()
390441{
391- if (!empty ($ _SERVER ['HTTP_CLIENT_IP ' ])) { //check ip from share internet
392- $ ip = $ _SERVER ['HTTP_CLIENT_IP ' ];
393- } elseif (!empty ($ _SERVER ['HTTP_X_FORWARDED_FOR ' ])) { //to check ip is pass from proxy
394- $ ip = $ _SERVER ['HTTP_X_FORWARDED_FOR ' ];
395- } else {
396- $ ip = $ _SERVER ['REMOTE_ADDR ' ];
442+ $ remoteAddr = getRemoteAddrFromServerArray ($ _SERVER );
443+ if (empty ($ remoteAddr )) {
444+ return '127.0.0.1 ' ;
397445 }
398- return $ ip ;
446+
447+ if (isPrivateOrLoopbackIP ($ remoteAddr )) {
448+ $ forwardedIp = getForwardedClientIpFromServerArray ($ _SERVER );
449+ if (!empty ($ forwardedIp )) {
450+ return $ forwardedIp ;
451+ }
452+ }
453+
454+ return $ remoteAddr ;
399455}
400456
401457function cleanString ($ text )
0 commit comments