用curl发布数据——实际上是刷新到下一页


Posting data with curl - actually refreshing to the next page

我正在尝试使用post在页面之间发送post数据。不是一个表单——我可能会在页面之间传递验证错误或其他什么(在几个地方使用它)。

cURL执行得很好,但它只是在底部的新页面上进行附加。如何执行cURL Post并加载以下页面?

所以我的目标是在页面之间发送数据。我不想使用GET或cookie,因为我不想依赖用户,我也不想使用$_SESSION,因为它与其说是直接关于会话,不如说是在页面之间发送私人数据。

感谢

$ch = curl_init($some_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'myvar=something');
curl_exec($ch);
curl_close($ch);

我怀疑代码是否有任何相关性,因为它是关于执行任务,而不是代码语法(在这个例子中可能有一个,但你必须相信我,它不是有问题的代码,因为它检索得很好)。

您可以将$_SESSION超全局划分为数组,这些数组描述当前用户/会话以及表单创建的任何错误。例如,

$_SESSION = array(
  'user' => array(), // user data goes here
  'errors' => array() // validation data goes here
);
if (!$_POST['myvar'] == 'something') {
  $_SESSION['errors']['myvar'] = 'You must specify a value for <code>myvar</code>';
}

然后,您可以使用以下调用在后续页面上输出错误:

if (isset($_SESSION['errors'])) {
  foreach($_SESSION['errors'] as $error) {
    echo '<li>' . $error . '</li>';
  }
}

为什么要使用cURL?为什么不直接使用AJAX:

$(function() {
   // Send data asynchronously
   $.ajax({
      url: '/path/to/your/script.php',
      type: 'POST',
      data: 'var1=value1&var2'=$('input.some_class').val(),
      success: function(data) {
         // Send the user to another page
         window.location.href = '/to/infinity/and/beyond';
      }
   });
});

使用ajax执行

$(function() {
   /
      data: 'var1=value1&/ Send data asynchronously
   $.ajax({
      url: '/path/to/your/script.php',
      type: 'POST',var2'=$('input.some_class').val(),
      success: function(data) {
         // Send the user to another page
         window.location.href = '/to/infinity/and/beyond';
      }
   });
});