You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS检测屏幕宽度传值PHP切换User-Agent失败求助

问题分析

你的代码核心问题在于PHP的执行时机和AJAX请求的异步性不匹配:

  • 当浏览器请求test.php时,PHP会先于JavaScript执行,此时还没有任何POST请求数据,$_POST['device']为空,所以直接进入else分支返回默认User-Agent。
  • JavaScript是在页面加载完成后才发送AJAX请求,这时候返回的响应只会在控制台打印,无法修改已经执行完毕的PHP上下文,也没法让后续的cURL操作直接使用这个User-Agent。
解决方案

根据你需要用User-Agent做cURL的需求,推荐两种可行方案:

方案1:用Cookie传递设备类型(适合页面加载时就确定并复用)

通过JavaScript将设备类型写入Cookie,然后刷新页面或者让后续PHP请求读取Cookie值:

修改后的test.php代码:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// 检查Cookie里是否已经有设备类型
if (!document.cookie.includes('device=')) {
    var width = window.innerWidth;
    var device = "";

    if (width <= 480) {
        device = "mobile";
    } else if (width <= 650) {
        device = "tablet";
    } else {
        device = "desktop";
    }
    // 写入Cookie,有效期1天
    document.cookie = `device=${device}; path=/; max-age=86400`;
    // 刷新页面让PHP读取Cookie
    window.location.reload();
}
</script>

<?php
// 从Cookie读取设备类型,默认desktop
$device = $_COOKIE['device'] ?? 'desktop';

if ($device == "desktop") {
    $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0';
} else if ($device == "mobile") {
    $agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1';
} else if ($device == "tablet") {
    $agent = 'Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1';
} else {
    $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';
}

// 这里可以直接用$agent做cURL操作
echo "Device Type: " . $device;
echo "<br>User Agent: " . $agent;
?>

方案2:拆分AJAX请求和业务逻辑(适合异步获取后使用)

把处理User-Agent和cURL的逻辑单独放在一个PHP文件里,通过AJAX传递设备类型后,让PHP返回处理结果:

  1. 创建get_agent.php文件:
<?php
$device = $_POST['device'] ?? 'desktop';

if ($device == "desktop") {
    $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0';
} else if ($device == "mobile") {
    $agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1';
} else if ($device == "tablet") {
    $agent = 'Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1';
} else {
    $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36';
}

// 在这里执行cURL操作,比如:
// $ch = curl_init('目标URL');
// curl_setopt($ch, CURLOPT_USERAGENT, $agent);
// $result = curl_exec($ch);
// curl_close($ch);

// 返回结果给前端
echo json_encode([
    'device' => $device,
    'user_agent' => $agent,
    // 'curl_result' => $result // 如果需要返回cURL结果
]);
?>
  1. 修改原test.php:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var width = window.innerWidth;
var device = "";

if (width <= 480) {
    device = "mobile";
} else if (width <= 650) {
    device = "tablet";
} else {
    device = "desktop";
}

$.ajax({
    url: 'get_agent.php',
    type: 'POST',
    data: {device: device},
    dataType: 'json',
    success: function(response) {
        console.log("Device Type: " + response.device);
        console.log("User Agent: " + response.user_agent);
        // 如果有cURL结果,也可以在这里处理
    }
});
</script>
关键注意点
  • 永远不要直接信任客户端传递的数据,建议在PHP里对$device做额外的合法性校验,比如用in_array($device, ['desktop', 'mobile', 'tablet'])来判断,避免非法值。
  • 方案1中Cookie会在客户端保存,后续请求都能直接读取,适合需要在整个会话中复用设备类型的场景;方案2是单次异步请求,适合临时获取User-Agent做单次cURL操作的场景。

内容的提问来源于stack exchange,提问作者Mehul Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:55:38