In this quick tutorial I am going to show you guys how to login to a website using cURL extension in PHP. Here is two different tutorials that will help you understand this tutorials. Please have a look at them before you proceed. Note that this tutorial may not work on every sites as they will require different headers that come in request HTTP header.
GET and POST fundamentals
HTTP- the very basics
Lets crack it on! So you want to login to a website, no problem! Here's what you will need to do.
1. URL where the data is submitted to be processed.
2. Fields name, like username password and submit button.
3. PHP with cURL extension enabled.
Here is an example I have setup to demonstrate it. I have two files here, 1st is index.php where we will send the data from, and 2nd is process_login.php where the data is sent to - where it is processed. Basically we're sending all the data from index.php to process_login.php. Assuming process_login.php is the other website page where its data is processed.
The code I have in process_login.php checks if data received is valid, it checks if username and password match.
session_start();
if(isset($_POST["login"])){
if( ($_POST["username"] == "username12345") and ($_POST["password"] == "password54321") ){
$_SESSION["is_logged_in"] = $_POST["username"];
echo "You're logged in, {$_SESSION["is_logged_in"]}";
}else{
echo "Couldn't process the request, something enexpected happened";
}
}
In index.php we do following:
- Store all data in a string, username, password and submit button name and value.
- Initiate curl.
- Set option, CURLOPT_URL, URL we're working on.
- Return the result, instead of echoing it on screen. CURLOPT_RETURNTRANSFER
- What type of method we are using. CURLOPT_POST
- HTTP string we want to send to process_login.php to be processed. CURLOPT_POSTFIELDS
if( isset($_SESSION["is_logged_in"]) ){
echo "Welcome, {$_SESSION["is_logged_in"]}";
}
$username = "username12345";
$password = "password54321";
$submit_button_name = "login";
$fields = "username=".$username."&password=".$password."&login=".$submit_button_name;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/curl/process_login.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
echo $result;
No comments:
Post a Comment