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

如何通过PHP+Curl跨站点传递数据?现有代码无法运行求解答

修复你的POST请求代码问题

看起来你的代码有几个关键问题导致无法正常传递变量,我帮你梳理并修正:

核心问题分析

  1. POST数据格式错误:你用了索引数组array($usr,$pass),但POST请求需要关联数组(键值对),这样接收端才能通过对应的键名获取值。
  2. CURL选项不完整:你的代码片段里curl_setopt ($ch, CURLOPT...没写完,缺少了发送POST数据的关键选项,也没设置返回请求结果的参数。
  3. 未调用发送函数:你定义了post_data函数,但没有实际调用它执行请求。

修正后的完整代码

<?php
// 假设$usr和$pass已经被正确赋值
$usr = "your_username";
$pass = "your_password";

$url = 'http://examplereceiver.com/sec/check.php';
// 改用关联数组,键名要和接收端$_POST的键对应
$post_dat = array(
    'usr' => $usr,
    'pass' => $pass
);

function post_data($url, $post_dat) {
    $ch = curl_init();
    
    // 设置请求URL
    curl_setopt($ch, CURLOPT_URL, $url);
    // 启用POST请求
    curl_setopt($ch, CURLOPT_POST, true);
    // 设置POST数据(http_build_query会把数组转为URL编码的字符串)
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_dat));
    // 设置返回结果而不是直接输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 禁用SSL验证(如果是HTTPS且证书有问题,生产环境不建议)
    // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    // 执行请求并获取返回值
    $response = curl_exec($ch);
    
    // 检查CURL错误
    if(curl_errno($ch)){
        echo 'CURL错误:' . curl_error($ch);
        $response = false;
    }
    
    // 关闭CURL资源
    curl_close($ch);
    
    return $response;
}

// 调用函数执行POST请求
$result = post_data($url, $post_dat);

// 可选:打印返回结果调试
// var_dump($result);
?>

接收端(examplereceiver.com/sec/check.php)的对应处理

确保接收端能正确获取POST参数:

<?php
// 检查是否接收到参数
if(isset($_POST['usr']) && isset($_POST['pass'])){
    $username = $_POST['usr'];
    $password = $_POST['pass'];
    // 这里写你的处理逻辑,比如验证、存储等
    echo "接收成功:用户名=" . $username . ",密码=" . $password;
} else {
    echo "未接收到有效参数";
}
?>

额外提示

  • 如果目标站点是HTTPS,建议保留SSL验证(不要注释那两行),并确保服务器配置了正确的SSL证书。
  • 调试时可以用var_dump($result)查看返回结果,或者检查CURL错误信息定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:21:14