如何通过POST调用php站点传输值?

时间:2012-11-22 17:36:38

标签: php post

假设我有 index.php

<?php
    $currentUser = "Paedow";
?>

我有一个 user.php

<?php
    printf($_POST["currentUser"]);
?>

如何在调用时将变量$currentUser提交给 user.php

我尝试了这段代码,但这只是在不调用/查看页面的情况下提交数据:

function PostToHost($host, $path, $referer, $data_to_send) {
  $fp = fsockopen($host, 80);
  fputs($fp, "POST $path HTTP/1.1\r\n");
  fputs($fp, "Host: $host\r\n");
  fputs($fp, "Referer: $referer\r\n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
  fputs($fp, "Content-length: ". strlen($data_to_send) ."\r\n");
  fputs($fp, "Connection: close\r\n\r\n");
  fputs($fp, $data_to_send);
  while(!feof($fp)) {
      $res .= fgets($fp, 128);
  }
  fclose($fp);

  return $res;
}

3 个答案:

答案 0 :(得分:3)

选项1

使用将发布数据的客户端javascript,返回输出,以便您可以根据需要使用它。见jQuery.post

选项2

使用服务器端(就像你已经使用的那样)但是使用cURL来发布你的值。见cURL

答案 1 :(得分:0)

$data_to_send的内容需要如下所示:

currentUser=Paedow

这就是形式 - urlencoded数据的样子。

但是,我可以建议一个不同的方法:您可能更容易使用cURL来执行HTTP POST,如下所示:

$curl = curl_init(); 
curl_setopt($curl, CURLOPT_POST, true); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata); 
curl_setopt($curl, CURLOPT_URL, $endpoint); 
$response = curl_exec($curl);
curl_close($curl);
print_r($response);

(请记住,我还没有对它进行过测试,只是在脑海中输入它。)

答案 2 :(得分:0)

似乎我不喜欢它;所以我使用Cookies 另一种选择是使用Session