How to use CURL to send data for Wordpress - php

I would like to send data from one WP site to an other.
I have two plugins the sender ad the reciver.
In the sender side I used the init hook
add_action('init', array($this, 'say_hello') );
....
public function say_hello() {
$data = get_plugin_data( $this->pDIR.'/plugin.php', $markup = false, $translate = false );
$url = $_SERVER['HTTP_HOST'].'/wp-admin/admin-ajax.php';
$fields = array(
'action' => 'Hello_ajax',
'zpm_hello' => '1',
'zpm_plugin_version' => $data['Version'],
'zpm_host' => $_SERVER['HTTP_HOST']
);
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
var_dump($result);
//close connection
curl_close($ch);
}
The variables are fine the url is correct I printed out.
On the reciver side I registered the admin ajax
add_action('wp_ajax_Hello_ajax', array($this, 'zpm_api_hello'));
add_action('wp_ajax_nopriv_Hello_ajax', array($this, 'zpm_api_hello'));
public function zpm_api_hello() {
$response['success'] = false;
$response['response'] = "";
$error = false;
$hello = $_POST['zpm_hello'];
$plugin_version = $_POST['zpm_plugin_version'];
$plugin_host = $_POST['zpm_host'];
if(!isset($hello)) {
$error = true;
$response['response'] .= "Ello >> Auth ERROR - CODE - 01 ";
}
if(!isset($plugin_version)) {
$error = true;
$response['response'] .= "Ello >> Plugin Version error - CODE - 02 ";
}
if(!isset($plugin_host)) {
$error = true;
$response['response'] .= "Ello >> Plugin host error - CODE - 03 ";
}
if(!$error) {
$response['success'] = true;
$response['response'] .= "Ello >> Auth OK ";
}
echo json_encode($response);
die();
}
So the code is here.
My problem is when I try to load the sender site it is just loading and loading for ever and I doesn't get back the result. Could you tell me what could be the problem with this method? Thanks all of your answers!

you might want to use this example to build your PHP request, if you send me the POST body, headers and url parameters I will even build it for you:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com//wp-admin/admin-ajax.php",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "blakey=blaval",
CURLOPT_HTTPHEADER => array(
"action: Hello_ajax",
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded",
"postman-token: fd5bcc0b-f46d-0cf8-a5cf-dc83bfe7dbec",
"zpm_hello: 1"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

Related

From Postman to PHP: Can't Properly Generate an Oauth 1 Signature

I’m having a rough time getting a simple Oauth 1 api call to work. I’ve figured out how to access the data I want via Postman and have made successful calls for lists, starred items, etc. If I copy an already-run call from postman and rerun it locally, as long as the timestamp is the timeout time (3 minutes) the api will accept it and I’ll be able to receive and parse the json data.
I've tested and run all of the elements of the code in isolation and everything seems to work fine... What seems to not work is generating a proper signature.
Full code is below... Any help is appreciated!
<?php
// Include Manually Entered Credentials
include 'credentials.php';
####################################
// GENERATE TIMESTAMP:
$oathtimestamp = time();
// GENERATE NONCE:
function generateNonce() {
$length = 15;
$chars='1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
$ll = strlen($chars)-1;
$o = '';
while (strlen($o) < $length) {
$o .= $chars[ rand(0, $ll) ];
}
return $o;
}
$oathnonce = generateNonce();
####################################
// API Determinants
$APIurl = "https://www.example.com/api/";
####################################
// GENERATE Oath1 Signature:
$signatureMethod = "HMAC-SHA1";
$oathVersion = "1.0";
$base = "POST&".$APIurl."&"."folder_id=starred"."&limit=25"."&oauth_consumer_key=".$oauth_consumer_key."&oauth_nonce=".$oathnonce."&oauth_signature_method=".$signatureMethod."&oauth_timestamp=".$oathtimestamp."&oauth_token=".$oauth_token."&oauth_version=".$oathVersion."&x_auth_mode=client_auth"."&x_auth_password=".$x_auth_password."&x_auth_username=".$x_auth_username;
//echo $base;
$key = $oauth_consumer_key."&".$oath_tokenSecret;
//echo $key;
$signature = base64_encode(hash_hmac('sha1', $oauth_consumer_key, $key));
//echo $signature;
$oath_getstringlength =
"folder_id=starred".
"&limit=25".
"&oauth_consumer_key=".$oauth_consumer_key.
"&oauth_nonce=".$oathnonce.
"&oauth_signature=".$signature.
"&oauth_signature_method=".$signatureMethod.
"&oauth_timestamp=".$oathtimestamp.
"&oauth_token=".$oauth_token.
"&oauth_version=".$oathVersion.
"&x_auth_mode=client_auth".
"&x_auth_password=".$x_auth_password.
"&x_auth_username=".$x_auth_username;
$oath_stringlength = strlen($oath_getstringlength);
//echo $oath_stringlength;
####################################
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.example.com/api/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>
"folder_id=starred".
"&limit=25".
"&oauth_consumer_key=".$oauth_consumer_key.
"&oauth_nonce=".$oathnonce.
"&oauth_signature=".$signature.
"&oauth_signature_method=".$signatureMethod.
"&oauth_timestamp=".$oathtimestamp.
"&oauth_token=".$oauth_token.
"&oauth_version=".$oathVersion.
"&x_auth_mode=client_auth".
"&x_auth_password=".$x_auth_password.
"&x_auth_username=".$x_auth_username,
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Accept-Encoding: gzip, deflate",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Content-Length: $oath_stringlength",
"Content-Type: application/x-www-form-urlencoded",
"Host: www.example.com",
"User-Agent: curlAPICall",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "... cURL Error #:" . $err;
} else {
echo $response;
$jsonresponse = json_decode($response, true);
print_r($jsonresponse);
}
?>

How to send an XML-file with PHP cURL?

This question is market as answered in this thread:
How to POST an XML file using cURL on php?
But that answer wasn't really the correct answer in my opinion since it just show how to send XML code with cURL. I need to send an XML file.
Basically, I need this C# code to be converted to PHP:
public Guid? UploadXmlFile()
{
var fileUploadClient = new WebClient();
fileUploadClient.Headers.Add("Content-Type", "application/xml");
fileUploadClient.Headers.Add("Authorization", "api " + ApiKey);
var rawResponse = fileUploadClient.UploadFile(Url, FilePath);
var stringResponse = Encoding.ASCII.GetString(rawResponse);
var jsonResponse = JObject.Parse(stringResponse);
if (jsonResponse != null)
{
var importFileId = jsonResponse.GetValue("ImportId");
if (importFileId != null)
{
return new Guid(importFileId.ToString());
}
}
return null;
}
I have tried in several ways and this is my latest try.
The cURL call:
/**
* CDON API Call
*
*/
function cdon_api($way, $method, $postfields=false, $contenttype=false)
{
global $api_key;
$contenttype = (!$contenttype) ? 'application/x-www-form-urlencoded' : $contenttype;
$curlOpts = array(
CURLOPT_URL => 'https://admin.marketplace.cdon.com/api/'.$method,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTPHEADER => array('Authorization: api '.$api_key, 'Content-type: '.$contenttype, 'Accept: application/xml')
);
if ($way == 'post')
{
$curlOpts[CURLOPT_POST] = TRUE;
}
elseif ($way == 'put')
{
$curlOpts[CURLOPT_PUT] = TRUE;
}
if ($postfields !== false)
{
$curlOpts[CURLOPT_POSTFIELDS] = $postfields;
}
# make the call
$ch = curl_init();
curl_setopt_array($ch, $curlOpts);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
The File Export:
/**
* Export products
*
*/
function cdon_export()
{
global $api_key;
$upload_dir = wp_upload_dir();
$filepath = $upload_dir['basedir'] . '/cdon-feed.xml';
$response = cdon_api('post', 'importfile', array('uploaded_file' => '#/'.realpath($filepath).';type=text/xml'), 'multipart/form-data');
echo '<br>Response 1: <pre>'.print_r(json_decode($response), true).'</pre><br>';
$data = json_decode($response, true);
if (!empty($data['ImportId']))
{
$response = cdon_api('put', 'importfile?importFileId='.$data['ImportId'], false, 'text/xml');
echo 'Response 2: <pre>'.print_r(json_decode($response), true).'</pre><br>';
$data = json_decode($response, true);
}
}
But the output I get is this:
Response 1:
stdClass Object
(
[Message] => The request does not contain a valid media type.
)
I have experimented around with different types at the different places, application/xml, multipart/form-data and text/xml, but nothing works.
How do I do to make it work? How do I manage to send the XML file with cURL?
to me, it looks like the C# code just does the equivalent of
function UploadXmlFile(): ?string {
$ch = curl_init ( $url );
curl_setopt_array ( $ch, array (
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array (
"Content-Type: application/xml",
"Authorization: api " . $ApiKey
),
CURLOPT_POSTFIELDS => file_get_contents ( $filepath ),
CURLOPT_RETURNTRANSFER => true
) );
$jsonResponse = json_decode ( ($response = curl_exec ( $ch )) );
curl_close ( $ch );
return $jsonResponse->importId ?? NULL;
}
but at least 1 difference, your PHP code adds the header 'Accept: application/xml', your C# code does not

How to get/set Header in Rest Server API?

i have a chriskacerguis Rest Server ,that listen for a client request as usually an API Server do.
base on client request i want to send/response some data to client in header only.
my questions are:
how do i access Client header first? then
how do i set Header in Rest Server?
This is how i send a request to REST SERVER:
function request_curl($url = NULL) {
$utc = time();
$post = "id=1&CustomerId=1&amount=2450&operatorName=Jondoe&operator=12";
$header_data = array(
"Content-Type: application/json",
"Accept: application/json",
"X-API-KEY:3ecbcb4e62a00d2bc58080218a4376f24a8079e1",
"X-UTC:" . $utc,
);
$ch = curl_init();
$curlOpts = array(
CURLOPT_URL => 'http://domain.com/customapi/api/clientRequest',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $header_data,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HEADER => 1,
);
curl_setopt_array($ch, $curlOpts);
$answer = curl_exec($ch);
// If there was an error, show it
if (curl_error($ch)) {
die(curl_error($ch));
}
curl_close($ch);
echo '<pre>';
print_r($answer);
echo '</pre>';
}
Below is my REST SERVER function that listen request and will response a header:
public function clientRequest_post() {
// Getting Post Data
$entityBody = file_get_contents('php://input', 'r');
$this->response($entityBody,200);
//getting header data ,no idea
}
May be try php function getallheaders() which will fetch all the header data for you. If you want to convert it into array, use foreach.
So this will get you the header data and will convert it into array
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
Now if you want to get body and convert it into array as well
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
The final function will look something like this...
public function clientRequest_post() {
$headers=array();
foreach (getallheaders() as $name => $value) {
$headers[$name] = $value;
}
$entityBody = file_get_contents('php://input', 'r');
parse_str($entityBody , $post_data);
$this->response($entityBody, 200);
}
Btw, I assume $this->response($entityBody,200); will generate the response for you. Best of luck with it

Extract string inside multi-quoted variable

I've a variable with multiple single quotes and want to extract a string of this.
My Code is:
$image['src'] = addslashes($image['src']);
preg_match('~src=["|\'](.*?)["|\']~', $image['src'], $matches);
$image['src'] = $matches[1];
$image['src'] contains this string:
tooltip_html(this, '<div style="display: block; width: 262px"><img src="https://url.com/var/galerie/15773_262.jpg"/></div>');
I thought all would be right but $image['src'] returns null. The addslashes method works fine and returns this:
tooltip_html(this, \'<div style="display: block; width: 262px"><img src="https://url.com/var/galerie/15773_262.jpg"/></div>\');
I don't get the problem in here, did I miss something?
=====UPDATE======
The whole code:
<?php
error_reporting(E_ALL);
header("Content-Type: application/json", true);
define('SITE', 'https://akipa-autohandel.autrado.de/');
include_once('simple_html_dom.php');
/**
* Create CDATA-Method for XML Output
*/
class SimpleXMLExtended extends SimpleXMLElement {
public function addCData($cdata_text) {
$node = dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
}
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url ) {
$user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';
$options = array(
CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get
CURLOPT_POST =>false, //set to GET
CURLOPT_USERAGENT => $user_agent, //set user agent
CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file
CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
if($content === FALSE) {
// when output is false it can't be used in str_get_html()
// output a proper error message in such cases
echo 'output error';
die(curl_error($ch));
}
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
function renderPage( $uri ) {
$rendering = get_web_page( $uri );
if ( $rendering['errno'] != 0 )
echo 'bad url, timeout, redirect loop';
if ( $rendering['http_code'] != 200 )
echo 'no page, no permissions, no service';
$content = $rendering['content'];
if(!empty($content)) {
$parsing = str_get_html($content);
}
return $parsing;
}
/**
* Get all current car data of the selected autrado site
*/
function models() {
$paramURI = SITE . 'schnellsuche.php?suche_hersteller=14&suche_modell=&suche_from=form&suche_action=suche&itemsperpage=500';
$content = renderPage($paramURI);
foreach ($content->find('tr[class*=fahrzeugliste]') as $auto) {
$item['src'] = $auto->find('a[onmouseover]', 0)->onmouseover;
preg_match('~src=["\'](.*?)["\']~', $item['src'], $matches);
echo $matches[1];
}
}
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
if((string) $action == 'test') {
$output = models();
json_encode($output);
}
}
?>
The content of $image['src'] is not as you wrote above. I've run now your script and the content is:
tooltip_html(this, '<div style="display: block; width: 262px"><img src="http://server12.autrado.de/autradogalerie_copy/var/galerie/127915_262.jpg" /></div>');
It will work if you add the following line before the preg_match:
$item['src']= html_entity_decode($item['src']);

Restful API for CakePHP 2

I am creating a Restful WebService with CakePHP 2 however, i am getting 500 Internal Server Error since i am not able to capture Post Data. The Rest Server is as below:
App::import ( 'Vendor', 'ExchangeFunctions', array ('file'=> 'exchange/exchangefunctions.php'));
class ExchangeController extends AppController
{
public $components = array('RequestHandler');
public
function index()
{
$exchange = new ExchangeFunctions();
$data = $this->request->data('json_decode');
$exchange->username = $_POST['username'];
$exchange->password = $_POST['password'];
$emailList = $exchange->listEmails();
$response = new stdClass();
$response->emailList = $emailList;
foreach($emailList->messages as $listid => $email)
{
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$_POST['attachmentPath']
);
$response->emails[$tempEmail['attachmentCode']] = $tempEmail;
}
$this->set('response', $response);
$this->set('_serialize','response');
}
}
and the client goes as:
class ApitestController extends AppController
{
Public function index()
{
$this->layout = 'ajax';
$jRequestURLPrefix = 'http://localhost/EWSApi/';
$postUrl = $jRequestURLPrefix."exchange/index.json";
$postData = array(
'username' => 'username',
'password' => 'password',
'attachmentPath'=> $_SERVER['DOCUMENT_ROOT'] . $this->base . DIRECTORY_SEPARATOR . 'emailDownloads' . DIRECTORY_SEPARATOR . 'attachments'
);
$postData = json_encode($postData);
pr($postData);
$ch = curl_init( $postUrl );
$options = array(
CURLOPT_RETURNTRANSFER=> true,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Content-Length: ' . strlen($postData)
),
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_POSTFIELDS => $postData,
);
curl_setopt_array( $ch, $options );
$jsonString = curl_exec($ch);
curl_close($ch);
$data = json_decode($jsonString, FALSE);
echo $jsonString;
}
}
Not sure where i am messing up! Please help!
Ok, after a second look there are some more suspicious things. As already mentioned, your CURL request uses GET instead of POST.
$options = array(
...
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $postData,
);
Another thing is that you are encoding the POST data for your CURL call to JSON, but then you are trying to access it on the other side using $_POST, however there won't be anything, POST data would have to be key/value query string formatted in order to appear in $_POST. You have to read php://input instead, which may be what you were trying to do with
$data = $this->request->data('json_decode');
However you must use CakeRequest::input() for that purpose, and of course you must then use the $data variable instead of $_POST
$data = $this->request->input('json_decode');
$exchange->username = $data['username'];
$exchange->password = $data['password'];
....
$tempEmail = $exchange->getEmailContent(
$email->Id,
$email->ChangeKey,
TRUE,
$data['attachmentPath']
);
Also make double sure that your CURL request looks like expected:
$options = array(
...
CURLOPT_POSTFIELDS => $postData,
CURLINFO_HEADER_OUT => true // supported as of PHP 5.1.3
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
echo '<pre>';
print_r($info);
echo '</pre>';

Categories