pastalover1234 pastalover1234 - 1 year ago 94
SQL Question

PHP to connect to remote Parse MongoDB; cURL works on command line but PHP file_get_contents doesn't

I am working with a Wordpress site with CPanel and a MySQL database. I want to be able to read data from a MongoDB held on Eventually, I want to change Wordpress's login.php script to search through the MongoDB and create users if necessary.

I am having lots of trouble connecting to the database.

Here is my php script:

$url = '';
$data = array('username' => 'username', 'password' => 'password');
$appID = "X-Parse-Application-Id: parseAppID";
$restKey = "X-Parse-REST-API-Key: praseRESTapiKey";
$session = "X-Parse-Revocable-Session: 1";
$contentType = "Content-Type: application/json";

$context = array(
'http'=> array(
"method" => "GET",
"header" => $appID . $restKey . $session . $contentType,
"content" => http_build_query($data)));

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


The errors I am receiving are:

Notice: file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded in C:\wamp\www\parseDB.php on line 26

Warning: file_get_contents( failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\wamp\www\parseDB.php on line 26

From my understanding, the 403 error means the web server is returning the "forbidden" status code.

I am testing my php script on localhost using WAMP. A colleague of mine tried to run a similar command on Bash and received a response. (I broke it out so it is easier to read).

curl -X GET
-H "X-Parse-Application-Id: parseAppID"
-H "X-Parse-REST-API-Key: parseRESTapiKey"
-H "X-Parse-Revocable-Session: 1"
-G --data-urlencode 'username=username' --data-urlencode 'password=password'

I have been stuck on this for 2 days so far, and I have no idea what is going on. I appreciate all the help I can get.

Here is my final solution:

$url = '';
$data = array('username' => 'USERNAME', 'password' => 'PASSWORD!');

$context = array(
'http'=> array(
'method' => "GET",
'header' => "X-Parse-Application-Id: APPID\r\n" .
"X-Parse-REST-API-Key: RESTAPIKEY\r\n" .
"X-Parse-Revocable-Session: 1" .
"Content-Type: application/json\r\n",
'content' => http_build_query($data)
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);

Answer Source

Look at the stream_content_create example at which explains how to pass headers properly. At this time, you slam each header together without any line feeds which will make them look like concatenated string:

X-Parse-Application-Id: parseAppIDX-Parse-REST-API-Key: praseRESTapiKeyX-Parse-Revocable-Session: 1Content-Type: application/json

Hint - add \r\n after each header line.

Instead of file_get_contents you could also use curl methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download