-2

I am android developer and have some knowledge in php. I need to make post request in php. I found two ways to achieve it.

1. Using CURL.

$url = "your url";    
$content = json_encode("your data to be sent");

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) {
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}


curl_close($curl);

$response = json_decode($json_response, true);

2. Using Simple Post(file_get_contents).

$options = array(
  'http' => array(
    'method'  => 'POST',
    'content' => json_encode( $data ),
    'header'=>  "Content-Type: application/json\r\n" .
                "Accept: application/json\r\n"
    )
);

$context  = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );

But, I just want to know which is better and efficient way to do that and why? Is there any server/browser or any platform related issue any of them? Or is there any other technique to achieve that? Suggestions are welcome.Thanks

SRB Bans
  • 3,096
  • 1
  • 10
  • 21
  • 1
    Possible duplicate of [PHP cUrl vs file\_get\_contents](http://stackoverflow.com/questions/11064980/php-curl-vs-file-get-contents) – Alex Andrei Nov 07 '15 at 14:57

2 Answers2

1

Best way to achieve is always

  1. Using CURL.

as this is fastest & more reliable..

Munjal Mayank
  • 131
  • 1
  • 10
0

If you are just sending a JSON reply from a PHP script launched by a call from your Android JAVA code then the simplest and probably the fasted is just to echo the JSON string from your PHP script.

i.e.

<?php

    // read the $_POST inputs from Android call

    // Process whatever building an array 
    // or better still an object containing all
    // data and statuses you want to return to the
    // android JAVA code

    echo json_encode($theObjectOrArray);
    exit;

This way it is all part of the same post/responce. If you get CURL involved you are breaking the simple life cycle.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • first of all thnx for comment... Actually am using mysql database with local webserver and php on my android device(like wamp server).. i am making a call to my local php script to fetch data from local mysql database and send it to the server side php script and database. – SRB Bans Nov 09 '15 at 07:07