Authenticating Cookies with PHP and Curl - php

I am writing code against the Space-Track API, and the curl request is failing to authenticate. My code is as follows:
$curl = curl_init();
$url = "https://www.space-track.org/basicspacedata/query/class/tle/EPOCH/%3C1969-12-18/NORAD_CAT_ID/4/orderby/EPOCH%20desc/limit/1/format/3le/metadata/true";
$c = curl_init('https://www.space-track.org/auth/login?identity=XXX&password="XXX"');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_COOKIEJAR, 'cookies.txt');
$page = curl_exec($c);
curl_close($c);
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_COOKIEFILE, 'cookies.txt');
$page = curl_exec($c);
curl_close($c);
echo $page;
The response received is: "You must be logged in to complete this action"
The authentication is apparently successful, however, as the cookies.txt file is filled with an authentication message.
I have read a number of tutorials on curl authentication, and I have also tried other users' implementations of the space-track API in php (eg) but have not managed to make these work with my request:
https://www.space-track.org/basicspacedata/query/class/tle/EPOCH/%3C1969-12-18/NORAD_CAT_ID/4/orderby/EPOCH%20desc/limit/1/format/3le/metadata/true
The request works in the browser (direct access) when authenticated and via terminal, but not when run in the script. Direct browser access returns this correct response:
0 EXPLORER 1
1 00004U 58001 A 69351.29911760 .00162519 +00000-0 +00000-0 0 9991
2 00004 033.1571 316.5155 0244636 013.0841 347.6023 15.32472396567852
Any assistance in correctly authenticating and receiving this response via PHP gratefully received.

Related

Arzoo Bus booking API integration using PHP Curl and XML

I'm working on Bus API of arzoo. The server must receive the posted data in simple POST Request. To achieve this i'm using PHP cURL. In the API Document it is clearly mention that the data should be sent in the following format:
<BusRequest>
<source>HYDERABAD</source>
<dest>BANGALORE</dest>
<dep_date>25-Mar-2016</dep_date>
<PartnerId>ID of the partner given by arzoo</PartnerId>
<Clientid>ID of the client given by arzoo</Clientid>
<Clientpassword>Client password given by arzoo</Clientpassword>
<Clienttype>ArzooBUSWS1.0</Clienttype>
</BusRequest>
My PHP cURL code is as follows:
$input_xml = '<BusRequest>
<source>Ernakulam</source>
<dest>Kozhikode</dest>
<dep_date>15-Nov-2017</dep_date>
<PartnerId>partner</PartnerId>
<Clientid>clientid</Clientid>
<Clientpassword>password</Clientpassword>
<Clienttype>clienttype</Clienttype>
</BusRequest>';
$url = "url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
I'm not getting any valid xml as response.Am i doing anything wrong ?. Your reply will be appreciated. Thank You.

Unable to get images from Instagram by using the provided PHP API

I am trying to the Instagram PHP API to get friends photos. I registered as a sandbox user as well as a dummy user with few random images posted.Then, I invited the dummy user to grant the app in sandbox to connect his account.
To get access token I send a request to get code and then get access token with scope:
https://api.instagram.com/oauth/access_token?client_id=CLIENT_ID&client_secret=SECRET_STRING&grant_type=authorization_code&redirect_uri=http://localhost/&code=CODE&scope=basic+public_content+comments+likes`
PHP code:
$url = 'https://api.instagram.com/oauth/access_token';
$payload = [
$GLOBALS['KEY_CID'] => $GLOBALS['VAL_CID'],
$GLOBALS['KEY_CECRET'] => $GLOBALS['VAL_CECRET'],
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/',
'code' => $param_code,
'scope' => 'basic+public_content+comments+likes'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // url
curl_setopt($ch, CURLOPT_POST, true); // POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); // POST DATA
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN RESULT true
curl_setopt($ch, CURLOPT_HEADER, 0); // RETURN HEADER false
curl_setopt($ch, CURLOPT_NOBODY, 0); // NO RETURN BODY false / we need the body to return
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // VERIFY SSL HOST false
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VERIFY SSL PEER false
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
After I got access token successfully.
I try to get images from a sandbox user which is a dummy account I created for testing:
https://api.instagram.com/v1/users/fane.leee/media/recent?access_token=ACCESS_TOKEN
PHP code for retrieving image:
$url = 'https://api.instagram.com/v1/users/fane.leee/media/recent?access_token='.$ACCESS_TOKEN;
$ch = curl_init(); // initializing
curl_setopt( $ch, CURLOPT_URL, $url ); // API URL to connect
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
$response = json_decode(curl_exec($ch), true); // connect and get json data
curl_close($ch);
The problem
The $response of the get image request is NULL without error message. Anyone got any ideas about the problem?
Thanks.
Reference
Instagram development doc authentication and authorization.
Instagram development doc about user endpoints
Another StackOverflow post about Instagram web API
Development environment:
Ubuntu 16.04
Apache2
PHP 7.0.8
MySQL 14.14
Edit 1: Add the PHP code calling cUrl functions.
Edit 2: If I replace the user id 'fane.leee' by using 'self', I am able to retrieve the images I posted. I also followed the user 'fane.leee'. Any else I should do to retrieve the friends' media?
The fane.leee is a username. Instagram requires a user id in the API caller.
To get a user id by calling a instagram API function, we could use
https://www.instagram.com/{username}/?__a=1
Another way to get the user id is to use a 3rd party website. It is able to retrieve an Instagram user id from a username. It is here
Reference:
An answer from Thinh Vu in this thread - Not the accepted answer, but the answer underneath. P.S the accepted answer is not working anymore.

php+curl to send a post request with fields

trying to send post request to api, to get an image back.
example url:
https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php?user=1003123&format=png&cloudid=asdasdasd&pass=123123123
the above url works fine in the browser,
the api doesnt care if the request is get/post,
result of my code is always 'invalid input'.
code:
$url='https://providers.cloudsoftphone.com/lib/prettyqr/createQR.php';
$u = rand();
$p = rand();
$fields = array(
'user'=> urlencode($u),
'pass'=> urlencode($p),
'format'=> urlencode('jpg'),
'cloudid' => urlencode('test')
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
on a side note: is there a way to debug the request in order to see what is being sent ?
The URL provided isn't working for POST request. Here is resulting screenshot (I tried using Advance Rest Client)
However Its working perfectly with GET method. So you can continue using GET request method to generate QR code.
I agree that GET isn't much secure compare to POST method but in your case while requesting from curl user won't get to know about such URL parameters (userid, password). Because curl request will be sending from your web server and not from client/user's browser.
Later you can just output the response image you got from the api.

How can I get a live data from API with cURL save or stream that data with another script?

I have a hardware which records data in every seconds. I can connect to the hardware with a browser and use the hardware’s interface and get the live data. For example: I can call the realtime data with command like this:
http://192.168.100.120:2345/realtime
That’s what I can see in the browser:
DM_NumLogChans=5
DM_NumDataModes=1
DM_LogicalChan=1
DM_ChanType=SEQUENTIAL
DM_NumDims=2
DM_DataMode=1
DM_DataModeType=TIMHIS
DM_AxisLabel.Dim1=Time
DM_AxisLabel.Dim2=Value
DM_AxisUnits.Dim1=secs
DM_AxisUnits.Dim2=microstrain
DM_SampleRate=1.000000
DM_TimeBase=0.0
DM_ChanName=bridge_1
DM_UserMin=-583.220764
DM_UserMax=940.916199
DM_Start=
-439.779 -391.875 -680.114 1001.37 0
-442.068 -396.62 -680.945 1001.37 0
-443.571 -399.705 -680.639 1001.37 0
-445.598 -404.848 -684.662 1001.37 0
A new row appear in each seconds. I would like to get this data and save it to a file or display it in real time in my php program. How can I catch the data? I tried with cURL. I think that is the solution but I am really new to this. I would appreciate any help or advice you could give me.
Try this code with your url
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
echo curl_download("192.168.100.120:2345/realtime");

PHP-cURL --> follow a ruby redirection

I am using trying to extract the wiki documentation from a page on my website (redmine). I successfully retrieved the redirect to the login page, send post username and password field, but then I arrive on a page with a ruby redirect from redmine and I can't go further. The ruby code in the file "response.rb" of redmine is:
def redirect(url, status)
self.status = status
self.location = url.gsub(/[\r\n]/, '')
self.body = "<html><body>You are being redirected.</body></html>"
end
I don't kbow enough about ruby to modify redmine's code, so is there a way to do this in php?
curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true);
Would tell cURL to follow any properly configured redirects (anything that sends the Location: header).
Found an alternate solution!
IF anybody else has that problem with redmine or any other redirect:
Use cURL to login first
Save your session to a cookie
Use cURL to get your secured page that needs authentification.
<?php
$tempFilename = tempnam("/tmp", "COOKIE");
// Login
$curlHandle = curl_init("http://bob.com/login");
curl_setopt($curlHandle, CURLOPT_COOKIEJAR, $tempFilename);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$dataArray = array(
"username" => "bob",
"password" => "password"
);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $dataArray);
$output = curl_exec($curlHandle);
// Getting the wiki
$curlHandle = curl_init("http://bob.com/wiki");
curl_setopt($curlHandle, CURLOPT_COOKIEFILE, $tempFilename);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curlHandle);
echo $output;
?>

Categories