PHP中根據(jù)IP地址判斷城市實現(xiàn)城市切換或跳轉(zhuǎn)代碼
Jun 13, 2016 am 11:58 AM
獲取IP地址
復(fù)制代碼 代碼如下:
function GetIP() {
??? if ($_SERVER["HTTP_X_FORWARDED_FOR"])
??????? $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
??? else if ($_SERVER["HTTP_CLIENT_IP"])
??????? $ip = $_SERVER["HTTP_CLIENT_IP"];
??? else if ($_SERVER["REMOTE_ADDR"])
??????? $ip = $_SERVER["REMOTE_ADDR"];
??? else if (getenv("HTTP_X_FORWARDED_FOR"))
??????? $ip = getenv("HTTP_X_FORWARDED_FOR");
??? else if (getenv("HTTP_CLIENT_IP"))
??????? $ip = getenv("HTTP_CLIENT_IP");
??? else if (getenv("REMOTE_ADDR"))
??????? $ip = getenv("REMOTE_ADDR");
??? else
??????? $ip = "Unknown";
??? return $ip;
}
echo GetIP();
?>
方法二
復(fù)制代碼 代碼如下:
function getip ()
{
??????????????? if (getenv('http_client_ip')) {
??????????????????????? $ip = getenv('http_client_ip');
??????????????? } else if (getenv('http_x_forwarded_for')) {
??????????????????????? $ip = getenv('http_x_forwarded_for');
??????????????? } else if (getenv('remote_addr')) {
??????????????????????? $ip = getenv('remote_addr');
??????????????? } else {
??????????????????????? $ip = $_server['remote_addr'];
??????????????? }
??????????????? return $ip;
PHP通過IP地址判斷用戶所在城市
上文已經(jīng)獲得了用戶IP地址,接下來,我們就是根據(jù)這個IP地址獲得用戶所在城市了。開始之前,我們需要下載一個現(xiàn)成的數(shù)據(jù)庫QQ IP數(shù)據(jù)庫。
最新IP地址數(shù)據(jù)庫:http://www.jb51.net/softs/10529.html
使用方法:解壓后QQWry.Dat就是我們想要IP地址數(shù)據(jù)庫,我們新建一個ipcity文件夾,將數(shù)據(jù)庫放在下面。QQ IP數(shù)據(jù)庫使用非常方便,數(shù)據(jù)也很齊全,你可以及時關(guān)注官方更新以保持?jǐn)?shù)據(jù)最新,強力推薦一下:)
接下來,我們在上面的ipcity目錄下新建一個ipaddress.php文件,直接復(fù)制以下代碼進去即可,重要的地方也作了相應(yīng)注釋。B段:
復(fù)制代碼 代碼如下:
/*
函數(shù)名稱:ipCity
參數(shù)說明:$userip——用戶IP地址
函數(shù)功能:PHP通過IP地址判斷用戶所在城市
author:lee
contact:xpsem2010@gmail.com
*/
function ipCity($userip) {
??? //IP數(shù)據(jù)庫路徑,這里用的是QQ IP數(shù)據(jù)庫 20110405 純真版
??? $dat_path = 'QQWry.dat';
??? //判斷IP地址是否有效
??? if(!ereg("^([0-9]{1,3}.){3}[0-9]{1,3}$", $userip)){
??????? return 'IP Address Invalid';
??? }
??? //打開IP數(shù)據(jù)庫
??? if(!$fd = @fopen($dat_path, 'rb')){
??????? return 'IP data file not exists or access denied';
??? }
??? //explode函數(shù)分解IP地址,運算得出整數(shù)形結(jié)果
??? $userip = explode('.', $userip);
??? $useripNum = $userip[0] * 16777216 + $userip[1] * 65536 + $userip[2] * 256 + $userip[3];
??? //獲取IP地址索引開始和結(jié)束位置
??? $DataBegin = fread($fd, 4);
??? $DataEnd = fread($fd, 4);
??? $useripbegin = implode('', unpack('L', $DataBegin));
??? if($useripbegin ??? $useripend = implode('', unpack('L', $DataEnd));
??? if($useripend ??? $useripAllNum = ($useripend - $useripbegin) / 7 + 1;
??? $BeginNum = 0;
??? $EndNum = $useripAllNum;
??? //使用二分查找法從索引記錄中搜索匹配的IP地址記錄
??? while($userip1num>$useripNum || $userip2num??????? $Middle= intval(($EndNum + $BeginNum) / 2);
??????? //偏移指針到索引位置讀取4個字節(jié)
??????? fseek($fd, $useripbegin + 7 * $Middle);
??????? $useripData1 = fread($fd, 4);
??????? if(strlen($useripData1) ??????????? fclose($fd);
??????????? return 'File Error';
??????? }
??????? //提取出來的數(shù)據(jù)轉(zhuǎn)換成長整形,如果數(shù)據(jù)是負(fù)數(shù)則加上2的32次冪
??????? $userip1num = implode('', unpack('L', $useripData1));
??????? if($userip1num ??????? //提取的長整型數(shù)大于我們IP地址則修改結(jié)束位置進行下一次循環(huán)
??????? if($userip1num > $useripNum) {
??????????? $EndNum = $Middle;
??????????? continue;
??????? }
??????? //取完上一個索引后取下一個索引
??????? $DataSeek = fread($fd, 3);
??????? if(strlen($DataSeek) ??????????? fclose($fd);
??????????? return 'File Error';
??????? }
??????? $DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
??????? fseek($fd, $DataSeek);
??????? $useripData2 = fread($fd, 4);
??????? if(strlen($useripData2) ??????????? fclose($fd);
??????????? return 'File Error';
??????? }
??????? $userip2num = implode('', unpack('L', $useripData2));
??????? if($userip2num ??????? //找不到IP地址對應(yīng)城市
??????? if($userip2num ??????????? if($Middle == $BeginNum) {
??????????????? fclose($fd);
??????????????? return 'No Data';
??????????? }
??????????? $BeginNum = $Middle;
??????? }
??? }
??? $useripFlag = fread($fd, 1);
??? if($useripFlag == chr(1)) {
??????? $useripSeek = fread($fd, 3);
??????? if(strlen($useripSeek) ??????????? fclose($fd);
??????????? return 'System Error';
??????? }
??????? $useripSeek = implode('', unpack('L', $useripSeek.chr(0)));
??????? fseek($fd, $useripSeek);
??????? $useripFlag = fread($fd, 1);
??? }
??? if($useripFlag == chr(2)) {
??????? $AddrSeek = fread($fd, 3);
??????? if(strlen($AddrSeek) ??????????? fclose($fd);
??????????? return 'System Error';
??????? }
??????? $useripFlag = fread($fd, 1);
??????? if($useripFlag == chr(2)) {
??????????? $AddrSeek2 = fread($fd, 3);
??????????? if(strlen($AddrSeek2) ??????????????? fclose($fd);
??????????????? return 'System Error';
??????????? }
??????????? $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
??????????? fseek($fd, $AddrSeek2);
??????? } else {
??????????? fseek($fd, -1, SEEK_CUR);
??????? }
??????? while(($char = fread($fd, 1)) != chr(0))
??????????? $useripAddr2 .= $char;
??????? $AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
??????? fseek($fd, $AddrSeek);
??????? while(($char = fread($fd, 1)) != chr(0))
??????????? $useripAddr1 .= $char;
??? } else {
??????? fseek($fd, -1, SEEK_CUR);
??????? while(($char = fread($fd, 1)) != chr(0))
??????????? $useripAddr1 .= $char;
??????? $useripFlag = fread($fd, 1);
??????? if($useripFlag == chr(2)) {
??????????? $AddrSeek2 = fread($fd, 3);
??????????? if(strlen($AddrSeek2) ??????????????? fclose($fd);
??????????????? return 'System Error';
??????????? }
??????????? $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
??????????? fseek($fd, $AddrSeek2);
??????? } else {
??????????? fseek($fd, -1, SEEK_CUR);
??????? }
??????? while(($char = fread($fd, 1)) != chr(0)){
??????????? $useripAddr2 .= $char;
??????? }
??? }
??? fclose($fd);
??? //返回IP地址對應(yīng)的城市結(jié)果
??? if(preg_match('/http/i', $useripAddr2)) {
??????? $useripAddr2 = '';
??? }
??? $useripaddr = "$useripAddr1 $useripAddr2";
??? $useripaddr = preg_replace('/CZ88.Net/is', '', $useripaddr);
??? $useripaddr = preg_replace('/^s*/is', '', $useripaddr);
??? $useripaddr = preg_replace('/s*$/is', '', $useripaddr);
??? if(preg_match('/http/i', $useripaddr) || $useripaddr == '') {
??????? $useripaddr = 'No Data';
??? }
??? return $useripaddr;
}
?>
PHP根據(jù)IP地址實現(xiàn)城市切換或跳轉(zhuǎn)
到這里,其實問題已經(jīng)很簡單了,用簡單的js就通通搞定。C段如下:
//根據(jù)IP地址跳轉(zhuǎn)指定頁面js取得城市
復(fù)制代碼 代碼如下:
var city='';
//根據(jù)IP地址所有城市跳轉(zhuǎn)到指定頁面
復(fù)制代碼 代碼如下:
if(city.indexOf("上海市")>=0){
??????? window.location.;
}
將開頭的A段代碼和上面的C段代碼分別放在B段代碼的頭和尾,然后我們在需要跳轉(zhuǎn)的頁面加入以下代碼:
復(fù)制代碼 代碼如下:
?
刷新頁面,是不是達到預(yù)想的效果了呢?
上面的代碼只是簡單的判斷了ip那里就跳到那,如果出現(xiàn)如,我想把湖南所有IP都跳到長沙去,那像衡陽,劉陽,耒陽 這些就要作多次父線處理了,要想知道請看下集。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
