在PHP中创建一个代理以欺骗iPhone用户代理?

4
我正在编写基于Web的iPhone模拟器,希望能够伪装iPhone的Safari浏览器,使得在模拟器(iframe)中加载的网页使用移动版。据我所知,我需要修改用户代理来实现这一目标。
那么,我应该如何创建一个PHP代理脚本来伪装iPhone的用户代理呢?
3个回答

3
你可以使用PHP类,例如Ben Alman的简单PHP代理 / Github。它可以以多种方式重定向跨域URL,包括以下方法来“更改”您的用户代理....
user_agent - This value will be sent to the remote URL request as the
     `User-Agent:` HTTP request header. If omitted, the browser user agent
     will be passed through.

我用它来插入一个iFrame - 带有Google Voice iPhone版本 - 到任何页面中,例如...

使用此脚本可以改变请求的许多其他方式,例如...

   url - The remote URL resource to fetch. Any GET parameters to be passed
     through to the remote URL resource must be urlencoded in this parameter.
   mode - If mode=native, the response will be sent using the same content
     type and headers that the remote URL resource returned. If omitted, the
     response will be JSON (or JSONP). <Native requests> and <JSONP requests>
     are disabled by default, see <Configuration Options> for more information.
   callback - If specified, the response JSON will be wrapped in this named
     function call. This parameter and <JSONP requests> are disabled by
     default, see <Configuration Options> for more information.
   send_cookies - If send_cookies=1, all cookies will be forwarded through to
     the remote URL request.
   send_session - If send_session=1 and send_cookies=1, the SID cookie will be
     forwarded through to the remote URL request.
   full_headers - If a JSON request and full_headers=1, the JSON response will
     contain detailed header information.
   full_status - If a JSON request and full_status=1, the JSON response will
     contain detailed cURL status information, otherwise it will just contain
     the `http_code` property.

1

您可以使用像cURL这样的库来使用iPhone用户代理请求页面,并将该页面返回到您的站点(请务必使用DOMDocument将相对URL扩展为绝对URL)。

但是,您可能会遇到一些边缘情况,例如通过用户代理以不同方式提供CSS / JavaScript / 图像。这可能不值得冒险请求每个资产。您可以通过使用您的用户代理和iPhone用户代理进行一次请求,然后执行md5_file()并查看它们是否不同来限制工作量。不过我认为这没必要:P

您也可以尝试使用此JavaScript...

navigator.__defineGetter__('userAgent', function(){
    return 'foo' // customized user agent
});

navigator.userAgent; // 'foo'

源代码

同时请记得,如果您的用户没有使用 Safari 浏览器,则可能需要发出警告,因为它是最接近模拟移动版 Safari 的浏览器。


有没有一种简单的方法将相对URL扩展为绝对URL,还是需要遍历DOM树并逐个修改URL? - Camsoft
@Camsoft 你可以使用 str_replace() 来猜测,但我宁愿安全起见遍历元素并替换 hrefsrc 等属性。 - alex

0
如果您想为最终用户欺骗标头,那么使用用户代理更改浏览器插件不是一个选项。我的建议是编写一个简单的PHP脚本,将URL传递给它,并向该URL发出PHP cURL请求,但在此之前,您应该使用以下调用设置User Agent标头:
curl_setopt($ch,CURLOPT_HTTPHEADER,array('User-Agent: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.3'));
我认为这应该可以工作,但它会很快使您的服务器崩溃...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接