Link to home
Start Free TrialLog in
Avatar of BR
BRFlag for Türkiye

asked on

Sending JSON Via POST In PHP

Dear Experts,
I'm new with sending data in Json format,
Reading posted data in Json format is ok for me. ( Thanks to Ray Paseur )

I use below code on my json.php page. When I visit json.php page, I'm expecting the code runs and the page posts $jsonData to the myurl.php . Normally when I post a data with html form, my page is going to action page, and I'm expecting here the same, I'm waiting to go myurl.php but json.php goes nowhere and it gives no error.

PHP works when a page is called, right? So that I guess, it doesn't post anything, right?

I'm using shared hosting with PHP 5.6

<?php

//API Url
$url = 'myurl.php;

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'username' => 'MyUsername',
    'password' => 'MyPassword'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

Open in new window


//the code is here: http://thisinterestsme.com/sending-json-via-post-php/
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

I don't see where you are setting the URL for the POST request.  See line 70 in the code example below.  You have to give this information to cURL.

Here's the discussion of JSON in PHP
https://www.experts-exchange.com/articles/22519/Understanding-JSON-in-PHP-and-JavaScript-Applications.html

Here's a script that makes a POST-method request.  I use this as my template when talking to APIs that expect POST.  You can install it and use it to post information to my request reflector script.
<?php // demo/curl_post_example.php
/**
 * Demonstrate how to use cURL to make a POST request
 * This may be used to start an asynchronous process
 * Property 'title' is a comment field to identify the object
 *
 * http://php.net/manual/en/book.curl.php
 * https://curl.haxx.se/libcurl/c/
 * https://curl.haxx.se/libcurl/c/libcurl-errors.html
 */
error_reporting(E_ALL);


// USAGE EXAMPLE CREATES ASSOCIATIVE ARRAY OF KEY=>VALUE PAIRS
$args["name"] = 'Ray';
$args["mail"] = 'Ray.Paseur@Gmail.com';

// SET THE URL
$url = "https://Iconoun.com/demo/request_reflector.php";

// CREATE THE RESPONSE OBJECT
$response = new POST_Response_Object($url, $args, 'TESTING 1 2 3...');

// SHOW THE WORK PRODUCT
echo "<pre>";
if ( $response->document) echo htmlentities($response->document); // ON SUCCESS SHOW RETURNED DOCUMENT
if (!$response->document) print_r($response); // ON FAILURE SHOW ERROR INFORMATION

// SHOW CURL RESPONSE MESSAGES FOR DEBUGGING
unset($response->document);
echo PHP_EOL . PHP_EOL;
print_r($response);

// OPTIONAL -- SHOW THE COOKIES, IF ANY
echo PHP_EOL . PHP_EOL;
echo @file_get_contents('cookie.txt');


Class POST_Response_Object
{
    public $href, $title, $http_code, $errno, $error, $info, $document;

    public function __construct($href, $post_array=[], $title=NULL)
    {
        // ACTIVATE THIS TO AVOID TIMEOUT FOR LONG RUNNING SCRIPT
        // set_time_limit(10);

        // STORE THE CALL INFORMATION
        $this->href  = $href;
        $this->title = $title;

        // CREATE THE REFERRER
        $refer = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        // PREPARE THE POST STRING
        $post_string = http_build_query($post_array);

        // MAKE THE REQUEST
        if (!$this->my_curl($href, $post_string, $refer))
        {
            // ACTIVATE THIS TO SEE THE ERRORS AS THEY OCCUR
            // trigger_error("Errno: $this->errno; HTTP: $this->http_code; URL: $this->href", E_USER_WARNING);
        }
    }

    protected function my_curl($url, $post_string, $refer, $timeout=3)
    {
        // PREPARE THE CURL CALL
        $curl = curl_init();
        curl_setopt( $curl, CURLOPT_URL,            $url           );
        curl_setopt( $curl, CURLOPT_REFERER,        $refer         );
        curl_setopt( $curl, CURLOPT_HEADER,         FALSE          );
        curl_setopt( $curl, CURLOPT_POST,           TRUE           );
        curl_setopt( $curl, CURLOPT_POSTFIELDS,     $post_string   );
        curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate' );
        curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout       );
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE           );
        curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE           );
        curl_setopt( $curl, CURLOPT_FAILONERROR,    TRUE           );

        // IF USING SSL, THIS INFORMATION IS IMPORTANT -- UNDERSTAND THE SECURITY RISK!
        curl_setopt( $curl, CURLOPT_SSLVERSION,     CURL_SSLVERSION_DEFAULT  );
        curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2  ); // DEFAULT
        curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 1  ); // DEFAULT

        // SET THE LOCATION OF THE COOKIE JAR (THIS FILE WILL BE OVERWRITTEN)
        curl_setopt( $curl, CURLOPT_COOKIEFILE,     'cookie.txt' );
        curl_setopt( $curl, CURLOPT_COOKIEJAR,      'cookie.txt' );

        // RUN THE CURL REQUEST AND GET THE RESULTS
        $this->document  = curl_exec($curl);
        $this->errno     = curl_errno($curl);
        $this->info      = curl_getinfo($curl);
        $this->http_code = $this->info['http_code'];
        curl_close($curl);

        // RETURN THE OBJECT
        return $this;
    }
}

Open in new window

Avatar of BR

ASKER

Dear Ray Paseur,
thank you very much. I will read the article again.

I need to ask this, it's like a splinter in my mind..

when I post the data, the data should be posted to this url, right?
$url = "https://Iconoun.com/demo/request_reflector.php";
so when I run your code, the page should post the name & mail to https://Iconoun.com/demo/request_reflector.php , right?
but the page brings lots of information and stays on the same page?
Let me read the article first, then write you again. Thank you
Yes, you should be able to make the POST request to https://iconoun.com/demo/request_reflector.php

Here is the request reflector script.
<?php // demo/request_reflector.php
/**
 * Bounce the request vars back
 */
error_reporting(E_ALL);
date_default_timezone_set('America/Chicago');

// START A BUFFER TO CAPTURE THE BROWSER OUTPUT
ob_start();

// USE PREFORMATTING TO MAKE THE OUTPUT EASY TO READ
echo '<pre>';

// SHOW THE COOKIE(S)
echo '$_COOKIE: ';
var_dump($_COOKIE);
echo PHP_EOL;

// SHOW THE GET REQUEST
echo '$_GET: ';
var_dump($_GET);
echo PHP_EOL;

// SHOW WHAT WAS RECEIVED IN POST
echo '$_POST: ';
var_dump($_POST);
echo PHP_EOL;

// SHOW WHAT WAS RECEIVED IN FILES
echo '$_FILES: ';
var_dump($_FILES);
echo PHP_EOL;

// CAPTURE THE BUFFER
$request_data = ob_get_clean();

// SAY THANK YOU
$refer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '(empty referrer)';
echo 'REQUEST REFLECTED FROM ' . $refer . ' AT ' . date('c');
echo PHP_EOL;
echo $request_data;

Open in new window

The additional information you are seeing is just stuff from cURL.   If you don't want it, you can remove the instructions that print this information (lines 29-36).  I used it mostly for debugging, and for teaching how to use cURL.
Avatar of BR

ASKER

Dear Ray Paseur, thank you again.
I saved the first code as json.php and run the page, but it didn't go to request_reflector.php page.

I just copy and past the code to be sure that I didn't break anything, but the page doesn't go anywhere..
the page stays on the same url as json.php .

when I run the page, it is not going to request_reflector.php page.
Thank you for your patience...
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BR

ASKER

Now I get it :)
Thank you so much

I think i can use it also for Hand Shake if I need it

Thank you so much
Avatar of BR

ASKER

thank you so much