Всем привет, Мне надо curl-ом получить страницу http://leadserve.opt-intelligence.com/ls/signin.action Но до входа до этой страницы надо ввести пользовательсий пароль Использование HTTP authentication типа Код (Text): curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword"); в данном случае не помогает и возвращается окно для ввода пароля, так как HTTP authentication это если пароль требует .htaccess, как я понимаю? Пробую так Код (Text): <?php class PublisherReprter { private $fpKey; private $Username; private $Password; private $IsDebug= true; private $CookeiFilename; private $strCookie; // public function setLogin( $Username, $Password ) { public function PublisherReprter() { $this->CookieFilename= dirname(__FILE__) . DIRECTORY_SEPARATOR . "my_cookies.txt"; session_start(); $this->strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=' . $this->CookieFilename; echo '<br>$strCookie::'.print_r( $strCookie,true).'<br>'; if ($this->IsDebug) echo 'PublisherReprter $this->CookieFilename::'.print_r($this->CookieFilename,true).'<br>'; } public function Run() { $LoginPageHTML= $this->OpenLoginPage(); //Open Login page to get value of __fp field for CSRF protection $this->Get__fpKey($LoginPageHTML); // retrieve __fp key from html from login page if ($this->IsDebug) echo 'Get__fpKey $this->fpKey::'.print_r($this->fpKey,true).'<br>'; $Res= $this->MakeLogToSite(); // make login to form using SRF protection from prior step and login parameters if ($this->IsDebug) echo '++$Res::'.print_r($Res,true).'<br>'; if ( $Res ) { $Res= $this->GetReportData(); // get report data using SRF protection from and from prior login if ($this->IsDebug) echo '++!!!@@ $Res::'.print_r($Res,true).'<br>'; } } // public function Run() { public function setLogin( $pUsername, $pPassword ) { $this->Username= $pUsername; $this->Password= $pPassword; } private function Get__fpKey($html) { $Pattern = '/"__fp"[\s]*value=[\s]*"([^"]*)".*?' . '$/xsi'; $Res= preg_match( $Pattern, $html, $A/*(, PREG_OFFSET_CAPTURE*/ ); if ( $Res and !empty($A[1]) ) { $this->fpKey= $A[1]; return true; } return false; } // private function Get__fpKey($html) { private function OpenLoginPage() { $url = "http://leadserve.opt-intelligence.com/ls/reports.action"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); // set url to post to curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects // curl_setopt($ch, CURLOPT_COOKIEJAR, /* dirname(__FILE__) .*/ "my_cookies.txt"); // curl_setopt($ch, CURLOPT_COOKIEFILE, /* dirname(__FILE__) . */ "my_cookies.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable curl_setopt($ch, CURLOPT_TIMEOUT, 3); // times out after 4s //curl_setopt($ch,CURLOPT_HEADER,true); $result = curl_exec($ch); // run the whole process $curl_errno= curl_errno($ch); if ($this->IsDebug) echo '<hr><h2>OpenLoginPage</h2><hr>'; if ($this->IsDebug) echo 'LOGIN $ch::'.print_r( $ch,true ).'<br>'; if ($this->IsDebug) echo 'LOGIN curl_errno($ch)::'.print_r( curl_errno($ch),true ).'<br>'; if ($this->IsDebug) echo 'LOGIN curl_error($ch)::'.print_r( curl_error($ch),true ).'<br>'; if ($this->IsDebug) echo 'LOGIN curl_getinfo($ch)::'.print_r( curl_getinfo($ch),true ).'<br>'; if ($this->IsDebug) echo '$_COOKIE::'.print_r( $_COOKIE,true).'<br>'; if ($this->IsDebug) echo '$_SESSION::'.print_r( $_SESSION,true).'<br>'; curl_close($ch); if ($this->IsDebug) echo '<hr>LOGIN<hr>'; return $result; } // private function OpenLoginPage() { private function GetReportData( ) { $ch = curl_init('http://leadserve.opt-intelligence.com/ls/reports.action'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_REFERER, "http://leadserve.opt-intelligence.com/ls/reports.action"); curl_setopt($ch, CURLOPT_POSTFIELDS, 'date=dr&d1=d&f2=p&f4='.urlencode('03/01/2013').'&f5=' .urlencode('03/31/2013').'&_sourcePage='.urlencode('/WEB-INF/jsp/reports/pageReports.jsp').'&__fp='.urlencode($this->fpKey) ); //curl_setopt($ch, CURLOPT_COOKIEJAR, /* dirname(__FILE__) .*/ "my_cookies.txt"); //curl_setopt($ch, CURLOPT_COOKIEFILE, /* dirname(__FILE__) .*/ "my_cookies.txt"); curl_setopt( $curl_handle, CURLOPT_COOKIE, $this->strCookie ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $content= curl_multi_getcontent($ch); curl_setopt($ch,CURLOPT_HEADER,true); $result = curl_exec($ch); $curl_errno= curl_errno($ch); if ($this->IsDebug) echo '<hr><h2>GetReportData: </h2><hr>'; if ($this->IsDebug) echo '$content::'.print_r( $content,true).'<br>'; if ($this->IsDebug) echo $result; if ($this->IsDebug) echo '<br>$result::'.print_r( $result,true).'<br>'; if ($this->IsDebug) echo '$ch::'.print_r( $ch,true ).'<br>'; if ($this->IsDebug) echo 'curl_errno($ch)::'.print_r( curl_errno($ch),true ).'<br>'; if ($this->IsDebug) echo 'curl_error($ch)::'.print_r( curl_error($ch),true ).'<br>'; if ($this->IsDebug) echo 'curl_getinfo($ch)::'.print_r( curl_getinfo($ch),true ).'<br>'; curl_close($ch); return $curl_errno == 0; } // private function GetReportData( ) { private function MakeLogToSite() { $ch = curl_init('http://leadserve.opt-intelligence.com/ls/signin.action'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_REFERER, "http://leadserve.opt-intelligence.com/ls/signin.action"); curl_setopt($ch, CURLOPT_POSTFIELDS, 'username='.urlencode($this->Username).'&password='.urlencode($this->Password).'&_sourcePage='.urlencode('/WEB-INF/jsp/common/signin.jsp').'&__fp='.urlencode($this->fpKey) ); // curl_setopt($ch, CURLOPT_COOKIEJAR, /* dirname(__FILE__) . */ "my_cookies.txt"); // curl_setopt($ch, CURLOPT_COOKIEFILE, /* dirname(__FILE__) . */ "my_cookies.txt"); curl_setopt( $curl_handle, CURLOPT_COOKIE, $this->strCookie ); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_HEADER,true); $result = curl_exec($ch); $curl_errno= curl_errno($ch); if ($this->IsDebug) echo '<hr><h2>MakeLogToSite</h2><hr>'; if ($this->IsDebug) echo $result; if ($this->IsDebug) echo '<br>$result::'.print_r( $result,true).'<br>'; if ($this->IsDebug) echo '$ch::'.print_r( $ch,true ).'<br>'; if ($this->IsDebug) echo 'curl_errno($ch)::'.print_r( curl_errno($ch),true ).'<br>'; if ($this->IsDebug) echo 'curl_error($ch)::'.print_r( curl_error($ch),true ).'<br>'; if ($this->IsDebug) echo 'curl_getinfo($ch)::'.print_r( curl_getinfo($ch),true ).'<br>'; if ($this->IsDebug) echo '$_COOKIE::'.print_r( $_COOKIE,true).'<br>'; if ($this->IsDebug) echo '$_SESSION::'.print_r( $_SESSION,true).'<br>'; curl_close($ch); return $curl_errno == 0; } // private function MakeLogToSite() { } // class PublisherReprter { $PublisherReprter= new PublisherReprter(); $PublisherReprter->setLogin( 'user@mail.com', 'password' ); $PublisherReprter->Run(); У меня получается такой вывод на экран Немного своими словами 1) Я успешно курлом открываю страницу логина ( $this->OpenLoginPage() ) с нее считываю ($this->Get__fpKey($LoginPageHTML)) значение спрятанной переменной __fp, котоая как я понимаю для CSRF защиты 2) В $this->MakeLogToSite пытаюсь симулировать отправку пост запроса логина с переменной полученной выше __fp и параметрами подключения и там странный результат так как curl_errno($ch) и curl_error($ch) ошибок не отбражают но вывоят пустую строку в результате 3) Я не очень понял с кукями - видимо на шаге 2) надо его создать и передать при шаге 3) ( в GetReportData() ) Подскажите плиз как это сделать и что в этом файле должно быть ? Сорри за длинные листы - буду благодарен за любую помощь.
ничего особенного руками писать в этом файле не надо - он автоматом должен создаться. попробуйте указать его путь внутри /tmp - по крайней мере, когда я пытался куки записывать cURL не хотел работать ни с одним другим путем кроме /tmp
Не помню, как с курлом, давно очень им не пользовался. Но отправить пост-запрос с произвольными заголовками (в том числе куки и user-agent) можно и простым file_get_contents: Код (PHP): <?php $sid = 'session_id, полученный при первом запросе'; $post = array( '__fp' => 'полученная в первом запросе переменная fp', 'login' => 'ваш логин', 'password' => 'ваш пароль' ); $opts = array( 'http' => array( 'method' => 'POST', 'user_agent' => 'Opera/9.80 (Windows NT 6.1; Win64; x64) Presto/2.12.388 Version/12.14', 'header' => "Cookie: session_id={$sid}\r\nContent-type: application/x-www-form-urlencoded", 'content' => http_build_query($post) ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context); ?> Добавлено спустя 1 минуту 4 секунды: Соответственно, названия переменных post и cookie свои подставить нужно туда.
А посольку это jsp страница то надо брать переменную JSESSIONID ? Там такие заголовки: Код (Text): LOGIN $ch::Resource id #2 LOGIN $result::HTTP/1.1 302 Moved Temporarily Cache-control: no-cache="set-cookie" Content-Type: text/plain; charset=UTF-8 Date: Sun, 10 Mar 2013 11:15:50 GMT Location: http://leadserve.opt-intelligence.com/ls/signin.action Set-Cookie: JSESSIONID=377515119381D380EE7FACA7AD419301; Path=/ls Set-Cookie: AWSELB=D171A3C314A759266FA0800BD41453A838AAFE90EC88BCF5FA39A459FDD713F494AEF2D49AE57739FF0B04EC5C1F189F5D5895521075CCDA5507BC9B3EF8BE820FBA0C5C60;PATH=/;MAX-AGE=86400 Content-Length: 0 Connection: keep-alive HTTP/1.1 200 OK Cache-control: no-cache="set-cookie" Content-Language: en-US Content-Type: text/html;charset=ISO-8859-1 Date: Sun, 10 Mar 2013 11:15:50 GMT Set-Cookie: JSESSIONID=C388A3686885375DACEA19E0969E866F; Path=/ls Set-Cookie: AWSELB=D171A3C314A759266FA0800BD41453A838AAFE90EC88BCF5FA39A459FDD713F494AEF2D49AE57739FF0B04EC5C1F189F5D5895521075CCDA5507BC9B3EF8BE820FBA0C5C60;PATH=/;MAX-AGE=86400 transfer-encoding: chunked Connection: keep-alive Только почему JSESSIONID имеет 2 разных значения ? Добавлено спустя 59 минут 36 секунд: file_get_contents( - возвращает форму для ввода логина как будто на страницу зашли GET-ом Если параметры подключения передать пустыми строками - то все рано возвращает форму для ввода логина, но без сообщений об незаполненных параметрах логина. Похоже, POST не сработал?