0

I am trying to get used to using cURL, and have hit a wall. Currently I have two php scripts, a "sender" hosted on one site and a "receiver" hosted under a different domain on a totally different site. I want the sender to read in an xml file saved in a folder, and post it to the receiver. Then when I load the receiver page, I want to see the contents of the xml displayed on screen.

Here is my code so far.

SENDER.

     //Load the xml file, into an object called $message.

     if(file_exists('../XML/example.xml')) {
        $message = simplexml_load_file('../XML/example.xml');
     }
     else
     {
        exit ('Could not load the xml file from the specified path location');
   }

      //POST the data using cURL to the receiving page.
      $url = "http://dev.somewhere_else.com/receiver.php";  //destination
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
      $output = curl_exec($ch);

      curl_close($ch);
      echo $output;

      // The output gets generated and looks like an array

eg:

array(4) { ["@attributes"]=> string(5) "Array" ["header_section"]=> string(23) " " ["application_section"]=> string(18) " " ["name"]=> string(7) "example" }

So far so good? In theory this means the response via cURL is the expected data. However when I go to the other site and load the receiving page, instead of seeing something similar I get.....

          array(0) { }

          result = 

RECEIVER.

      // Display the contents of the super global..
      var_dump($_POST);          

This displays "array(0) {}" here on this page. I suspect because the data is xml, and so $_POST isn't populated. Puzzling though, as the response the sender gets display's correctly. To fix this I added..

       $dataFromPost = file_get_contents('php://input');
       echo"<br><br>result =";
       echo $dataFromPost;

So these last three lines should read the incoming stream from my "sender" and put it in the $dataFromPost variable. It should then display it on the screen, but all i get is blank...

I've read countless examples and followed many different guides, but can't get it to work the way I expect it to. Can anyone please put me out of my misery?

Tivie
  • 18,864
  • 5
  • 58
  • 77
coca_coder
  • 13
  • 5
  • How do you **load the receiving page**, are you navigating in your browser to the page? – swidmann Nov 18 '15 at 15:43
  • 1
    your message variable will contain the object of SimpleXMLElement not array which can not be passed in post request directly That's i think but please google for doing such passing object in post requst – siddhesh Nov 18 '15 at 15:45
  • you can json encode your object and at reciever.php parse it and get the object. – siddhesh Nov 18 '15 at 15:49
  • @siddhesh, I'm not sure `json_encode()` is the right way to go about that - it's not really JSON. I expect `serialize()` might work better. – HPierce Nov 18 '15 at 15:56
  • @HPierce yes you are write. – siddhesh Nov 18 '15 at 16:01
  • @swidmann Yes to load the page i am just navigating to it in browser. – coca_coder Nov 18 '15 at 16:02
  • @siddhesh I've tried json encode when sending, and json decode at receiving end. It didn't help, but i suspect it's not related. According to what i've read though, i shouldn't need to json encode. – coca_coder Nov 18 '15 at 16:04
  • @coca_coder: Well then I can't see where you expect more output than `array(0) { }`because if you are just navigate in the browser to that file, where should the post come from? – swidmann Nov 18 '15 at 16:08
  • @swidmann, This might be where i'm going wrong. The goal of the exercise for me is to pass information from one website to another and display it. I thought i could do this by storing information in an xml file, and then sending it to the other site using curl. I thought that once it was posted to the other site, it would stay there waiting to be picked up when needed. But are you saying that's not the case? How can i display something sent over using curl? Is the answer, that the receiver.php should save the data at the moment it arrives to be displayed when navigated to? – coca_coder Nov 18 '15 at 16:40

3 Answers3

0

You are setting the post fields incorrectly. Typically, you would want to pass an array with CURLOPT_POSTFIELDS like so:

curl_setopt($ch, CURLOPT_POSTFIELDS, array('message' => $message));

or even better by building a query string with http_build_query():

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('message' => $message)));

The PHP manual also describes a way of posting the entire file with this setting:

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix. As of PHP 5.5.0, the @ prefix is deprecated and files can be sent using CURLFile. The @ prefix can be disabled for safe passing of values beginning with @ by setting the CURLOPT_SAFE_UPLOAD option to TRUE.

You should then be able to receive the data from $_POST however you decide to send it.

HPierce
  • 7,249
  • 7
  • 33
  • 49
  • I've tried setting the "postfields" option using a variable before, and not had any success. To double check, i've tried your suggestion as above... curl_setopt($ch, CURLOPT_POSTFIELDS, array('message' => $message)); And not got any further. Sender displays.. array(1) { ["message"]=> string(7) " " } And receiver displays.... array(0) { } result.. – coca_coder Nov 18 '15 at 16:10
0

I have not tried the following solution but You can try

Sender code Make a JSON string of your object

$post_data['xmlobj'] = json_encode($message) //or u can use` serialize/unserialize 

pass the post data array in your request

curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

Reciever Code.

at the recieving point get Post array use json_decode get the object_string from post array and decode it

$obj = json_decode($_POST['xmlobj']); // if you are using serialize then use unserialize here.

NOTE:

  1. if you are using json_decode you will get stdclass obje
  2. if you are using unserialize then you will get simplexmlobj
siddhesh
  • 598
  • 6
  • 19
0

Like we found out in the comments, the script itself seems to work as you are getting the processed XML like you mentioned here:

// The output gets generated and looks like an array eg: array(4) { ["@attributes"]=> string(5) "Array" ["header_section"]=> string(23) " " ["application_section"]=> string(18) " " ["name"]=> string(7) "example" }

So I think you are just missunderstood the POST so I would recommend you to take a look at the manual for $_POST. You already suspected that something is different than you probably thought and you are correct with this.

Just some good and simple information about post:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked

Here you can find additional info:

So in your case, you have to save the XML. I don't know what is your intention to do, but here is a small approach:

Just take the XML from the cURL request, save it in file with file_put_contents() and add a condition (if isset post[your key] then file write else show file) to you site or split the files, one which shows only the output and one which takes your request and renews the XML.

I made this (post[your key]) bold, because you have to secure it at least a bit, otherwise I have just to post to your page and it will change.

Note without SSL it is not really possible to secure your requests, but you can at least use some key in your post to validate that this is your script, where the post comes from.

Additional information:

To get back to your question: If you post something you can see the content of the post with your var_dump() in the receiver file, If you navigate in your browser to that file $_POST is empty, because of the reason you have not postet anything, you just created a GET request. I don´t want to confuse you but the GET request method has (usually) nothing to do with the PHP $_GET variable => HTTP Request Methods

Community
  • 1
  • 1
swidmann
  • 2,787
  • 1
  • 18
  • 32
  • Thanks so much for helping to clarify this. Just to make sure I understand correctly. To send data from one website to another, and then display that data on the receiving website. I would create the data on the sending site, save it as xml. Then post that xml data to the receiving site. The receiving site needs to listen out on the input stream, and if something comes in save that data to it's own xml file. Then when you visit the receiving site, it can display that data by displaying whats been saved in the file. Is that a method that would work? – coca_coder Nov 19 '15 at 12:05
  • Yes and no :) The web server is always listening (if it's running), the rest is OK. You can also post this from one server to another by using JSON as well, or you just post a file to the receiver, so you don't have to process the xml, just take it as is, copy it on your receiver to specific path. If you open the receiver in the browser you have to look up if a xml exists on the specific path and show it. some info about file upload with curl: http://stackoverflow.com/a/15200804/5297359 – swidmann Nov 19 '15 at 12:10
  • Excellent thanks. I know it sounds like i'm trying an unusual way to skin a cat. If i wanted to do this for real, i would create the file on one site, and then upload the file to the other site. Then the receiver site can just open and display the file. But I'm trying to gain a better understanding of the difference between uploading a file, and streaming data between site's using "POST". Now i understand data streamed, isn't stored at the receiving end unless told to do so ..(such as saving it to an xml), the whole thing makes more sense. Thanks for your help and useful links. – coca_coder Nov 19 '15 at 12:24
  • You're welcome, glad that I brought some light into the darkness :) – swidmann Nov 19 '15 at 12:32