使用CURL

时间:2016-02-04 19:43:07

标签: php arrays post curl http-post

我试图在两个文件之间传输数据。

sender.php 代码(使用POST方法发送数组的文件)

$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three")
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_elements);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

echo "$response";

receiver.php 代码(从sender.php文件接收数组的文件,然后获取数组的每个元素并回显它,并将其放入文件saved.txt。

    echo $_POST($myvars); // To test the output of the received data.

      foreach($myvars as $item) {
       if (!empty($item)) {
        echo $item."<br>";
$myfile = file_put_contents('Saved.txt', (" Name: ". ($_POST["$item"])) . PHP_EOL , FILE_APPEND);
      }
    }

数组没有被转移到receiver.php或者我没有捕获它。在文档输出中,我只代替变量$ item而不是数组的每个元素。

编辑: 在接收文件中添加了以下代码,以便从内部获取数组元素,但我得到的只是阵列打印出来:

foreach( $_POST as $stuff ) {
    if( is_array( $stuff ) ) {
        foreach( $stuff as $thing ) {
            echo $thing;
        }
    } else {
        echo $stuff;
    }
}

通过在接收文件上添加以下内容:

echo "<pre>";
print_r($_POST);
echo "</pre>";

我得到以下内容:

Array
(
    [myvars] => Array
)

2 个答案:

答案 0 :(得分:0)

尝试序列化数组,因为它总能帮助我:

$url = 'http://localhost/receiver.php';
$myvars = array("one","two","three");
$myvars_post=join(" ",$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, "array=".urldecode($myvars_post));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

echo "$response";

并在receiver.php中使用:

print_r($_POST);

答案 1 :(得分:0)

好的,上面评论中讨论的底线导致了这个结果:

发送部分:

<?php
$url = 'http://localhost/out.php';
$myvars = array("one","two","three");
$post_elements = array('myvars'=>$myvars);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($post_elements));
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
print_r($response);

接收部分:

<?php
print_r($_POST);

发送方的输出是:

Array ( [myvars] => Array ( [0] => one [1] => two [2] => three ) )

基本上说你可以简单地在接收端使用$_POST['myvars'],它将完全保存你想要传输的标量数组。