Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

php - Edit and redirect a post request with json

For my project, i'm trying to get the post request on my index.php, edit it with some random values, and then redirect it to another page.

I tried the following:

----------- 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 -----------

My 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);

?>

By doing that, i only get the [answers] on my response. How can i get to recompile the full request?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like you are simply failing to reassemble all the parts. Store the POST, manipulate the answer element, and then replace that part.

<?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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...