I have never used cURL before and I think I have hit a roadblock in my learning. I am trying to make a HTTP GET request to my Wowza server which uses the Rest API to return JSON results. The URL actually returns it in XML but Wowza support says it I can get the response in JSON by adding the content type as I have done.
$url = 'http://DOMAINNAME:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/instances/_definst_/incomingstreams/ncopeland';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=utf-8',
'Accept: application/json'
));
$result = curl_exec($cURL);
$result = json_decode($result,true);
curl_close($cURL);
The response should be this.
{
"serverName": "_defaultServer_",
"sourceIp": "ncopeland",
"isPTZEnabled": false,
"applicationInstance": "_definst_",
"name": "ncopeland",
"isRecordingSet": false,
"isStreamManagerStream": true,
"isPublishedToVOD": false,
"isConnected": true,
"ptzPollingInterval": 2000
}
But, instead the response is being returned and formatted like this.
{"serverName":"_defaultServer_","sourceIp":"ncopeland","isPTZEnabled":false,"applicationInstance":"_definst_","name":"ncopeland","isRecordingSet":false,"isStreamManagerStream":true,"isPublishedToVOD":false,"isConnected":false,"ptzPollingInterval":2000}
How can I format this so I can get these into usable variables. Really all I am needing from the response is "name" and "isConnected" so I can updated fields in a DB. Really all I am needing from the response is "name" and "isConnected" so I can updated fields in a DB like this.
Array (
[serverName] => _defaultServer_
[sourceIp] => ncopeland
[isPTZEnabled] => false
[applicationInstance] => _definst_
[name] => ncopeland
[isRecordingSet] => false
[isStreamManagerStream] => true
[isPublishedToVOD] => false
[isConnected] => false
[ptzPollingInterval] => false
)
So I can work with $obj variable as an array like so.
echo $obj['name'];
echo $obj['isConnected'];
I'm not sure what are you missing, everything should be working as intended from your code. The fact, that json returns data without newline, doesn't change how data will be used later.
$jsondata = '{"serverName":"_defaultServer_","sourceIp":"ncopeland","isPTZEnabled":false,"applicationInstance":"_definst_","name":"ncopeland","isRecordingSet":false,"isStreamManagerStream":true,"isPublishedToVOD":false,"isConnected":false,"ptzPollingInterval":2000}';
$result = json_decode($jsondata,true); //is array
var_dump ($result['serverName']);
var_dump ($result['isConnected']);
Besides that, keep in mind, that you cannot echo boolean values.
BTW, using objects is even simpler than arrays in my opinion.
$jsondata = '{"serverName":"_defaultServer_","sourceIp":"ncopeland","isPTZEnabled":false,"applicationInstance":"_definst_","name":"ncopeland","isRecordingSet":false,"isStreamManagerStream":true,"isPublishedToVOD":false,"isConnected":false,"ptzPollingInterval":2000}';
$result = json_decode($jsondata);
var_dump ($result->serverName);
var_dump ($result->isConnected);
There was nothing wrong with my code after all. Come to find out on my hosted server solution the package I was using from Bluehost blocked the ports I was needing to make the http request via cURL. I was able to upgrade to a dedicated IP to get the ports I was needing open so it would work and has been working great since.
Related
there's the following ETH JSONRPC implementation to transfer tokens, which can be utilised via curl in PHP and I would like to do EXACTLY the same but on the Solana Blockchain - which supports it's own JSONRPC implementation
var whatever= {};
whatever.jsonrpc="2.0";
whatever.id=1;
whatever.method="eth_sendTransaction";
whatever.params= [];
whatever.params[0].from="0x52f273a06a420453aa5b33c4f175395c9a1fddd8";
whatever.params[0].to=data.ethAddress;
whatever.params[0].value=1e18;
whatever.params[0].currency="xxx";
source on stack overflow for the above code is here
as the Solana Documentation mentions only sendTrasactions here are my two questions:
how to implement the above example using Solana (see below our curl implementation of the Solana JSONRPC to get a user's current token amount in php i.e. "getTokenAmount")
where do I get the fully-signed Transaction as an encoded string which is a parameter for the "sendTransaction"*
*I assume the fully-signed Transaction is issued once the transfer is made, no?
----- example of our implementation as mentioned above (for those who might be interested in it -----
public function getTokenAmount($wallet_address, $token_address)
{
$data = array(
"jsonrpc" => "2.0",
"id" => 1,
"method" => "getTokenAccountsByOwner",
"params" => array(
0 => $wallet_address,
1 => array(
"mint" => $token_address
),
2 => array(
"encoding" => "jsonParsed"
)
)
);
$data = json_encode($customer);
$response = $this->initCurl($data);
return $response->result->value[0]->account->data->parsed->info->tokenAmount->uiAmount;
}
private function initCurl($data)
{
$ch = #curl_init();
#curl_setopt($ch, CURLOPT_POST, true);
#curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
#curl_setopt($ch, CURLOPT_URL, $this->_endpoint);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
#curl_setopt($ch, CURLOPT_HTTPHEADER, array( "accept: application/json", "content-type: application/json"));
$response = json_decode(#curl_exec($ch));
$err = #curl_error($ch);
curl_close($ch);
// TODO: ERROR HANDLING
if ($err) {
return false; //"cURL Error #:" . $err;
}
return $response;
}
The answers to 1 and 2 are very similar.
In order to send a transaction, you must create a base64 or base58 encoded string with all of the transaction data, which includes accounts, data, and any other flags needed. After that, you must sign the transaction with a ed25519 key, and provide that whole string as the transaction.
You can build this yourself by following how it's done for JS:
system instruction, specifically transfer: https://github.com/solana-labs/solana/blob/005592998dd107b3d54d9203babe24da681834f5/web3.js/src/system-program.ts#L676
transaction, specifically adding instructions, compiling the message, and signing: https://github.com/solana-labs/solana/blob/005592998dd107b3d54d9203babe24da681834f5/web3.js/src/transaction.ts#L205
Your better bet, however, would be to reuse an existing library which has already done a lot of this work for you. For example, https://github.com/tighten/solana-php-sdk#transactions provides an easy API to do exactly what you're looking for.
I am working with an API that is documented here: https://cutt.ly/BygHsPV
The documentation is a bit thin, but I am trying to understand it the best I can. There will not be a developer from the creator of the API available before the middle of next week, and I was hoping to get stuff done before that.
Basically what I am trying to do is update the consent of the customer. As far as I can understand from the documentation under API -> Customer I need to send info through PUT to /customers/{customerId}. That object has an array called "communicationChoices".
Going into Objects -> CustomerUpdate I find "communicationChoices" which is specified as "Type: list of CommunicationChoiceRequest". That object looks like this:
{
"choice": true,
"typeCode": ""
}
Doing my best do understand this, I have made this function:
function update_customer_consent() {
global $userPhone, $username, $password;
// Use phone number to get correct user
$url = 'https://apiurlredacted.com/api/v1/customers/' . $userPhone .'?customeridtype=MOBILE';
// Initiate cURL.
$ch = curl_init( $url );
// Specify the username and password using the CURLOPT_USERPWD option.
curl_setopt( $ch, CURLOPT_USERPWD, $username . ":" . $password );
// Tell cURL to return the output as a string instead
// of dumping it to the browser.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// Data to send
$data = [
"communicationChoices" => [
"communicationChoiceRequest" => [
"choice" => true,
"typeCode" => "SMS"
]
]
];
$json_payload = json_encode($data);
print_r($json_payload);
// Set other options
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($json_payload)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);
// Execute the cURL request
$response = curl_exec($ch);
// Check for errors.
if( curl_errno( $ch ) ) :
// If an error occured, throw an Exception.
throw new Exception( curl_error( $ch ) );
endif;
if (!$response)
{
return false;
} else {
// Decode JSON
$obj = json_decode( $response );
}
print_r($response);
}
I understand that this is very hard to debug without knowing what is going on within the API and with limited documentation, but I figured asking here was worth a shot anyway.
Basically, $json_payload seems to be a perfectly fine JSON object. The response from the API however, is an error code that means unknown error. So I must be doing something wrong. Maybe someone has more experience with APIs and such documentation and can see what I should really be sending and how.
Any help or guidance will be highly appreciated!
before you test your code, you can use the form provided on the API Documentation.
when you navigate to API > Customers > /customers/{customerId} (GET), you will see a form on the right side of the page (scroll up). you need to provide the required values on the form then hit Submit button. you will surely get a valid data for communicationChoices based on the result from the Response Text section below the Submit button.
now, follow the data structure of communicationChoices object that you get from the result and try the same on API > Customers > /customers/{customerId} (PUT) form.
using the API forms, you may be able to instantly see a success or error from your input (data structure), then translate it to your code.
I'm trying to create a relatively simple PHP endpoint for users to send requests to. I know that the endpoint is working because when I accessed it using cURL the parameters I sent to my database we're added. The problem however is that when I use
var_dump($response);
The page returns "NULL".
So the code is working fine, I just want to know how to print an error/success message
This is what I've tried so far on the endpoint
header("HTTP/1.1 200 OK");
header('Content-Type: text/plain');
echo 'Success message';
the full cURL code:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
);
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = json_decode($resp, true);
var_dump($response);
So how can I get the success message to properly show instead of "NULL"?
Test if your curl code returns something by testing: var_dump($resp). It looks like NULL comes from json_decode. You are not returning valid JSON from the endpoint.
php > var_dump(json_decode("Success message", true));
NULL
Try returning a json string such as:
php > echo json_encode("Success", true);
"Success"
Note the " around it. This encodes a json string. See the JSON spec for a reference on how to encode json. Best practice, if your return json, then run your content through json_encode().
Your curl code seems correct.
Not sure if anyone can help me out with a question.
I had to write some php for the company I work for that lets us integrate with an API that accepts a JSON body. I used the cUrl method, and the script is working great.
If I wanted to build another php page that would accept the request im sending, how would I go about this?
Say I wanted to allow someone to send this same request to me, and then wanted the info they sent to go into my database, how would turn their request into php strings?
Here is the code im sending.
<?
$json_string = json_encode(array("FirstName" => $name, "MiddleName" => " ", "LastName" => $last));;
// echo $json_string;
// jSON URL which should be requested
$json_url = 'http://www.exampleurl.com';
// jSON String for request
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Accept: application/json;charset=utf-8',
'Content-Type: application/json;charset=utf-8',
'Expect: 100-continue',
'Connection: Keep-Alive') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
echo $result;
$myArray = json_decode($result);
$action = $myArray->Action;
?>
To get the raw data from the POST that you would be receiving you would use $postData = file_get_contents('php://input');
http://php.net/manual/en/reserved.variables.post.php
Then you would json_decode() the contents of that POST back into JSON.
http://php.net/manual/en/function.json-decode.php
Not really good understood your question. May be you are looking for the way to read raw POST data? In that case open and read from php://stdin stream.
$stdin = fopen('php://stdin', 'r');
By the way read here ( http://php.net/manual/en/function.curl-setopt.php ) how to use CURLOPT_POSTFIELDS. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value.
I am trying to figure out how I would go about caching the data I am pulling from a webservce json file onto my page so that I do not continually request this data and bring down the server.
I currently am pullin the json data like so:
// jSON URL which should be requested
$json_url = 'http://example.com/datastore.json?toolbar_id='.$persona['toolbar_id'].'';
// jSON String for request
$json_string = '[Json string? What is this]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$result = json_decode($result, true);
$result = $result[0];
From here I can pull the associative array results as I need them. But If I were to refresh the page, it would recall the server info. Any solutions?
You'd treat it like any other cache file:
Check if the cache file exists
If it does, check the filemtime() against the current time()
If it needs to be refreshed, make the cURL call and write the data to the cache file and carry on
If it does not need to be refreshed, simply return the data from the file to to your variable.
It will be the same JSON regardless if PHP returns it via cURL or if PHP returns it via fread() on a cache file.