Hi everyone, I am trying to get contents of a web page which requires login, how can i access that page with CURL?
How to maintain session when using CURL?
Collapse
X
-
Tags: None
-
No help :( ?
I am missing you experts? Especially Atli, seems as if you are enjoying ur weekend :-? ? -
No help :( ?
I am missing you experts? Especially Atli, seems as if you are enjoying ur weekend :-? ?Comment
-
Hi.
Glad you found a solution.
Let me suggest another one tho.
You can have cUrl save all cookies by setting the CURLOPT_COOKIEF ILE and CURLOPT_COOKIEJ AR options. So if the site uses Sessions to log you in, you can simply pass the POST data required, and then save the Session ID cookie to maintain the session.
Say the server has a script like this:
[code=php]
<?php
session_start() ;
if(isset($_SESS ION['UserName'])) {
echo "You are logged in as ". $_SESSION['UserName'];
}
else if(isset($_POST['UserName'])) {
$_SESSION['UserName'] = $_POST['UserName'];
echo "You have been logged in as ". $_POST['UserName'];
}
else {
echo "No username available in session or post.";
}
?>
[/code]
You can log in by doing something like this:
[code=php]
<?php
// Create cookie file if it doesn't exists
$cookieFile = "myCookiefile.t xt";
if(!file_exists ($cookieFile)) {
$fh = fopen($cookieFi le, "w");
fwrite($fh, "");
fclose($fh);
}
// Initialize the cUrl connection
$ch = curl_init();
curl_setopt($ch , CURLOPT_URL, 'http://localhost/login.php');
// Set the POST data
$data = array('UserName ' => 'Foo');
curl_setopt($ch , CURLOPT_POST, 1);
curl_setopt($ch , CURLOPT_POSTFIE LDS, $data);
// Set the COOKIE files
curl_setopt($ch , CURLOPT_COOKIEF ILE, $cookieFile);
curl_setopt($ch , CURLOPT_COOKIEJ AR, $cookieFile);
// Send request and print results
curl_exec($ch);
// Close the connection
curl_close($ch) ;
?>
[/code]
It will log you in on the first execution but print the "You are logged in" message after that.Comment
Comment