简体   繁体   中英

PHP get data from pubsub

I have a pub/sub project, and i want to use it in my PHP project, my topic is setup: 在此处输入图片说明

I have a php script to serve this, msg.php:

$file = "text.txt";

$fp = fopen($file, "w");
fwrite($fp, json_encode($_REQUEST));// tried $_POST, $_GET
fclose($fp);

But i can't get data from it, however script seems to be executed (i see it by changed date of txt file). I always end up with a [] in a text.txt, doesnt metter if notifications sended automaticaly or manualy by me through publish message option. How can i get data from incoming pub/sub messages?

Solutions descriped in this questions doesnt work for me Google Cloud Platform Pub/Sub push empty POST data Google Cloud Pub/Sub Push Messages - Empty POST

By this i mean replacing

fwrite($fp, json_encode($_REQUEST));

with

fwrite(json_decode(file_get_contents('php://input')_);
fwrite(json_decode($HTTP_RAW_POST_DATA));

I bumped into the same problem, and following solution helped me. Hope this helps someone.

ob_start();

$rawData = file_get_contents("php://input");
echo $rawData."\n";

$JSONObj = json_decode($rawData);

/*All sensitive data comes encoded in base64 and you need to decode that string, which gives another JSON String
*/
echo base64_decode($JSONObj->message->data);

$info = ob_get_contents();
ob_end_clean();

$fp = fopen("test.txt", "w+");
fwrite($fp, $info);
fclose($fp);

PHP's json_encode function will output that open-and-close bracket "[]" when given an empty array. There are 2 main possibilities that could be occurring.

  1. It is possible that an empty array is being sent to your endpoint from pubsub.
  2. Depending on your PHP version and configuration, the request contents may not come through $_REQUEST, $_POST or $HTTP_RAW_POST_DATA variables.

I recommend using a function like the following to dump all the variables and environment settings to see if the expected data is coming into PHP at all:

function PHPInfo2File($target_file) {
      ob_start();
      phpinfo();
      $info = ob_get_contents();
      ob_end_clean();

      $fp = fopen($target_file, "w+");
      fwrite($fp, $info);
      fclose($fp);
   }

If PHP is not receiving the data, the problem should be at the pubsub level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM