cURL PHP to Plain cURL - php

I'm trying to connect my Rails app to a third-party API. In their example code, the code to connect to their service is all in PHP. I'm not familiar with PHP.
This is the code:
<?php
// Token generation
$timestamp = time();
$uri = "https://api.website.com/post.json";
$password = "somePassword";
$security_token = sha1($timestamp.$uri.$password);
// Webservice call
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$post = array();
$post["timestamp"] = $timestamp;
$post["security_token"] = $security_token;
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_POST, true);
// USE THIS CODE TO CHECK THAT SSL CERTIFICATE IS VALID:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, "path/to/certifcate/file/certificate.crt");
$ret = curl_exec($ch);
// Check response
if(curl_errno($ch)) {
curl_close($ch);
die("CURL error: ".curl_error($ch));
}
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($http_code != 200) {
die("Server error, HTTP code: $http_code");
}
curl_close($ch);
// Parse response
try {
$json = json_decode($ret);
var_dump($json);
}
catch(Exception $e) {
die("Failed to decode server response");
}
?>
Any help to convert this to plain cURL would be appreciated and thanks in advance!

This is how I did it and it worked good.
uri = URI.parse("https://apilink/post.json")
pass = 'supper-password'
timestamp = Time.now
token = Digest::SHA1(timestamp + uri + pass)
request = Net::HTTP::Post.new(uri)
# request.body = "timestamp&security_token"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
render json: response.code

Related

My API request keeps using up 25 requests for no apparent reason

My request functions from PUBG official API
<?php
function getProfile($profile, $div){
$pubgapikey = 'xxxxxxxxxxxxx';
$id = getID($profile);
$url = "https://api.pubg.com/shards/pc-na/players/$id/seasons/$div";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
if($json["data"]["type"] == "playerSeason"){
return $json["data"]["attributes"];
}else {
return false;
}
}
function getID($name){
$pubgapikey = 'xxxxxxxxxxxxxxxxxxx';
$url = "https://api.pubg.com/shards/pc-na/players?filter[playerNames]=$name";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $pubgapikey, 'Accept: application/vnd.api+json'));
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
return $json["data"][0]["id"];
}
So That's my function for requesting the data. I'll include the ways I call this.
// My index.php file (All requests go through here)
$page = explode("/", trim($_SERVER["REQUEST_URI"], "/"));
switch($page[0]){
case "profile":
require("controllers/search_controller.php");
$data = getProfile($page[1], "division.bro.official.2018-09");
if($data != false){
include("pages/profile.php");
}else{
include("pages/home.php");
echo '<script> document.getElementById("error").innerHTML = "Cannot find user. Remember To Be Capital Sensitive!"; </script>';
}
break;
}
I know that I'm using a really dumb way to include pages and what not but I don't wanna use or build my own php framework atm and this works just fine for what I'm doing
// Here is my php for calling the function
<?php
if (isset($_POST['username'])) {
$user = $_POST['username'];
if($user != ""){
header("Location: http://www.statstreak.us/profile/$user");
die();
}
}
?>
That's pretty much it. The form is just a basic html form.
For some reason this keeps using up my 25 requests/minute that I got from PUBG which is annoying as I can't find a reason why it would use up more than 2 requests per user

curl function return Protocol http not supported or disabled in libcurl

im facing here a problem with this function :
function curl_function($uri)
{
$ch = curl_init($uri);
$timeout = 30; //set to zero for no timeout
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERAGENT, 'mycoreg');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$file_contents = curl_exec($ch);
$errornum = curl_errno($ch);
$info = curl_getinfo($ch);
$status = (int) $info['http_code'];
if ($errornum !== 0) {
echo 'Error: ', curl_error($ch);
$file_contents = NULL;
}
curl_close($ch);
return $file_contents;
}
It gives the error that
"http protocol is not supported or disabled".
plz need help.
thanks.
Debug print your URL and ensure it contains no extraneous characters.
In my case, the URL I was using with php curl was quoted. The quote is not printed by curl error handling, so the error is rather confusing and hard to track down.
You can generate this error with the following code:
// wrong
$uri = "'". "http://www.google.com/" . "'"; // quoted string
curl_setopt($ch, CURLOPT_URL, $url);
Now try it with the proper URL format...
// right
$uri = "http://www.google.com/"; // correct format URL
curl_setopt($ch, CURLOPT_URL, $url);
Update your function like this to avoid a strange errors :)
function curl_function($uri) {
$uri = trim($uri);
// ... your code
}

twitter api update status updating but no response from twitter

having a bit of an issue with the twitter API. When I send something to https://api.twitter.com/1/statuses/update.json, the tweet (status update) does get sent, however, I do not get a response from twitter. When I send requests to any of the other api urls they work as expected and do return a response. Please see code below...
function postStatus($oauthToken,$status) {
//Create sig base string
$tokenddata = array('oauth_token'=>$oauthToken['oauth_token'],'oauth_token_secret'=>$oauthToken['oauth_token_secret']);
$status = rawurlencode($status);
$baseurl = $this->baseurl . "statuses/update.json";
$url = "{$baseurl}?status={$status}";
$authHeader = get_auth_header($url, $this->_consumer['key'], $this->_consumer['secret'],
$tokenddata, 'POST', $this->_consumer['algorithm']);
$postfields = "status={$status}";
$response = $this->_connect($url,$authHeader,$postfields,'POST');
return json_decode($response);
}
private function _connect($url, $auth, $postfields=null, $method='GET') {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($ch, CURLOPT_SSLVERSION,3);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth));
if ($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, TRUE);
if (!empty($postfields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
}
}
$curl_info = curl_getinfo($ch);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
And as I said before, the other requests that I am using are 'GET' requests and use the code below...
function getFromTwitter($url, $oauthToken, $params=null) {
$tokenddata = array('oauth_token'=>$oauthToken['oauth_token'],'oauth_token_secret'=>$oauthToken['oauth_token_secret']);
$baseurl = $this->baseurl . $url;
if(!empty($params)) {
$fullurl = $baseurl . "?" . build_http_query($params);
$postfields = build_http_query($params);
$authHeader = get_auth_header($fullurl, $this->_consumer['key'], $this->_consumer['secret'],
$tokenddata, 'GET', $this->_consumer['algorithm']);
} else {
$authHeader = get_auth_header($baseurl, $this->_consumer['key'], $this->_consumer['secret'],
$tokenddata, 'GET', $this->_consumer['algorithm']);
}
if(!empty($postfields)) {
$response = $this->_connect($fullurl,$authHeader);
} else {
$response = $this->_connect($baseurl,$authHeader);
}
return json_decode($response);
}
Thanks for all of the help!
-SM
Implementing code for social networks on your own can be a pain (in my opinion)
It would be easier for you to use twitter-async (https://github.com/jmathai/twitter-async)
I have added it before to my CI as a helper function then used it as is.
It was easy to use & well documented.

No response from XML using cURL

I am using a simple cURL statement to parse XML on my site. When the API is up and working it works fine, however as soon as the API does down for any reason the entire site crashes.
$url = 'http://www.mydomain.com/webservicexample';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$xml = new SimpleXmlElement($data);
Is there a conditional I can put around the url so that it only carries out the cURL script if there's a positive response from the API? I tried the following but it didn't work because it never got a server response to give any headers:
$url_headers = #get_headers($url);
if($url_headers[0] == 'HTTP/1.1 200 OK') {
// do script
}
Any help/advice much appreciated!
You can check the return value of curl_exec():
if (false === ($data = curl_exec($ch))) {
die("Eek! Curl error! " . curl_error($ch));
}
And check the response headers too:
if (200 !== (int)curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
die("Oh dear, no 200 OK?!");
}
In the end I was able to get it working by setting a timeout time with CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT and then put a conditional around it using curl_errno().
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
$data = curl_exec($ch);
if(!curl_errno($ch))
{
curl_close($ch);
$xml = new SimpleXmlElement($data);
return $xml;
}

how to use curl in php? [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
get the value of an url response with curl
I have an php page names stores.php now i want to see the output of this page using curl, what i can do ?
my code is so far for stores.php page
<?php
include_once '../application/Boot.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$body = #file_get_contents('php://input');
$json = json_decode($body, true);
if (isset($json['version'])) {
$client_cache_version = #$json['version'];
$sql = $db->quoteInto("SELECT * FROM stores where version_modified > ". $client_cache_version);
$results = $db->fetchAll($sql);
$version_sql = $db->quoteInto("SELECT max(version_modified) as version FROM stores");
$version_results = $db->fetchAll($version_sql);
$count = array(
'count' => sizeof($results)
);
array_push($results, $version_results['0']);
array_push($results, $count);
//ob_start("ob_gzhandler");
header('HTTP/1.1 200 Stores list');
echo json_encode($results);
exit;
}else {
header('HTTP/1.1 400 Bad Request');
exit;
}
}else{
header('HTTP/1.1 400 Bad Request');
exit;
}
?>
use man curl for how to use curl to display the response of a webpage.
example:
curl "http://www.stackoverflow.com"
function getPage($url, $referer, $agent, $header, $timeout, $proxy="")
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if($proxy != "")
{
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_REFERER, $referer);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_COOKIEJAR, realpath('cookies.txt'));
curl_setopt($ch, CURLOPT_COOKIEFILE, realpath('/cookies.txt'));
$result['EXE'] = curl_exec($ch);
$result['INF'] = curl_getinfo($ch);
$result['ERR'] = curl_error($ch);
curl_close($ch);
return $result;
}
$url = "www.targeturl.com";
$referer = "http;//www.google.com";
$agent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
$header = 1;
$timeout = 15;
$result = getPage($url, $referer, $agent, $header, $timeout);
//$result["ERR"] contain errors if any one
//$result['EXE'] have the html of traget url you supplied in $url variable
//$result['info] have information.
you can use it like this
if(empty($result["ERR"])) // no error
{
echo $result['EXE']; //html of target url
}
else // errors
{
// do something on errors
}
// $proxy is optional
// if you want to open target url through a proxy use it like this
$proxy = "120.232.23.23:8080";
$result = getPage($url, $referer, $agent, $header, $timeout,$proxy);

Categories