I am using a remote login feature in my website for logging into an onapp server from my site.. This will actually fetch the form using CURL and submitting it with user name and password. It is working fine. Now my site has got different services for a single user and so there is multiple accounts in the onapp server. So I need a method to check if there is a session is existing in the onapp server(if a user is already logged in).If a user is already logged in onapp, will not allow another login and will show there is a user already logged in. So it is needed to logout the user and login using the new credentials. Any idea how this can be done. ?
This one I think it could help you
// REST Server URL
$request_url = 'http://localhost:3000/rest_api/user/login';
// User data
$user_data = array('username' => 'jimthunderbird',
'password' => '123456', );
// cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_POST, 1);
// Do a regular HTTP POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($user_data)); // Set POST data
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($curl);
print $response;
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Check if login was successful
if ($http_code == 200) {
// Convert json response as array
$logged_user = json_decode($response);
} else {
// Get error msg
$http_message = curl_error($curl);
die($http_message);
}
print_r($logged_user);
Related
Just like facebook login I want my user to get logged into my wordpress site by api. I want to get logged-in without storing the any info of user in the wordpress database.
here is what I tried
$ch = curl_init();
$username = $_REQUEST['value'];
curl_setopt($ch, CURLOPT_URL, 'http://api.ig.sapps.com/userLogin?emailOrUsername='.$login_data['user_login'].'&password='.$login_data['user_password'].'&api_token=12345&device_id=0&device_type=0');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
$result = json_decode($res);
if ($result->code == 400) {
$login_error = $result->message;
$all_errors = array($login_error);
}
if ($result->code == 200) {
wp_set_current_user($result->data->id, $result->data->username);
wp_set_auth_cookie($result->data->id);
do_action('wp_login', $result->data->username);
But I am not able to logged in. Please help me out.
There are so many Authentication technique... but I will explain only 2 way. (If user will login you app this user will anyway use his/hers private data other way meaningless)
1) Common Token Based Authentication Which you have to persist some data on BackEnd to check this data in every request.
2) JWT - Some Third Part Authorization Centers uses this technique. With this way you have not persist user data. Validation takes with your (Third Part Authorization Center's) unique and private SIGNATURE.
With second way you or Third part Authorization Centers saves some unique and Secured Signature and validates this user login and api call request with this sign.
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.
I create one small API what collect contact form informations from one website and store in database on another website in managment application what I also build.
On website where is contact form is this code:
// collect all fields
$save = array(
'oAuth'=>'{KEY}',
'secret'=>'{SECRET-KEY}',
'category'=>'Category',
'name'=>'Jon Doe',
'email'=>'jon#doe.com',
'phone'=>'123 456 7890',
// ... etc. other fields
);
// made GET request
$fields=array();
foreach($save as $key=>$val){
$fields[]=$key."=".rawurlencode($val);
}
// Set cross domain URL
$url='http://api.mydomain.com/';
// Send informations in database
$cURL = curl_init();
curl_setopt($cURL,CURLOPT_URL, $url.'?'.join("&",$fields));
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($cURL, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($cURL, CURLOPT_TIMEOUT, 2);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$output=curl_exec($cURL);
curl_close($cURL);
usleep(1000);
// redirect
header("Location: http://somemysite.com/thank-you-page");
session_destroy();
exit;
My question is do to use cURL like now for this or to use header() function to send GET?
I ask because I not use output here and sometimes redirection start before cURL finish request.
What is faster way to send GET info and not lost data?
The redirection will not start before cURL finishes. What may happen is that cURL fails to load you remote page, and you don't handle that error. You should add something like this:
if($output === false || curl_getinfo($cURL, CURLINFO_HTTP_CODE) != 200) {
// Here you handle your error
}
If you are looking for an alternative to load remote webpages, you can set allow_url_fopen to true in your php.ini and then use this simple function instead of cURL:
$output = file_get_contents($url.'?'.join("&",$fields));
I'm trying to make a curl request to my laravel server, in that request I have to check whether the user of my laravel application is logged in or not. I use this code:
$transferAmount = 200;
//set POST variables
$url = URL::route('post-spend-partner');
$fields = array(
'transferAmount' => urlencode($transferAmount),
'cancelUrl' => urlencode(URL::route('get-return-page-example')),
'returnUrl' => urlencode(URL::route('get-return-page-example')),
);
// New Connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
In the requested url I'm just checking if I'm logged in or not, but it always returns false:
public function postSpendPartner() {
echo "Authenticated? " . (Auth::check() ? 'Yes' : 'No');
}
I know for sure that I'm logged in, if I try the exact same thing with Ajax it completely works!
Does anyone know what I could try, to solve this problem?
Best regards!
Fabrice
Some facts: HTTP is stateless. Session IDs need to be passed to the server in order to continue the session. Session IDs are (most of the time) stored in cookies. Cookies are included in the request.
Using a cookiejar could indeed be one possible solution. The fact that it works using Ajax, and not by re-submitting the request from your server might be because of the session-verification mechanism on the server: Some session implementations lock session IDs to the initial IP address. If the contents of your cookiejar file check out, that might be the culprit.
That aside: re-submitting the request via Curl from your server is a severe codesmell to me. A proper solution would to implement something such as OAuth.
Try sending your cookies as a header with your curl request.
// ...
$cookie_header = "Cookie:";
$headers = [];
foreach($_COOKIE as $key => $val) {
// Do sanitize cookie values
$cookie_header .= " ".$key."=".$value.";";
}
$headers[] = $cookie_header;
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// ...
You could filter out unnecessary cookie values from $cookie_header.
I was wondering is it possible to automatically login to moodle after loging-in in aonther site? I tried to use curl but it seems not really working.
This is my testing code:
//set POST variables
$url = "http://moodlesite.com/login/index.php";
$fields = array(
'username' => 'username',
'password' => 'password'
);
//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, http_build_query($fields));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE );
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
I notice that after moodle login to the system, they redirect it again to http://moodlesite.com/login/index.php?testsession=userid and they need cookies it this case.
you can create a customized page for login into moodle.
code for that page .
<?php
require('config.php');
$name=$_REQUEST['name'];
$password=$_REQUEST['password'];
$dashboard = $CFG->wwwroot;
$user = authenticate_user_login($name, $password);
if(complete_user_login($user))
{
echo "login";
}
else
{
echo "not login";
}
?>
After creating that page you can pass name and password for login .
Not like that, Moodle needs to setup a session in your browser in order for you to be logged in. In general your requirement sounds strange - what exactly are you trying to achieve?
If you'd prefer to avoid your users logging in twice, you would be better implementing some sort of single sign on system:
Moodle supports CAS as standard ( http://docs.moodle.org/25/en/CAS_server_(SSO) )
Other add-on authentication plugins such as SAML and OAuth are available.
If none of those suit, you can also create your own authentication plugin. See Authentication plugins in Moodle docs and lib/authlib.php for details.