Jan Kočvara
Jan Kočvara

Reputation: 3

CURL-less HTTP request (returning array)

I am new in PHP and I am trying to access file of another website of mine. So on my web #1 I am trying to send a POST request like this:

<?php

$url = 'http://localhost/modul_cms/admin/api.php'; //Web #2

$data = array(
    "Action" => "getNewestRecipe",
    "Secret" => "61cbe6797d18a2772176b0ce73c580d95f79500d77e45ef810035bc738aef99c3e13568993f735eeb0d3c9e73b22986c57da60a0b2d6413c5dc32b764cc5897a",
    "User" => "joomla localhost",
);

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);

$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
if($result === FALSE){
    echo "Not working connection :(";
}else{
    echo "HOORAY!";
    var_dump($result);
}   

And on my web #2 I have some kind of receiver I made. Now I need to return after selecting stuff from my database array of data. So I have code like this on my web #2:

<?php
 $action = isset( $_POST["action"] ) ? $_POST["action"] : "";
 $secret = isset( $_POST["secret"] ) ? $_POST["secret"] : "";
 $user = isset( $_POST["user"] ) ? $_POST["user"] : "";

 if(!empty($secret)){
  if(!empty($user)){

   switch($action){
     case 'getNewestRecipe':
      getNewestRecipe();
      break;

    case '':
      error();
      break;

    default:
      error();
      break;
   }
  }
}

/* *************** FUNCTIONS ************* */
function getNewestRecipe(){
  return array("msg" => "Here is your message!");
}

The problem is everything I get on my web #1 from the response is actually the echo I have there for knowing that the HTTP request reached something (so I've got the message "HOORAY!") but the

var_dump($response)

has empty value (not NULL or something it's literally this):

C:\Program Files (x86)\Ampps\www\joomla30\templates\protostar\index.php:214:string '' (length=0)

Thank you for any help!

Upvotes: 0

Views: 583

Answers (1)

Tobias K.
Tobias K.

Reputation: 3082

On web#1 you are sending "Secret","User","Action" in upper-case, but on web#2 you are accessing $_POST['secret'] (lower-case). Because of this your code never gets to the call of getNewestRecipe() nor to your error() call, thus there is no content / a blank page, but also no error.

Also, you need to output the array your function returns in some way. An array cannot simply be echod, so you need to serialize it. I suggest using json_encode: echo json_encode(getNewestRecipe());

Upvotes: 1

Related Questions