无法将var成功发布到另一个php文件

时间:2018-06-29 05:06:51

标签: php html html-form php-curl html-post

我有一个PHP文件A.php,其中包含一个名为formA的表单。

formA得到结果,然后通过php & SQL & traditional HTML form posting方法发布并存储到MYSQL中。

formA的一个字段中,我想将此值$amount发布到另一个php文件B.php。这是因为B.php中有一个隐藏的形式我尝试使用php-curl方法发布此消息,以采取进一步措施。

B.php中,我尝试测试是否可以成功获得$amount

  

两个print_r($_POST); print_r($_GET);都显示Array ( ) Array ( ),这意味着无法获得amount

这是我的代码:

A.php:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  // Validate amount
    $input_amount = trim($_POST["amount"]);
    if (empty($input_amount)) {
        $amount_err = "Please enter the amount.";
    } elseif (!ctype_digit($input_amount)) {
        $amount_err = 'Please enter a positive integer value.';
    } else {
        $amount = $input_amount;
    }
//storing to db
 if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
        // Prepare an insert statement
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";

        $q = $pdo->prepare($sql);
        $q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
        Database::disconnect();



        //curl part start:  post the `amount`
        $ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"B.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "amount=amount,input_amount=input_amount");




// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);



    header("Location: B.php");
}

}
?>

//Form A -the field that get the `amount` value 

    <div class="form-group <?php echo (!empty($amount_err)) ? 'has-error' : ''; ?>">                             
                                 <label>* Donation amount</label>                    
               <input list="amount" name="amount"  multiple class="form-control"> 
   <datalist id="amount" >
    <option value="100">
    <option value="300">
    <option value="500">
    <option value="1000">
  </datalist>  
                     <span class="help-block"><?php echo $amount_err; ?></span>
                        </div>
....other fields. .... 

B.php:

<?php
print_r($_POST);
print_r($_GET);
    $amount = null;
    if ( !empty($_GET['amount'])) {
        $amount = $_REQUEST['amount'];
    }
     ...later  action....

?>

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您的CURLOPT_POSTFIELDS值格式错误,并且不包含您期望的值。值的编码必须使用application/x-www-form-urlencoded。本质上,变量之间用&隔开。

大卫·沃尔什(David Walsh)有一个了不起的例子here

您的字符串应如下所示。 "amount=".$amount."&input_amount=".$input_amount