I'm using PHP curl to send a series of requests to a 3rd party server which requires login and then persisting the session cookie for that login.
So I wrapped the curl operation into this class:
class SoapCli {
private $ch;
private $id;
private $rc;
function __construct() {
$this->rc=0;
$this->id=bin2hex(random_bytes(8));
$this->ch = curl_init();
$time=microtime(true);
error_log(PHP_EOL.PHP_EOL."Instance id $this->id created ($time): \$this->ch = ".print_r($this->ch,true).PHP_EOL,3,"log.txt");
curl_setopt($this->ch, CURLOPT_AUTOREFERER,1);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, "");
curl_setopt($this->ch, CURLOPT_ENCODING, "");
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->ch, CURLOPT_VERBOSE, 1);
}
function Request(string $method, string $url, array $headers = array(), $postdata = "", $referer = null) {
$resp = new stdClass();
$resp->id = $this->id;
$this->rc++;
$time=microtime(true);
error_log("Instance id $this->id before request $this->rc ($time): \$this->ch = ".print_r($this->ch,true).PHP_EOL,3,"log.txt");
try {
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
if (isset($referer)) curl_setopt($this->ch, CURLOPT_REFERER, $referer);
if (preg_match("/^POST$/i",$method)===1) curl_setopt($this->ch, CURLOPT_POSTFIELDS, $postdata);
$resp->body = curl_exec($this->ch);
$resp->err_message = curl_error($this->ch);
$resp->err_number = curl_errno($this->ch);
$resp->info = curl_getinfo($this->ch);
}
catch (Exception $exception) {
$resp->err_message = $exception->getMessage();
$resp->err_number = $exception->getCode();
$resp->info = $exception->getTrace();
}
$time=microtime(true);
error_log("Instance id $this->id before request $this->rc ($time): \$this->ch = ".print_r($this->ch,true).PHP_EOL,3,"log.txt");
return $resp;
}
}
However, after the 3rd request, the protected variable that stored the curl handle resource has its content replaced by the value of 0 (integer) and I really can't figure out why. I could only collect this log:
Instance id 1cb893bc5b7369bd created (1547852391.7976): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 1 (1547852391.8025): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 1 (1547852392.0723): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 2 (1547852392.0778): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 2 (1547852392.357): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 3 (1547852392.3616): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 3 (1547852392.6225): $this->ch = Resource id #3
Instance id 1cb893bc5b7369bd before request 4 (1547852393.0264): $this->ch = 0
Instance id 1cb893bc5b7369bd before request 4 (1547852393.0758): $this->ch = 0
Instance id 1cb893bc5b7369bd before request 5 (1547852394.8992): $this->ch = 0
Instance id 1cb893bc5b7369bd before request 5 (1547852394.9461): $this->ch = 0
EDIT: This is the code that consumes class SoapCli:
// index.php
$postdata = filter_input_array(INPUT_POST);
if ($_SESSION["logged_in"]===true) {
echo file_get_contents("main.html");
} else if (isset($postdata) && isset($postdata["action"])) {
$action = $postdata["action"];
if ($action==="Login" && isset($postdata["usrcpf"]) && isset($postdata["usrpwd"])) {
$username=$postdata["username"];
$password=$postdata["password"];
$sc=new SoapCli(); //instantiated here
$_SESSION["sc"]=$sc;
$login_response = $sc->Request(
"GET",
BASEURL."/login",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
"Cache-Control: max-age=0"
)
);
if ($login_response->err_number) {
echo file_get_contents("login_server_error.html");
} else {
$dom = new DOMDocument;
$dom->loadHTML($login_response->body);
$xdom = new DOMXPath($dom);
$csrf_token_nodes = $xdom->query("//input[#name='_csrf_token']/#value");
if ($csrf_token_nodes->length<1) {
echo file_get_contents("login_server_error.html");
} else {
$csrf_token = $csrf_token_nodes->item(0)->textContent;
$postdata = "_csrf_token=$csrf_token&_username=$username&_password=$password&_submit=Login";
$login_check_response = $sc->Request(
"POST",
BASEURL."/login_check",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/x-www-form-urlencoded",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1"
),
$postdata,
BASEURL."/login"
);
if ($login_check_response->err_number) {
echo file_get_contents("login_server_error.html");
} elseif (strpos($login_check_response->body, "api.js")) {
echo file_get_contents("login_auth_error.html");
} else {
$route_userinfo = $sc->Request(
"POST",
BASEURL."/route",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: */*",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/json",
"X-Requested-With: XMLHttpRequest",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
),
USERINFO_JSON,
BASEURL."/"
);
if ($route_userinfo->err_number) {
echo file_get_contents("login_server_error.html");
} else {
$_SESSION["logged_in"]=true;
$_SESSION["user_info"]=json_decode($route_userinfo->body);
header("Location: ".$_SERVER["PHP_SELF"], true, 303);
}
}
}
}
} else {
http_response_code(400);
}
} else {
echo file_get_contents("login.html");
}
and
// ajax.php (called by JS in main.html, which is loaded after login)
if ($_SESSION["logged_in"]===true) {
$postdata = filter_input_array(INPUT_POST);
if (isset($postdata)) {
if (isset($postdata["content"])) {
if ($postdata["content"]==="tasks") {
$sc=$_SESSION["sc"];
$route_tasks = $sc->Request(
"POST",
BASEURL."/route",
array(
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Accept: */*",
"Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3",
"Content-Type: application/json",
"X-Requested-With: XMLHttpRequest",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
),
TAKS_JSON,
BASEURL."/"
);
if ($route_tasks->err_number) {
echo file_get_contents("ajax_server_error.html");
} else {
$tarefas=json_decode($route_tasks->body);
if (isset($tarefas) && is_array($tarefas->records)) {
foreach($tarefas->records as $i=>$tarefa){
echo "<p>".$tarefa->especieTarefa->nome."</p>";
}
} else {
http_response_code(500);
}
}
}
} else {
http_response_code(400);
}
} else {
http_response_code(400);
}
} else {
http_response_code(403);
}
Since the variable SoapCli::ch is not accessible out of the class, I really can't see how its content could be changed without a statement. I coundn't find any information about a kind of http request/response which would destroy the handle, either.
Additional info
Whatever it is, it doesn't have to do with the request, because i tried to repeat request #3, which is valid and receives a valid response, and its repetition fails because of the handle is gone.
Plus, what I'm trying to implement in PHP is already done by a fully functional .NET desktop (winforms) application, so it's not like it can't be done for external reasons. I'm just trying to do with PHP curl what I did with System.Net.HttpWebRequest, and stumbled upon the problem described at this post.
How can I preserve the handle as long as I need it?
I'm using PHP 7.2 on IIS Express/Windows 10.
Short answer is: the handle does not exist when you are trying to use it inside ajax.php
Inside ajax.php, take a look at the following line:
$sc=$_SESSION["sc"];
And then you call:
$route_tasks = $sc->Request(
...
);
So you instaciated your class inside index.php and all the 3 calls made there where succesfull, then you write an object into the $_SESSION["sc"] variable and apparently the object gets encoded and decoded correctly by php's session handler which is why you are still able to call the method Request inside ajax.php after retrieving the object.
While you are indeed using an object in ajax.php it is not the same instance of the object that was created by index.php as that instance belongs to the index.php thread along with the curl handle; calling ajax.php from index.php will create a diffrent thread to handle it and will require a new curl handle as well.
Change $sc=$_SESSION["sc"]; to $sc=new SoapCli(); so the curl handle can be created before used.
I'm posting this answer just to show how I went around the problem that was described and explained by #Solrac in his answer (which is correct and I'll accept):
class SoapCli {
private $ch;
private $cookiepot;
function __construct() {
$this->cookiepot=tempnam(sys_get_temp_dir(),"CookieJar");
$this->reconstruct();
}
function reconstruct() {
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_AUTOREFERER, true);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($this->ch, CURLOPT_COOKIEFILE, $this->cookiepot);
curl_setopt($this->ch, CURLOPT_COOKIEJAR, $this->cookiepot);
curl_setopt($this->ch, CURLOPT_ENCODING, "");
curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->ch, CURLOPT_HEADER, true);
curl_setopt($this->ch, CURLINFO_HEADER_OUT, true);
curl_setopt($this->ch, CURLOPT_MAXREDIRS, 32);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_VERBOSE, true);
}
function Request(string $method, string $url, array $headers = array(), $postdata = "", $referer = "") {
if (!is_resource($this->ch)) {
$this->reconstruct();
}
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($this->ch, CURLOPT_URL, $url);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($this->ch, CURLOPT_REFERER, $referer);
if (preg_match("/^POST$/i",$method)===1) curl_setopt($this->ch, CURLOPT_POSTFIELDS, $postdata);
$response=curl_exec($this->ch);
list($headers,$body)=preg_split("/\r\n\r\n(?!HTTP)/", $response, 2);
$resp_obj = (object) array(
"body"=>$body,
"headers"=>$headers,
"err_number"=>curl_errno($this->ch),
"err_message"=>curl_error($this->ch),
"info"=>curl_getinfo($this->ch)
);
return $resp_obj;
}
function log(string $text) {
file_put_contents($this->id."log.txt",$text.PHP_EOL,FILE_APPEND|FILE_TEXT|LOCK_EX);
}
}
Related
I am trying to check login information for a website using curl php.
The Request header looks like this:
GET /loginpage.cgi HTTP/1.1
Host: test.com
Connection: keep-alive
pragma: no-cache
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Accept: */*
Referer: https://test.com/login.cgi
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: QSESSIONID=**c0da73be1917324c157e5c45b1bccd4f**
The QSESSIONID value changes every time, I need this value to be passes in the header in order to make a curl request from php. My php code looks like:
<?php
$username = 'user';
$password = 'pass';
$url = "https://test.com/login.cgi?key=GetLoginUserInfo";
$ch = curl_init();
$headers = array();
$headers[] = "Pragma: no-cache";
$headers[] = "Accept-Encoding: gzip, deflate, br";
$headers[] = "Accept-Language: en-US,en;q=0.8";
$headers[] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36";
$headers[] = "Accept: */*";
$headers[] = "Referer: https://test.com/login.cgi?key=UDIT";
$headers[] = "Cookie: QSESSIONID=c0da73be1917324c157e5c45b1bccd4f";
$headers[] = "Connection: keep-alive";
$headers[] = "Cache-Control: no-cache, no-store, max-age=0, must-
revalidate";
$headers[] = "Expires: Fri, 01 Jan 1990 00:00:00 GMT";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result = curl_exec($ch);
print_r($result);
$ch_error = curl_error($ch);
if ($ch_error) {
echo "cURL Error: $ch_error";
} else {
echo $result;
}
curl_close($ch);
?>
Now when I run this. When I get the session id from the dev tools request header and change it in my header then only I can log in, because the value changes every time some one login.
So my question is, is their a way I can get that value from the request header so that i can append that value in my header in php code. Or any other way that you can suggest, I am open for suggestions.
If i remove this information from php code the request fails, if
That looks like a session ID (the name kinda gives it away), these are generated on your first connection. You're supposed to store this and send this as a cookie in subsequent requests so the server can keep track of your session.
If you dont send this cookie header you will get a random one with every request.
This code is written in a way to attempt to teach you how cookies are handled. There are a lot of assumptions about what you are trying to do, but this gives you a basic understanding of how to parse/handle headers and the session ID.
I've avoided using a cookiejar (which is much easier and cleaner to code) because it automatically does all of this for you, i recommend you look into them once you learn how session ID's work.
<?php
class MyService
{
private $headers = [];
private $cookies = [];
private $loggedIn = false;
function login($username, $password)
{
$ch = curl_init('https://test.com/login.cgi');
#Assumption: Do whatever is needed for login here
curl_setopt($ch, CURLOPT_USERPWD, $username . ':' . $password);
# This is where we setup header processing
curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'parseHeaders']);
#Assumption: Check for valid response
$response = curl_exec($ch);
$this->loggedIn = ($response == 'true');
curl_close($ch);
return $this->loggedIn;
}
function getHeader($header)
{
return array_key_exists($header, $this->headers) ? $this->headers[$header] : null;
}
function getCookie($cookie)
{
return array_key_exists($cookie, $this->cookies) ? $this->cookies[$cookie] : null;
}
function parseHeaders($ch, $header)
{
if (stristr($header, 'set-cookie')) {
# If you can install PECL pecl_http this will work better
// $this->cookies = http_parse_cookie(strstr('Set-Cookie', $header))['cookies'];
# Otherwise
$reserved_words = [
'httponly',
'expire',
'path',
'expires',
'domain',
'secure'
];
preg_match("/Set-Cookie: (.*)/", $header, $cookies);
foreach ($cookies as $cookie) {
$cookie = explode(';', $cookie);
foreach ($cookie as $cookie_part) {
$cookie_part = explode('=', $cookie_part);
array_walk($cookie_part, create_function('&$val', '$val = trim($val);'));
if (!in_array($cookie_part[0], $reserved_words) && isset($cookie_part[1])) {
$this->cookies[$cookie_part[0]] = $cookie_part[1];
}
}
}
} else {
$header_part = explode(':', $header, 2);
if (isset($header_part[1])) {
$this->headers[trim($header_part[0])] = trim($header_part[1]);
}
}
}
function otherInfo()
{
if (!$this->loggedIn) {
throw new NotLoggedInException('Login first');
}
$headers = []; # Populate whatever headers are mandatory
$url = "https://test.com/login.cgi?key=GetOtherInfo";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, 'QSESSIONID=' . $this->getCookie('QSESSIONID'));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function getUserInfo()
{
if (!$this->loggedIn) {
throw new NotLoggedInException('Login first');
}
$headers = []; # Populate whatever headers are mandatory
$url = "https://test.com/login.cgi?key=GetLoginUserInfo";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, 'QSESSIONID=' . $this->getCookie('QSESSIONID'));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
$username = 'user';
$password = 'pass';
$api = new MyService();
$api->login($username, $password);
$info = $api->getUserInfo();
$other = $api->otherInfo();
i am new to api so i may be completely wrong.
i was going through some docuementaion in github but could not find some answers so i am here
i want to pass url of these functions to api.php
after validating these key and secret.when i echo these data i get key, secret and url but how to get these details in php as its not a post and i cant use _post function to manipulate data based on url submitted and give the result
public function __construct($key = '', $secret = '', $timeout = 30,
$proxyParams = array()) {
$this->auth = array(
"auth" => array(
"api_key" => $key,
"api_secret" => $secret
)
);
$this->timeout = $timeout;
$this->proxyParams = $proxyParams;
}
public function url($opts = array()) {
$data = json_encode(array_merge($this->auth, $opts));
// echo $data;
$response = self::request($data, 'http://somesite.com/a/api.php', 'url');
return $response;
}
here is request function
private function request($data, $url, $type) {
$curl = curl_init();
if ($type === 'url') {
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
}
curl_setopt($curl, CURLOPT_URL, $url);
// Force continue-100 from server
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.85 Safari/537.36");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_FAILONERROR, 0);
curl_setopt($curl, CURLOPT_CAINFO, __DIR__ . "/cacert.pem");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
if (isset($this->proxyParams['proxy'])) {
curl_setopt($curl, CURLOPT_PROXY, $this->proxyParams['proxy']);
}
$response = json_decode(curl_exec($curl), true);
if ($response === null) {
$response = array (
"success" => false,
"error" => 'cURL Error: ' . curl_error($curl)
);
}
curl_close($curl);
return $response;
}
}
output of echo data is sufficient but its not post and i tried json_decode but nothing is coming to api.php
here is output of echo
{"auth":{"api_key":"be8fgdffgrfffrffc4b3","api_secret":"1b59fsfvfrgfrfvfb29d6e555a1b"},"url":"https:\/\/i.ndtvimg.com\/i\/2017-06\/modi-at-kochi-metro-station_650x400_81497685848.jpg","wait":true}
i tried these in api.php to get the data but nothing is working
$gggss['url'] = json_decode($data, true); //this returns an array
or
$gggss=$_POST['data'];
any help will be great
I think you are trying get urlencoded data, while your JSON string located in body of request. Try use this instead:
$entityBody = file_get_contents('php://input');
<?php
function cuload($url, $got = array()){
//include(MDL.'socket_adapter.php');
$user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
$default_options = array(
'data' => 'og',
'post_data' => false,
'referer' => false,
'cookie' => false,
'auth' => false,
'proxy' => false,
'pauth' => false,
'returndata' => true,
);
foreach($default_options as $opt=>$value) {
if(!isset($default_options[$opt])) {$got[$opt] = $value; }
}
$curl = curl_init();
//if(strstr($referer,"://")){
//curl_setopt ($curl, CURLOPT_REFERER, $got['referer']);}
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($curl, CURLOPT_HEADER, 1);
if(isset($got['returndata'])){
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
}else{
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
}
curl_setopt ($curl, CURLOPT_ENCODING, 'gzip, deflate');
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
//curl_setopt($curl ,CURLOPT_USERAGENT, $got_opt['user_agent']); //The Name of the UserAgent we will be using ;)
if(isset($got['post'])){curl_setopt($curl ,CURLOPT_POST , true); curl_setpot($curl ,CURLOPT_POSTFIELDS , $post); }
if(isset($got['referer'])) curl_setopt($curl,CURLOPT_REFERER, $options['referer']);
if(isset($got['cookie'])){ if($got['cookie'] == "0"){
curl_setopt($curl ,CURLOPT_COOKIEJAR, TBP."cookie.txt"); }//If ever needed...
elseif($got['cookie'] != "0"){
curl_setopt($curl ,CURLOPT_COOKIE, $got['cookie']); }}
//curl_setopt($curl ,CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($curl ,CURLOPT_MAXREDIRS, 5);
//curl_setopt($curl ,CURLOPT_SSL_VERIFYPEER, false);
$custom_headers = array();
$custom_headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$custom_headers[] = "Pragma: no-cache";
$custom_headers[] = "Cache-Control: no-cache";
$custom_headers[] = "Accept-Language: en-us;q=0.7,en;q=0.3";
$custom_headers[] = "Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7";
if(isset($url_parts['user']) and isset($url_parts['pass'])) {
$custom_headers[] = "Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']);
}elseif(isset($got['auth'])){
$uj = explode(":",$got['auth']); $custom_headers[] = "Authorization: Basic ".base64_encode($uj[0].':'.$uj[1]); }
if(isset($got['pauth'])){
curl_setopt($curl ,CURLOPT_PROXYUSERPWD ,$pauth); }
if(isset($got['proxy'])){
curl_setopt($curl ,CURLOPT_PROXY ,$proxy); }
curl_setopt($curl ,CURLOPT_HTTPHEADER, $custom_headers);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
curl_close ($curl);
ob_end_clean();
return $response;
}
?>
ok now when i tries this script on same page :
<?php
$page = cuload('http://www.google.com');
?>
But now without echoing the $page variable it echo the content . i donot need to echo anything here is just need to find some link from the $page variable content .. after exploring the script deeply i find that may be there was a problem in curl_exec cause if i remove the return $response still is shows the content ! i cant understand why it giving output of $page when i am not echoing $page .
please help me !
Instead of
foreach($default_options as $opt=>$value) {
if(!isset($default_options[$opt])) {$got[$opt] = $value; }
}
try this:
foreach($default_options as $opt=>$value) {
if(!empty($default_options[$opt])) {$got[$opt] = $value;}
}
well the problem is the simple this today not working !
<?php
function cload($url, $got = array()){
//include(MDL.'socket_adapter.php');
$user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0";
$default_options = array(
'data' => 'og',
'post_data' => false,
'referer' => false,
'cookie' => false,
'auth' => false,
'proxy' => false,
'pauth' => false,
'returndata' => true,
);
foreach($default_options as $opt=>$value) {
if(!empty($default_options[$opt])) {$got[$opt] = $value; }
//if(!empty($got[$opt])) {$got[$opt] = $value; }
}
//echo "<hr>"; print_r($got); echo "<hr>";
$curl = curl_init();
//if(strstr($referer,"://")){
//curl_setopt ($curl, CURLOPT_REFERER, $got['referer']);}
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt ($curl, CURLOPT_USERAGENT, $user_agent);
curl_setopt ($curl, CURLOPT_HEADER, 1);
if(isset($got['returndata'])){
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
}else{
curl_setopt ($curl, CURLOPT_RETURNTRANSFER, false);
}
curl_setopt ($curl, CURLOPT_ENCODING, 'gzip, deflate');
curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, false);
if(isset($got['post_data'])){ curl_setopt($curl ,CURLOPT_POST , true);
curl_setpot($curl ,CURLOPT_POSTFIELDS ,$got['post_data']); }
if(isset($got['referer'])) curl_setopt($curl,CURLOPT_REFERER, $got['referer']);
if(isset($got['cookie'])){ if($got['cookie'] == "0"){
curl_setopt($curl ,CURLOPT_COOKIEJAR, TBP."cookie.txt"); }//If ever needed...
else{
curl_setopt($curl ,CURLOPT_COOKIE, $got['cookie']); }}
$custom_headers = array();
$custom_headers[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
$custom_headers[] = "Pragma: no-cache";
$custom_headers[] = "Cache-Control: no-cache";
$custom_headers[] = "Accept-Language: en-us;q=0.7,en;q=0.3";
$custom_headers[] = "Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7";
if(isset($url_parts['user']) and isset($url_parts['pass'])) {
$custom_headers[] = "Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']);
}elseif(isset($got['auth'])){
$uj = explode(":",$got['auth']); $custom_headers[] = "Authorization: Basic ".base64_encode($uj[0].':'.$uj[1]); }
if(isset($got['pauth'])){
curl_setopt($curl ,CURLOPT_PROXYUSERPWD ,$pauth); }
if(isset($got['proxy'])){
curl_setopt($curl ,CURLOPT_PROXY ,$proxy); }
curl_setopt($curl ,CURLOPT_HTTPHEADER, $custom_headers);
//curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$response = curl_exec($curl);
$info = curl_getinfo($curl);// , CURLINFO_HEADER_OUT);
curl_close ($curl);
//echo "<hr>"; echo $info; echo "<hr>";
return $response; }
?>
now when i am using this code :
<?php
$cv = load('https://localhost/a/ac.php?a=io',array('cookie' => $fbcook,'referer' => $ref,'post_data' => 'odl=lop&isi=837&io'));
echo $cv;
?>
but i am getting error :
Fatal error: Call to undefined function curl_setpot() in C:\xampp\htdocs\a\mack\curl.php on line 41
Please help me ! why this happning this line 42 indicates this line curl_setpot($curl ,CURLOPT_POSTFIELDS ,$got['post_data']); }
thanks
simple typo: curl_setpot should be curl_setopt
When a function of cURL is undefined, then it is most likely that cURL is not available.
However, I think that you meant curl_setopt().
curl_setpot should be curl_setopt.
You use xampp so you need to activate curl lib by following these steps:
Locate XAMPP install directory
Open php/php.ini (probably C:\xampp\php\php.ini
or C:\program files\apachefriends\xampp\php\php.ini)
Do a search for the word ‘curl’ and uncomment (remove the leading semicolon) that line. Before removing: ;extension=php_curl.dll. After removing: extension=php_curl.dll
Save and close
Open apache/bin/php.ini (probably C:\xampp\apache\php.ini
or C:\ program files\apachefriends\xampp\apache\php.ini)
Search for curl, uncomment as before (step 3)
Save and close
Do not forget to restart Apache
Good luck
I am authenticating a login via CURL just fine. I have a variable I am using to display the returned HTML, and it is returning my user control panel as if I am logged in.
After authenticating, I want to communicate variables with a form on another page within the site; but for some reason the HTML from that page is returning a non-authenticated version of the header (as if the original authentication never took place.)
I have a cookies.txt file with 777 permissions, and have tried just getting the contents of the same page shown when I authenticate and it is as if I am losing any associated session/cookie data somewhere along the way.
Here is my curl.class file -
<?
class Curl {
public $cookieJar = "";
// Make sure the cookies.txt file is read/write permissions
public function __construct($cookieJarFile = 'cookies.txt') {
$this->cookieJar = $cookieJarFile;
}
function setup() {
$header = array();
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($this->curl, CURLOPT_COOKIEJAR, $this->cookieJar);
curl_setopt($this->curl, CURLOPT_COOKIEFILE, $this->cookieJar);
curl_setopt($this->curl, CURLOPT_AUTOREFERER, true);
curl_setopt($this->curl, CURLOPT_COOKIESESSION, true);
curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
}
function get($url) {
$this->curl = curl_init($url);
$this->setup();
return $this->request();
}
function getAll($reg, $str) {
preg_match_all($reg, $str, $matches);
return $matches[1];
}
function postForm($url, $fields, $referer = '') {
$this->curl = curl_init($url);
$this->setup();
curl_setopt($this->curl, CURLOPT_URL, $url);
curl_setopt($this->curl, CURLOPT_POST, 1);
curl_setopt($this->curl, CURLOPT_REFERER, $referer);
curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
return $this->request();
}
function getInfo($info) {
$info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
return $info;
}
function request() {
return curl_exec($this->curl);
}
}
?>
And here is my curl.php file -
<?
include('curl.class.php'); // This path would change to where you store the file
$curl = new Curl();
$url = "http://www.site.com/public/member/signin";
$fields = "MAX_FILE_SIZE=50000000&dado_form_3=1&member[email]=email&member[password]=pass&x=16&y=5&member[persistent]=true";
// Calling URL
$referer = "http://www.site.com/public/member/signin";
$html = $curl->postForm($url, $fields, $referer);
echo($html);
?>
<hr style="clear:both;"/>
<?
$html = $curl->postForm('http://www.site.com/index.php','nid=443&sid=733005&tab=post&eval=yes&ad=&MAX_FILE_SIZE=10000000&ip=63.225.235.30','http://www.site.com/public/member/signin');
echo $html; // This will show you the HTML of the current page you and logged into
?>
Any ideas?
As always when doing HTTP scripting, you should use LiveHTTPHeaders or similar to record a manual session first and then you should mimic that as closely as possible when you write your curl stuff.
Also (unfortunately) the command line tool curl offers slightly better debug and tracing options than what the PHP binding does, which makes that a better tool to work out exactly what you need to do and once that works you convert it to a PHP program.
See http://curl.haxx.se/docs/httpscripting.html for further details.
Err, please tell us what authentication scheme the server is using. Not all schemes use cookies.