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!
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());
Related
Hi i am using php file_get_contents method to get content. For getting high content it makes problem about bandwidth. I like to get gzip format data to get and decode to it later.
I collected a sample one but it show quite similar content length. here it is
<?php
function fetchUrl( $url, $gzip = false ) {
$raw = file_get_contents( $url, false, $context = stream_context_create( array(
'http' => array(
'method' => 'GET',
'header' => 'Accept-Encoding:' . ( $gzip ? 'gzip,deflate' : 'identity' ) . "\r\n",
)
) ) );
if ( $raw === false ) {
return false;
}
return $gzip ? gzdecode( $raw ) : $raw;
}
$src1 = fetchUrl( 'http://www.google.com' );
$src2 = fetchUrl( 'http://www.google.com', true );
echo strlen($src1). "<br>";
echo strlen($src2);
?>
which results
52233
52232
if there a better solution please help me or redirect me any solution present this site.
NB: i searched but do not get exact one, if i may wrong then provide that link where i get proper solution.
TIA.
I am using PHP with XAMPP and Dialogflow to create a chat interface. In a simple intent(question) in Dialogflow, I have created a webhook to XAMPP regarding the question 'Who is X' (e.g. Paul, George). Therefore , I place a POST REQUEST in order to have access to the json form of this question in DIalogflow so that I can answer it as I want to. Specifically, the ultimate goal of this is to retrieve some data from a MySQL database in phpMyAdmin about this question and respond for example that 'X is a developer' or 'X is a financial analyst'. This is why wrote a php script which is the following:
<?php
$method = $_SERVER['REQUEST_METHOD'];
// Process when it is POST method
if ($method == 'POST') {
$requestBody = file_get_contents('php://input');
$json = json_decode($requestBody);
$text = $json->result->parameters;
switch($text) {
case 'given-name':
$name = $text->given-name;
$speech = $name . 'is a developer';
break;
default:
$speech = 'Sorry I did not get this. Can you repeat please?';
}
$response = new \stdClass();
$response->speech = "";
$response->displayText = "";
$respone->source = "webhook";
echo json_encode($response);
}
else
{
echo "Method not allowed";
}
?>
However, the output of this program is: Method not allowed.
Paradoxically enough $method has the value 'GET' so it identifies a GET REQUEST while Dialogflow explicitly states at the webhook page that
Your web service will receive a POST request from Dialogflow in the
form of the response to a user query matched by intents with webhook
enabled.
Hence I am wondering: why my php script cannot see and process the POST REQUEST from Dialogflow?
P.S. Questions close to mine are the following: Form sends GET instead of POST, Why is $_SERVER['REQUEST_METHOD'] always GET?.
It doesn't work because $_SERVER['REQUEST_METHOD'] == "GET" by default.
So you program execute the 'else' condition.
You need to submit a request with the POST method to change this value.
You can use
<form method="POST">
[...]
</form>
in your HTML, or
$.ajax({
url : "ajax_url.php",
type : 'POST',
data : 'data='+data,
[...]
});
in your AJAX JS code for example
Here i am doing same like you from below code your Query will be resolved,
index.php
<?php
require 'get_enews.php';
function processMessage($input) {
$action = $input["result"]["action"];
switch($action){
case 'getNews':
$param = $input["result"]["parameters"]["number"];
getNews($param);
break;
default :
sendMessage(array(
"source" => "RMC",
"speech" => "I am not able to understand. what do you want ?",
"displayText" => "I am not able to understand. what do you want ?",
"contextOut" => array()
));
}
}
function sendMessage($parameters) {
header('Content-Type: application/json');
$data = str_replace('\/','/',json_encode($parameters));
echo $data;
}
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input["result"]["action"])) {
processMessage($input);
}
?>
get_enews.php
<?php
function getNews($param){
require 'config.php';
$getNews="";
$Query="SELECT link FROM public.news WHERE year='$param'";
$Result=pg_query($con,$Query);
if(isset($Result) && !empty($Result) && pg_num_rows($Result) > 0){
$row=pg_fetch_assoc($Result);
$getNews= "Here is details that you require - Link: " . $row["link"];
$arr=array(
"source" => "RMC",
"speech" => $getNews,
"displayText" => $getNews,
);
sendMessage($arr);
}else{
$arr=array(
"source" => "RMC",
"speech" => "No year matched in database.",
"displayText" => "No year matched in database.",
);
sendMessage($arr);
}
}
?>
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input
i want the php script to be able the get json using Unirest php
<?php
require_once 'src/Unirest.php';
$word = 'Cartoon newttork';
// return: convert-spaces-to-underscore-and-lowercase-with-php
$word = str_replace(' ', '_', strtolower($word));
// These code snippets use an open-source library.
$response = Unirest\Request::get("https://od-api.oxforddictionaries.com:443/api/v1/entries/en/$word",
array(
"Accept" => "application/json", // accept app as json
"app_id" => "xxxxx", // app id found in dashboard
"app_key" => "xxxxxx" //app key also found in dashboard
)
);
$word_name = $response->body;
if ($word_name === "Not Found") {
echo "Not Found";
}
?>
i want is to be something like this
$word_name = $response->body;
if ($word_name === "Not Found") {
echo "Not Found";
}
P.S if you have another php http client that is better write it down also
I'm using HTTP post request from Codeigniter to python and return a tuple from MySQL to python
Codeigniter controller:
$data['email'] = $this->input->post("email");
$url = 'http://domain/path';
$data = array('email' => $data['email']);
// 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);
var_dump($result);
Python code:
elif self.path=="/forgotpass":
print "forgot password module"
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
self.send_response(200)
self.send_header('Content-type','text/html')
self.send_header("Access-Control-Allow-Origin","http://domain")
self.end_headers()
#print form['email'].value
email = str(form["email"].value)
sql = "SELECT email_address, personal_id from personal_info where email_address='"+email+"'"
result = validate(sql)
print result
#print email;
self.wfile.write(result)
def validate(sql):
try:
db = MySQLdb.connect("localhost","root","password","schema" )
cnn = db.cursor()
cnn.execute(sql)
return cnn.fetchone()
cnn.close()
except MySQLdb, e:
print "Error validate function"
The display is, I think this is now a string format.
string(36) "('jerahmeel.acebuche#smsgt.com', 2L)"
In a simple Codeigniter connecting to a model.
The result of an array from mysql is:
array (column => value) etc etc..
You could display that array using foreach and $item->data;
But this result came from python which is a tuple and returning it to PHP is a different approach.
How will I break this tuple in PHP? or should I break it on python and return it to PHP?
I have this method:
protected function _sendRequest($url, $method, Busca_Cxense_Data $data, $get = null) {
if (! isset ( $this->_urls [$url] )) {
throw new Busca_Cxense_Exception_Argument ( "El tipo de url enviado no es valido. (type: {$url})" );
}
$url = $this->_urls [$url] . $data->getUrlKey () . ($get ? "$get" : '');
$httpConfig = array ('http' => array ('method' => $method, 'request_fulluri' => $url, 'ignore_errors' => false ) );
if ($data->getSendJson ()) {
$json = $this->_setJson ( $data );
$header = "Content-Type: application/json\r\nContent-Length: " . strlen ( $json );
$httpConfig ['http'] ['content'] = $json;
} else {
$header = "Content-Type: text/html";
}
$httpConfig ['http'] ['header'] = $header;
$context = stream_context_create ( $httpConfig );
$stream = fopen ($url, 'r', false, $context);
$result = stream_get_contents($stream);
$headers = stream_get_meta_data($stream);
fclose($stream);
if (! $result) {
print_r ( $data );
var_dump ( $url );
print_r ( $httpConfig );
throw new Busca_Cxense_Exception_MethodCall ( "Bad call. \nString: $json\n" );
}
var_dump($result); exit;
return array ('json' => json_decode ( $result ), 'string' => $result, 'headers' => $headers );
}
As you can see, it create a context and open an stream. However, I have a error very strange. If I send this url:
http://sandbox.cxsearch.cxense.com/api/search/levelup?p_aq=query%28category^1:%22preview%20trailer%22,token-op=or%29&p_sm=idobject:desc&p_s=0&p_c=20&p_dr=title
it throws a bad request error, but if I send this other one:
http://sandbox.cxsearch.cxense.com/api/search/levelup?p_q=test&p_sm=idobject:desc&p_s=0&p_c=20&p_dr=title
it works as expected. Do I have to encode the url or something?
FIXED
I was able to figure what the problem was. I Only need to change the space for %20. And that was all...
400 response is returned by remote server, so you want to see specs/contact people on that side on how to build correct query.
The urls you provide look very different and remote system might have own validation rules on values, list of provided parameters, etc. Also it might require some specific headers and/or request body.
I was able to figure what the problem was. I Only need to change the space for %20. And that was all...