Home >Backend Development >PHP Tutorial >Determine whether the page was opened by WeChat_PHP tutorial
I encountered a problem today. A page can be opened on WeChat but cannot be opened directly on a PC. I have searched online for a long time, but I have not found a satisfactory answer, and it is all the same.
<span $user_agent</span> = <span $_SERVER</span>['HTTP_USER_AGENT'<span ]; </span><span if</span> (<span strpos</span>(<span $user_agent</span>, 'MicroMessenger') === <span false</span><span ) { </span><span //</span><span 非微信浏览器禁止浏览</span> <span echo</span> "HTTP/1.1 401 Unauthorized"<span ; } </span><span else</span><span { </span><span //</span><span 微信浏览器,允许访问</span> <span echo</span> "MicroMessenger"<span ; </span><span //</span><span 获取版本号</span> <span preg_match</span>('/.*?(MicroMessenger\/([0-9.]+))\s*/', <span $user_agent</span>, <span $matches</span><span ); </span><span echo</span> '<br>Version:'.<span $matches</span>[2<span ]; }</span>
Well, I can’t refute it directly, but this is indeed very unreliable.
Let’s talk about it with data.
The following are the HTTP_USER_AGENT information for Android, WinPhone, and iPhone.
<span 1</span> "HTTP_USER_AGENT": "Mozilla/5.0 (Linux; U; Android 4.1; zh-cn; Galaxy Nexus Build/Wind-Galaxy Nexus-V1.2) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 MicroMessenger/5.0.1.352"<span , </span><span 2</span> "HTTP_USER_AGENT": "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Nokia 920T)"<span , </span><span 3</span> "HTTP_USER_AGENT": "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Mobile/10B329 MicroMessenger/5.0.1",
You can see that WinPhone does not have MicroMessenger at all, so it is impossible to judge.
In fact, the userAgent judgment is very false.
So I think we should use js to judge whether WeixinJSBridge exists, and then use ajax to php
php It is detected and then returns the real page information, adding a "Loading..." during the process, which is very harmonious.
Of course, ajax can also be deceived, but compared to userAgent deception, it is a little more troublesome. ,
However, our purpose is to detect whether it is WeChat, not the problem of deception.
I will not write the specific code, because I hate the kind of borrowing.
Infinite copy and paste. Posted, and sometimes the code is filtered even if part of it is filtered,