Call another php from another domain and get the result - php

I'm trying to call a php from another php passing data to it and getting the return value. The two php's are on different domains.
First php:
$url = 'http://myweb.com/custom-php/createCat.php';
$data = array('name' => $name);
$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;
Second php (It's on a Wordpress site):
header("Access-Control-Allow-Origin: *");
require('../wp-load.php');
$name = $_REQUEST['name'];
echo $name;
if(isset($name))
{
echo wp_create_category($name,0);
}
else
{
echo false;
}
I get the following error:
file_get_contents(http://myweb.com/custom-php/createCat.php): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error
But if i access it via http://myweb.com/custom-php/createCat.php?name=test it works ok.

The request error could be because the allow_url_fopen PHP.ini directive is set off in the remote URL.
So an alternative may be using CURL:
<?php
$url = 'http://myweb.com/custom-php/createCat.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$result= curl_exec($curl);
curl_close($curl);
?>
Answer to the comment 'how can i send the data i need(a variable with some text)':
Use CURLOPT_POSTFIELDS:
curl_setopt($curl, CURLOPT_POSTFIELDS, "name=test&var=" . urlencode($someText));

When you visit the url you make a get request.
You should do the same in your php:
$url = 'http://myweb.com/custom-php/createCat.php';
$data = array('name' => $name);
$result = file_get_contents($url . '?' . http_build_query($data));
echo $result;
Also, you need to check if the $_REQUEST key is set before using it:
//this header is only required for ajax..
header("Access-Control-Allow-Origin: *");
require('../wp-load.php');
if(isset($_REQUEST['name'];))
{
echo wp_create_category($_REQUEST['name'],0);
}
else
{
echo false;
}

Related

How to get access token Strava Api with PHP

public function auth_callback()
{
if ($this->input->get("code") != null)
{
$this->Strava_model->UpdateProfileStravaToken($this->input->get("code"),$this->session->userdata("athlete_id"));
$url = "http://www.strava.com/oauth/token?client_id=[xxxxx]&client_secret=[xxxxxxxxxxx]&code=".$this->input->get("code")."&grant_type=authorization_code";
$post = array();
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($post)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
echo $result;exit;
$cURLConnection = curl_init($url);
curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, $post);
curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
$apiResponse = curl_exec($cURLConnection);
curl_close($cURLConnection);
$jsonArrayResponse = json_decode($apiResponse);
redirect($this->config->item("base_url") . "/activity");
}
}
I manage to get the code, and now proceed to get access token.
I'm using php curl to send post as below:
http://www.strava.com/oauth/token?client_id=[xxxx]&client_secret=[xxxxx]&code=[code retrieve from redirection]&grant_type=authorization_code
Once I executed the code above, I got this "You're being redirect..."
Can anyone advice and help?
Generally requests to the OAuth2 token endpoint require parameters to be passed as form-data, in the request body. Based on your current source, you are sending an empty request body.

API has redirecting page - PHP

I need to send data to an API using PHP. The API has a redirect page before showing the final result. The following code shows the content of the redirecting page rather than the final result. How can I wait until the final result?
$url = 'https://example.com/api';
$data = array('text' => "try");
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
echo $result;
P.S. I got this code from one of stackoverflow's questions.
You could use cURL to get the final response, using CURLOPT_FOLLOWLOCATION:
From documentation :
CURLOPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
$url = 'https://example.com/api';
$data = array('text' => "try");
$full_url = $url . (strpos($url, '?') === FALSE ? '?' : '')
. http_build_query($data) ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
var_dump($response) ;

Sending HTTP GET Request Using PHP

I use the following code to send a get request to boilerpipe java web api to extract the html contents into plain text of a website,i use telerivet webhook api to send and recieve messages to my server where the php file is located,the timeout provided is 10 sec,i get timeout always with this code,please help me out
if ($_POST['secret'] !== $webhook_secret)
{
header('HTTP/1.1 403 Forbidden');
echo "Invalid webhook secret";
}
else
{
if ($_POST['event'] == 'incoming_message')
{
$content = $_POST['content'];
$from_number = $_POST['from_number'];
$phone_id = $_POST['phone_id'];
// do something with the message, e.g. send an autoreply
header("Content-Type: application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,
'http://boilerpipe-web.appspot.com/extract?url=http://www.kvgengg.com&extractor=DefaultExtractor&output=text&extractImages='
));
$content = curl_exec($ch);
echo $content;
}
}
It seems that there is a syntax error as you have an extra parentheses in the url, I've removed it.
As well if you use http_build_query to pass in your parameter it should solve your problem
if ($_POST['secret'] !== $webhook_secret)
{
header('HTTP/1.1 403 Forbidden');
echo "Invalid webhook secret";
}
else
{
if ($_POST['event'] == 'incoming_message')
{
$content = $_POST['content'];
$from_number = $_POST['from_number'];
$phone_id = $_POST['phone_id'];
// do something with the message, e.g. send an autoreply
header("Content-Type: application/json");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,
'http://boilerpipe-web.appspot.com/extract?' .
http_build_query(array(
'url' => 'http://www.kvgengg.com',
'extractor' => 'DefaultExtractor'
'output' => 'text',
'extractImages' => ''
))
);
$content = curl_exec($ch);
echo $content;
}
}

cURL not actually sending POST data

Overview
I have a script, we'll call it one.php, that creates a database and tables. It also contains an array of data to be posted to another script, two.php, which will sort through the data and insert it into our newly created database.
Your help is much, much appreciated.
The Problem
two.php has a check for the $_POST[] array at the very top of the script:
if (empty($_POST))
{
$response = array('status' => 'fail', 'message' => 'empty post array');
echo json_encode($response);
exit;
}
Normally, this would not be triggered unless the post array is, well, empty(). However, when sending the data from one.php to two.php via cURL, I'm receiving the above encoded array as my response, and my data does not progress further down two.php.
I'll lay out the relevant code from the files below for your viewing pleasure:
one.php
$one_array = array('name' => 'John', 'fav_color' => 'red');
$one_url = 'http://' . $_SERVER['HTTP_HOST'] . '/path/to/two.php';
$response = post_to_url($one_url, $one_array, 'application/json');
echo $response; die;
This is currently giving me the below:
{"status":"fail","message":"empty post array"}
The post_to_url() function, for reference
function post_to_url($url, $array, $content_type)
{
$fields = '';
foreach($array as $key => $value)
{
$fields .= $key . '=' . $value . '&';
}
$fields = rtrim($fields, '&');
$ch = curl_init();
$httpheader = array(
'Content-Type: ' . $content_type,
'Accept: ' . $content_type
);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
two.php
header("Content-type: application/json");
$response = array(); //this is used to build the responses, like below
if (empty($_POST))
{
$response['status'] = 'fail';
$response['message'] = 'empty post array';
echo json_encode($response);
exit;
}
elseif (!empty($_POST))
{
//do super neat stuff
}
Because you're setting the request body content type as "application/json", PHP will not populate $_POST in "two.php". Because you're sending url encoded data, the best thing to do is only send the Accept: header:
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: ' . $content_type]);
That said, "two.php" doesn't actually use the Accept: header and always outputs JSON; in that case, you can make do with not setting CURLOPT_HTTPHEADER at all.
Update
Creating url encoded data from an array can be simpler (and safer) too:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($array));
I have some issue like that, but in my case I added
Content-Type: {APPLICATION/TYPE}
Content-Length: {DATA LENGTH}
and problem was solved.

Submit form on one server, process it and then post results to another domain

I have a form on one page with the action set to /process.php
Within the process.php I have the validation of the form and also it writes to a database on the server it sits on.
What I'd like to do after it has written to the database, is post the variables to another domain that will then process those variables differently.
Example using curl:
$name = 'Test';
$email = 'test#gmail.com';
$ch = curl_init(); // initialize curl handle
$url = "http://domain2.com/process.php";
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // times out after 10s
curl_setopt($ch, CURLOPT_POST, 1); // set POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, "text=$name&name=$email"); // post fields
$data = curl_exec($ch); // run the whole process
curl_close($ch);
Example without curl: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/
you can use file_get_contents for the same.
Example:
$name="foobar";
$messge="blabla";
$postdata = http_build_query(
array(
'name' => $name,
'message' => $message
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = #file_get_contents('http://yourdomain.com/process_request.php', false, $context);
if($http_response_header[0]=="HTTP/1.1 404 Not Found"):
echo "iam 404";
elseif($http_response_header[0]=="HTTP/1.1 200 OK"):
echo "iam 200";
else:
echo "unknown error";
endif;

Categories