Calling $.get after $.post while maintaining the session somehow - php

I have an API which you can access through web url. You can sign in by POSTing your username/password to let's say
http://myapi.example/signin
I do that with a jQUERY's $.post request which works fine - I get the status OK back if everything is correct. Now I need to somehow GET data from this API with certain url, which I would do with $.get of course, but I get the reponse unauthorized… So probably the session somehow gets lost, after the POST request/response.
I know that this POST/GET works, because if I do signin and then just type the GET url in browser - i get the response text plain in browser.
How would you keep the "session" somehow to simulate browser's behaviour in this?
function ajaxSignIn(){
$.post(url,
{
email: document.getElementById("name").value,
password: document.getElementById("password").value
},
function(data,status){ // this is where POST is successful (i get data in)
console.log("\nStatus of POST: " + status);
console.log(data);
$.get(urlForGet,function(data,status){ // GET call
console.log("Status of GET: " + status);
});
});
}
If I was unclear please ask for more info.
Thank you for any help.

I think that your API does not work as it should or you are not using all the data it provides you. Usually this is how these APIs work:
You send login request.
Server replies with status code and if it is ok sends you a generated key which is valid for some period of time.
If you want to use the api further you need to supply this key with every new request.
Browsers use Cookies, APIs use this.

In case anyone is interested: I ended up sending ajax request to my local php server, where I managed to get a Cookie from the remote API with the use of cURL.
You create a cookie file and then use the cookie with further GET requests …
curl link to cookie explained
Server-side curl part without getting parameters etc etc.:
// here I come from my ajax
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookieJarFilePath); // this is what you need
curl_setopt( $ch, CURLOPT_HEADER, 1);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
// i get data in response from the server
$response = curl_exec( $ch );
curl_close($ch);
Here you can continue to use GET requests on the same page now with this cookie with the use of:
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookieJar); // other stuff is the same as before

Related

PHP cURL request takes up the entire Timeout

I currently have a Laravel application, which is doing a CURL request from one route to another route within the same route. My CURL looks like this:
//LOGGING THAT A CURL CALL IS ABOUT TO BE MADE
$url = env('APP_URL') . '/tests/add/results';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return server error
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLINFO_HEADER_OUT, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $test_post_data);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
In the route, that the POST is being sent to, the first thing i log, is the request data:
//LOGING THAT I RECEIVED THE CURL CALL in receiving function
I'm noticing, that the logs for the request data get logged exactly the same amount of time as the timeout, meaning the request is actually being sent 10 seconds after the initial call.
In my logs i'll see something like:
10:10:10 - LOGGING CURL CALL
10:10:20 - Recieving CURL call
If i change the timeout to 30, then the log shows 30 seconds later that i received the CURL call.
Does anyone have any idea why this may be happening?
The response from the CURL just comes back as false always.
I did the following to make a post request work:
Instead of calling the route via CURL i did a post directly to the route function
$testController = new TestsController;
$test_data_request = new \Illuminate\Http\Request();
$test_data_request->setMethod('POST');
$test_data_request->request->add( $test_post_data );
$testId = $testController->addTestResults($test_data_request);
You've not provided enough information, but i think, the problem will be one or more of the following:
The WebServer http://127.0.0.1:8000 is not running
The script located on http://127.0.0.1:8000/tests/add/results is running too long and the request timeouts before it is completed
The requested path is returning redirect headers and creates an infinite loop
The response is too big to finish the data transfer in thirty seconds (very wierd if on localhost)
Try some more debugging and provide more information on this, so we may help you.
PS: Firstly i would try to catch the headers (curl_setopt($ch, CURLINFO_HEADER_OUT, true);) and print out the response (var_dump($response);) - or save it to some file :)

PHP remote login with cURL, need advice

I'll try to explain the issue, I don't know if it is doable...
If you login here (1st link):
https://profile.ea.com/
And then go here (2nd link):
https://accounts.ea.com/connect/auth?client_id=sparta-companion-web&response_type=code&prompt=none&redirect_uri=nucleus:rest
You will find a code like this only if you are logged (token):
{"code":"QUORAL0aEYq2RjJGJwFEIddI99wM_FaZ_FgktceQ"}
That token is what I need to make some (not documented) API calls work from my web app (cURL with PHP).
I'm trying to emulate what I do when I execute a login but it seems to fail every time and I can't understand why...
This is my 1st call for the 1st link:
<?php
$username = urlencode('myaccount#mail.test');
$password = 'Mysecretpassword';
$event = 'submit';
$loginUrl = 'https://profile.ea.com/';
//init curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'email='.$username.'&password='.$password.'&_eventId='.$event);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$firstlogin = curl_exec($ch);
//var_dump($firstlogin);
//login done?
Then the token part:
//get the token
curl_setopt($ch, CURLOPT_URL, 'https://accounts.ea.com/connect/auth?client_id=sparta-companion-web&response_type=code&prompt=none&redirect_uri=nucleus:rest');
//execute the request
$token = curl_exec($ch);
var_dump($token);die;
The main issue is the 1st part:
The profile.ea link seems to do a redirect to a unique url, maybe the CURLOPT_FOLLOWLOCATION is not enough?
The data needed to login is an array with 'email', 'password' and '_eventId' but I can't find any other required field.
What I'm doing wrong? Why the login is not working? How can I debug what is not working?
Probably the issue is that when you hit first url with code $firstlogin = curl_exec($ch);. It essentially does not mean that you got logged in for every request now. The next url hit needs to know, who you are before sending you the data, and they are possibly using cookies for this identification. Try simulating it in a browser. Probably, with the first URL request, there are some cookies returned after logging in, which are then forwarded with the next request.
You need to replicate cookies with your curl too. Try to extract any cookies being set with login cURL with the code at this link.
Then forward the cookies with your cURL request using curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));
If above doesn't work, try replicating the same scenerio at browser and find out all the cookies in browser. Then replicate cookies already set and the ones being set by the login cURL request. This should probably work.
you're doing lots of things wrong,
you don't urlencode $username, but you need to. you don't urlencode $password, but you need to. you don't urlencode $event, but you need to. you don't use, nor try to fetch, the csrf token (called execution) prior to sending the login request, that won't work. you try to login without a pre-existing cookie session, that won't work, the cookie session and the csrf token are tied together, if 1 of them are missing/incorrect, your login won't be successful, and your code fetches neither of them. you're also missing a lot of login post parameters, including phoneNumber, passwordForPhone, _rememberMe, and several others, add them all.

Create Classic ASP session variables using Curl with PHP

I have created a simple classic ASP script that will take a username and password from a post and create session variables. This script works fine if i use a standard html form and redirect to this page. I have a php site and I want to log users into both websites when they log into the php site. To do this i wanted to add a curl request to the login script in php. This would send the password and username over to the script and create the session variables. The response i get from the curl request would suggest that it worked, but it doesnt seem to be saving the session.
Here is the curl request.
$postinfo = "username=".$username."&password=".$password;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postinfo);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
I dont want to paste the full asp script, but this is roughly how it works. The session persists when i login using a html form so i know its working correctly. When the curl request is finished executing it seems that the session variables are populated, but when i visit another page the session does not exist.
'do some stuff with the db to check if the credentials work.
if success = true then
Session("userid") = userid
Session("login") = "good"
Response.Write("Login successful - " & Session("userid"))
else
Response.Write("Login Failed")
end if
When i run the curl request the response is "Login successful - 123". This means not only is the login working, but its also setting the session value. The problem is that when i try to visit the asp site it does not detect any session data.
I have verified that the all links are pointing to https://www.website.com. Both websites are under the same domain name, just 2 different subdirectories/languages. They are both running on the same server.

Scrape data from AJAXREQUEST

I would like to crab data from a website that uses an ajax request to load new data from the server into a DIV.
When I click on the button of the website, that will load new data into the website, I can see that the browser does only 1 POST request with the following post string:
AJAXREQUEST=_viewRoot&j_id376=j_id376&javax.faces.ViewState=j_id3&j_id376%3Aj_id382=j_id376%3Aj_id382&valueChanged=false&AJAX%3AEVENTS_COUNT=1&
When I do the above post request using php curl I don't get any useful data.
Does someone know how to crab data for this kind of request?
UPDATE1:
This is what I use in php:
$ch = curl_init ('http://www.website.com');
$post_string = 'AJAXREQUEST=_viewRoot&j_id376=j_id376&javax.faces.ViewState=j_id3&j_id376%3Aj_id382=j_id376%3Aj_id382&valueChanged=false&AJAX%3AEVENTS_COUNT=1&';
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
$output = curl_exec ($ch);
I don't get any results, also no errors or messages.
Your problem probably isn't with your PHP code, its more likely with what you are actually sending to the server. I'm assuming you listed website.com as a place holder for whatever service you are trying to interact with, but since you haven't listed any of the information as to where your sending the request or what your getting back I'm assuming that what your posting to the server is simply being ignored because what your sending is invalid, or incomplete, or requires further POST/GET requests. Another possibility is that your attempting to POST to a service that requires an authenticated session (the POST variables you listed could include some sort of token to identify the session) which you have not established.
I would recommend that you first test your code on a simpler "controlled test case". Setup a basic web form that returns true or something when you POST a value to it. Test your code with the simpler case first to make sure your POST code works.
Then using a debugging tool such as LiveHTTPHeaders or Firebug record the entire POST/GET request interaction with the server. It might be a good idea to first try to "replay" this interaction with a debugging tool to prove that your methodology works. Then once you know exactly what you need to do from a high level, repeat this process in your PHP code.
There is not much other advice anyone can give you with the information you have given us.

Using CURL - Post and redirect help

I've been banging my head against a wall for a few hours now - and it's probably something really obvious I've missed!
I'm trying to connect to a payment service provider (PSP) using CURL, post data and follow the post so the user actually ends up on the PSP's site.
Using the following:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://psp.com/theirpage');
curl_setopt($ch, CURLOPT_REFERER, "http://mysite.com/mypage");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
curl_setopt($ch, CURLOPT_POST, 1);
$result=curl_exec($ch);
curl_close($ch);
This successfully connects, verifies the data I've passed, but instead of redirecting the user to the PSP, it just loads the HTML on my site. Safe mode is off, and open_basedir is blank.
What am I doing wrong?
CURL would do an internal redirect and it wont have any effect on the user viewing your curl script. Keep in mind that the payment was made by your server NOT the users computer, hence expecting the session to work for the user is incorrect. cURL 'is the browser'.
If you just want a redirect after payment is made via cURL, you will have to do it via header() or by using some JS like window.location.
The curl request is being made from your server, and as such your server is receiving the response page. There's no way to initiate the request from the server and have the client receive the response. Either return the HTML to the user from your site (as you're doing), or make the request from the client's browser using Javascript. Hope that helps

Categories