Reading values from cURL POST request - php

I am trying to make a POST request using cURL in PHP. I have the code to make the POST request (from index.php) and I believe it is correct.
The next part is the API layer (api.php) which needs to extract the data from the POST request and this is where I am having issues. In the code, I am trying to read the value of the parameter q that I have passed using index.php.
Here's the code for both the files.
index.php
<?php
$handle = curl_init();
curl_setopt_array(
$handle,
array(
CURLOPT_URL => 'http://localhost:8888/restAPI/api.php',
'q' => 'getCompanyId',
'post_fields' => 'q=getCompanyId',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => array(
'q' => 'getCompanyId'
),
CURLOPT_RETURNTRANSFER => true
)
);
$response = curl_exec($handle);
curl_close($handle);
?>
api.php
<?php
require_once("Rest.inc.php");
class API extends REST {
public function processApi() {
$func = $_REQUEST['q'];
if((int)method_exists($this,$func) > 0){
$this->$func();
}
else{
$this->response('',404);
// If the method not exist with in this class, response would be "Page not found".
}
}
public function getCompanyId(){
$dbhost = 'localhost:8888';
$conn = mysql_connect($dbhost, 'root', 'root');
if (! $conn) {
die('Could not connect - ' . mysql_error());
}
$sql = 'SELECT companyId FROM Companies';
mysql_select_db('IRSocialBackend');
$executeSql = mysql_query($sql);
while($data = mysql_fetch_array($executeSql)){
echo $data['companyId'];
}
}
}
//echo "here";
$api = new API;
$api -> processApi();
?>

Just a side note: your API is not RESTFUL. REST is not a matter of "making HTTP requests". Read up on it!
First mistake:
array(
CURLOPT_URL => 'http://localhost:8888/restAPI/api.php',
'q' => 'getCompanyId',
'post_fields' => 'q=getCompanyId',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => array(
'q' => 'getCompanyId'
),
CURLOPT_RETURNTRANSFER => true
)
Random "q" and "post_fields" is definitely not how you add fields to curlopt.
In api.php, you assign the following:
$dbhost = 'localhost:8888';
$conn = mysql_connect($dbhost, 'root', 'root');
I thought localhost:8888 was your webserver? localhost:3306 would be your MySQL server if it is on a default port.
The rest is hard to debug without knowing your table/DB structure.

Related

Why does execution stop at wordpress_remote_post() function call?

I am trying to write an SSO plugin for my WordPress multisite and MemberSuite. I'm in the beginning steps, just trying to have the user sign in and get the MemberSuite sign-in token.
Here's the code I have so far:
define("MS_API_URL", "http://rest.membersuite.com/swagger/platform/v2/");
define("TENANT_ID", "00000");
define("USER_POOL", "placeholder");
define("CLIENT_ID", "placeholder");
function send_request() {
$username = $_POST[portalusername];
$password = $_POST[portalpassword];
return ms_sign_in($username, $password, USER_POOL, CLIENT_ID);
}
function ms_sign_in($un, $pw, $up, $cid) {
$url = MS_API_URL . 'storeJWTTokenForUser/' . TENANT_ID;
$data = array(
'username' => $un,
'password' => $pw,
'userPool' => $up,
'clientID' => $cid
);
$arguments = array(
'method' => 'POST',
'headers' => array(
'Content-Type' => 'application/json',
'Accept' => 'application/json'
),
'body' => json_encode($data)
);
echo "before post";
$response = wp_remote_post($url, $arguments);
echo "after post";
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
}
echo $response;
echo $response['body'];
return $response['body'];
}
?>
<html>
<body>
<p>body 1</p>
<?php echo send_request();?>
<p>body 2</p>
</body>
</html>
My form calls the send_request() function. As far as I can tell, I've implemented everything the way the MemberSuite documentation indicates it should be implemented. I've included all the necessary values for verification.
However, it appears execution just stops when I reach the line that says $response = wp_remote_post($url, $arguments);. The output displays:
body 1
before post
but nothing else. I'd like to know why this happening, if there is any way to fix it, and/or if there is a different way I should go about making the POST request.

How to send a message to specific connectionId to aws api gateway websockets?

I am using this code to establish a new connection on user device.
var socket = new WebSocket("wss://cdsbxtx2xi.execute-api.us-east-2.amazonaws.com/test");
socket.onmessage = function (event) {
json = JSON.parse(event.data);
connectionId = json.connectionId;
document.cookie = "connection_id="+connectionId;
console.info(json);
}
Suppose from this request I get connectionId CLO5bFP1CYcFSbw=
Another user from another device also established a new connection with connectionId Cs42Fs5s5yuSbc=. Now how can I send a message from user 2 device to user 1?
I already tried this. I don't know this is right way or not but still, i am open for any suggestion.
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Credentials\Credentials;
$client = new GuzzleHttp\Client();
$credentials = new Credentials("XXXXXXXXXX","XXXXXXXX");
$url = "https://cdsbxtx2xi.execute-api.us-east-2.amazonaws.com/test/#connections/CLO5bFP1CYcFSbw=";
$region = 'us-east-2';
$msg['action'] = 'sendmessage';
$msg['data'] = 'hello world';
$msg = json_encode($msg);
$request = new Request('POST', $url, '["json"=>$msg]');
$s4 = new SignatureV4("execute-api", $region);
$signedrequest = $s4->signRequest($request, $credentials);
$response = $client->send($signedrequest);
echo $response->getBody();
This code keeps on loading and finally throws gateway timeout error.
I expect that user 2 should be able to send message to any specific connectionId over wss or https.
I tried https by signing this request but signing doesn't works. I am getting an error with the signing part
After struggling with this problem for the last 3 days finally I found the solution. None of the previously mentioned solutions on StackOverflow was working for me.
This is the correct solution. I hope this will be helpful to someone.
use Aws\Signature\SignatureV4;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Aws\Credentials\Credentials;
$client = new GuzzleHttp\Client();
$credentials = new Credentials(accessKeyId, secretAccessKey);
$url = "https://xsdsdsd.execute-api.us-east-2.amazonaws.com/test/#connections/CNtBveH2iYcCKrA=";
// CNtBveH2iYcCKrA= is connectionid
$region = 'us-east-2';
$msg['action'] = 'sendmessage';
$msg['data'] = 'hello world';
$msg = json_encode($msg);
$headers = array('Content-Type => application/x-www-form-urlencoded');
$request = new GuzzleHttp\Psr7\Request('POST', $url, ['Content-Type' => 'application/json'], $msg);
$signer = new Aws\Signature\SignatureV4('execute-api', $region);
$request = $signer->signRequest($request, $credentials);
$headers = array('Content-Type => application/x-www-form-urlencoded');
$client = new \GuzzleHttp\Client([ 'headers' => $headers]);
$response = $client->send($request);
$result = $response->getBody();
Hey you can use the Connection URL to send message also.
Connection url : https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections
To find go to : Aws console > Api gateway > api > your_api > dashboard their you will find your connection url.
Use php cURL method because its easy and fast as compare to GuzzleHttp
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/#connections/{YOUR_CONNECTION_ID_OF_USER}',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{"message" : "Hello world"}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Web service for retrieving records using php xml-rpc protocol

I am trying to implement a web service using PHP. I am following xml-rpc protocol.
I am trying to call a function through index file and display records from the database but when i try to call the function in file server2 nothing is printed on the screen just a blank white screen is showed up here is my code so far.
Kindly help me out with this I have spent hours searching about this but cannot find any help
server2.php
<?php
$request_xml = file_get_contents("php://input");
function say_hello($method_name, $args) {
$dbLink = mysqli_connect('localhost','root','saad','enstructo');
if (!$dbLink) {
echo "ERROR";
}
$query = "SELECT * FROM Admin";
if ($result = mysqli_query($dbLink,$query)) {
while($getquery = mysql_fetch_array($result)){
$returnquery[] =array($result['username'],$result['email']) ;
}
}
return $returnquery;
}
$xmlrpc_server = xmlrpc_server_create();
xmlrpc_server_register_method($xmlrpc_server, "say_hello", "say_hello");
header('Content-Type: text/xml');
print xmlrpc_server_call_method($xmlrpc_server, $request_xml, array());
?>
index.php
<?php
$request = xmlrpc_encode_request("say_hello", array('10'));
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml\r\nUser-Agent: PHPRPC/1.0\r\n",
'content' => $request
)));
$server = 'http://localhost/rpc/basic/server2.php';
$file = file_get_contents($server, false, $context);
$response = xmlrpc_decode($file);
echo $response;
?>

Cannot receive any SMS messages when I register/ inquire via SMS Globe Labs API

I am developing an SMS Based Registration System and so far I'm at the stage of testing my system. All of a sudden, I was not able to receive any messages from my server when I tried to register via SMS it must receive a confirmation messages. Here's what i did when using PHP nusoap.
Register.php
<?php
// This will allow user to register via SMS.
error_reporting( E_ALL );
// load the nusoap libraries. These are slower than those built in PHP5 but
require_once('nusoap.php');
// create the client and define the URL endpoint
$soapclient = new nusoap_client('http://www.mnccyf.info/soap_book.php?wsdl');
// set the character encoding, utf-8 is the standard.
$soapclient->soap_defencoding = 'UTF-8';
$soapclient->call('sendSMS', array( 'uName' => '48dwi5',
'uPin' => '159597',
'MSISDN' => '09152886810',
'messageString' => 'Registered Successfully',
'Display' => '1',
'udh' => '',
'mwi' => '',
'coding' => '0' ),
"http://ESCPlatform/xsd");
?>
Inquiry.php
<?php
// This will allow user to inquire about the latest news within the organization.
error_reporting( E_ALL );
// load the nusoap libraries. These are slower than those built in PHP5 but
require_once('nusoap.php');
$soapclient = new nusoap_client('http://www.mnccyf.info/soapquery_server.php?wsdl');
// set the character encoding, utf-8 is the standard.
$soapclient->soap_defencoding = 'UTF-8';
// Call the SOAP method, note the definition of the xmlnamespace as the third in the call and how the posted message is added to the message string
$soapclient->call('sendSMS', array( 'uName' => '48dwi5',
'uPin' => '159597',
'MSISDN' => '09152886810',
'messageString' => 'Summer Camp 2013',
'Display' => '1',
'udh' => '',
'mwi' => '',
'coding' => '0' ),
"http://ESCPlatform/xsd");
?>
incoming_sms.php
<?php
require_once('nusoap.php');
function sendSMS($number,$soapclient)
{
$x=sendSMS("09152886810",$soapclient);
}
# Load XML string from input
$xml = simplexml_load_file('php://input');
# Parse the XML for parameters
$sms = array();
$nodes = $xml->xpath('/message/param');
foreach($nodes as $node)
{
$param = (array) $node;
$sms[$param['name']] = $param['value'];
}
if($sms['messageType'] == 'SMS-NOTIFICATION') {
sendSMS();
list($action, $messagetype, $source, $type) =explode (" ",$soapclient);
}elseif($sms['messageType'] == 'SMS') {
sendSMS();
list($action, $name, $age, $localchurch, $district) = explode(" ",$soapclient);
}elseif($sms['messageType'] == 'SMS') {
sendSMS();
list($action, $event,$location,$time) = explode(" ", $soapclient);
}
else {
echo "Unsupported Message Type";
}
?>
register_soapserver.php
<?php
//call library
require_once ('nusoap.php');
//using soap_server to create server object
$server = new nusoap_server;
$server ->configureWSDL('http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform?
wsdl','urn:http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform?wsdl');
//register a function that works on server
$server->register('reg');
// create the function
function reg()
{
$connect = mysql_connect("localhost","root","jya0312#");
if (!$connect)
{
die("Couldnt connect" . mysql_error());
}
mysql_select_db("cyfdb", $connect);
$sql = "INSERT INTO mydb(name, age,localchurch,district) VALUES ('{$_POST [name]}','{$_POST[age]}','{$_POST[localchurch]}','{$_POST[district]}')";
mysql_close($connect);
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>
soapquery_server.php
<?php
//call libraryrequire_once ('nusoap.php');
//using soap_server to create server object
$server = new nusoap_server;
$server ->configureWSDL('http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform? wsdl','urn:http://iplaypen.globelabs.com.ph:1881/axis2/services/Platform? wsdl');
//register a function that works on server
$server->register('getquery');
// create the function
function getquery()
{
$link=mysql_connect("localhost", "root", "jya0312#") or die("Cannot connect to DB!");
mysql_select_db("cyfdb") or die("Cannot select DB!");
$sql = "SELECT event,location,time from activity";
while($r = mysql_fetch_array($sql)){
$items[] = array('event'=>$r['event'],
'location'=>$r['location'],
'date'=>$r['date']);
}
return $items;
$mysql_close($link);
}
// create HTTP listener
$server->service($HTTP_RAW_POST_DATA);
exit();
?>

Update twitter profile image using OAuth

I'm trying to get twitter update_profile_image to work using OAuth. I was using curl with regular authentication and everything was working fine, but I switched to OAuth using this library, and now everything except update_profile_image works.
I read something about twitter OAuth having problems with multipart data, but that was a while ago and the plugin is supposed to have dealt with that issue.
My working regular authentication with curl code
$url = 'http://api.twitter.com/1/account/update_profile_image.xml';
$uname = $_POST['username'];
$pword = $_POST['password'];
$img_path = 'xxx';
$userpwd = $uname . ':' . $pword;
$img_post = array('image' => '#' . $img_path . ';type=image/jpeg',
'tile' => 'true');
$format = 'xml'; //alternative: json
$message = 'Test update with a random num'.rand();
$opts = array(CURLOPT_URL => $url,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $img_post,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_USERPWD => $userpwd,
CURLOPT_HTTPHEADER => array('Expect:'),
CURLINFO_HEADER_OUT => true);
$ch = curl_init();
curl_setopt_array($ch, $opts);
$response = curl_exec($ch);
$err = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
My current OAuth code [I had to cut it down, so do not minor look for syntax errors]
include 'EpiCurl.php';
include 'EpiOAuth.php';
include 'EpiTwitter.php';
include 'secret.php';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($_GET['oauth_token']);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
try{
$img_path = 'xxx';
//$twitterObj->post_accountUpdate_profile_image(array('#image' => "#".$img_path));
$twitterObj->post('/account/update_profile_image.json', array('#image' => "#".$img_path));
$twitterObj->post_statusesUpdate(array('status' => 'This is my new status:'.rand())); //This works
$twitterInfo= $twitterObj->get_accountVerify_credentials();
echo $twitterInfo->responseText;
}catch(Exception $e){
echo $e->getMessage();
}
I've been trying to figure this out for a while, ANY help would be greatly appreciated. I'm not in any way tied to this library, so feel free to recommend others.
The version of the library I was using was outdated. Once I updated, I had to deal with a couple of other issues including 401 error due to a wrong server time, and now everything works fine. Printing out the $response->responseText helps a lot.

Categories