使用json编辑和重定向发布请求

时间:2017-08-23 18:16:15

标签: php json regex

对于我的项目,我试图在我的index.php上获取发布请求,使用一些随机值进行编辑,然后将其重定向到另一个页面。

我尝试了以下内容:

----------- POST REQUEST -----------

Array
(
    [authToken] => 0a65e943412453ecec35c814
    [sessionId] => 431503466924
    [answers] => [{"Boost":false,"answerTime":1300,"id":3},{"Boost":false,"answerTime":800,"id":1},{"Boost":false,"answerTime":900,"id":3},{"Boost":false,"answerTime":1000,"id":1},{"Boost":false,"answerTime":1200,"id":1}]
    [userId] => 2235
)

----------- POST REQUEST -----------

我的index.php

<?php
$time=[800,900,1000,1100,1200,1300,1500];
$array = json_decode($_POST['answers'], true);
foreach($array as &$k)
{
    $k['answerTime'] =$time[array_rand($time)];
}

$postpop = json_encode($array);

$url = 'http://127.0.0.1/index2.php';

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($postpop));
curl_setopt($ch,CURLOPT_POSTFIELDS,$postpop);

$result = curl_exec($ch);

curl_close($ch);

?>

通过这样做,我只得到我的回答[答案]。 我怎样才能重新编译完整的请求?

1 个答案:

答案 0 :(得分:0)

看起来你只是没有重新组装所有部件。存储POST,操作answer元素,然后替换该部分。

<?php

$time = [800,900,1000,1100,1200,1300,1500];

//Store the full post as received.
$originalPost = $_POST;

$array = json_decode($_POST['answers'], true);
foreach($array as &$k) {
    $k['answerTime'] = $time[array_rand($time)];
}

//replace just the part of the array we manipulated
$originalPost['answers'] = json_encode($array);

$url = 'http://127.0.0.1/index2.php';

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($originalPost));
curl_setopt($ch,CURLOPT_POSTFIELDS,$originalPost);

$result = curl_exec($ch);

curl_close($ch);