2012-04-25 24 views
6

He intentado iniciar sesión en el sitio móvil de barnesandnoble.com con curl y hasta ahora no he tenido suerte. Vuelvo la página sin errores y de forma predeterminada mi correo electrónico en el cuadro de entrada de correo electrónico de la página de inicio de sesión nuevamente (en el formulario devuelto desde print $ result).Cómo iniciar sesión con Curl y SSL y cookies

El mismo código en realidad puede dejar que me vaya en eBay correctamente cambiando el loginUrl para apuntar al inicio de sesión de eBay

La única diferencia es que barnesandnobles es https: // y eBay entrada aproximadamente http: //

Además, creo que Barnes sitio web es asp/aspx, así que no sé cómo que se ocuparía de las galletas y _state diferente

Cualquier ayuda será apreciada como yo estado tratando de depurar este por el pasado 16hrs

también, mi cookie.txt se puede escribir y trabajar

<?php 

$cookie_file_path = "C:/test/cookie.txt"; 
$LOGINURL  = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; 

$agent   = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)"; 

$ch = curl_init(); 

$headers[] = "Accept: */*"; 
$headers[] = "Connection: Keep-Alive"; 
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8"; 


curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   

    curl_setopt($ch, CURLOPT_URL, $LOGINURL); 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 

    $content = curl_exec($ch); 

    curl_close($ch); 

    unset($ch); 




//  NAME="path_state" value="6657403"> 

if(stristr($content,"path_state")){ 
     $array1=explode('path_state" value="',$content); 
     $content1=$array1[1]; 
     $array2=explode('">',$content1); 
     $content2=$array2[0]; 
     } 







$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; 

$POSTFIELDS  = "d_hidPageStamp=V_3_17&hidViewMode=opSignIn&stage=signIn&previousStage=mainStage&path_state=" . $content2 . "&[email protected]&acctPassword=YOURPASSWORD"; 

$reffer  = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; 

$ch = curl_init(); 


$headers[] = "Accept: */*"; 
$headers[] = "Connection: Keep-Alive"; 
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8"; 


curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 



    curl_setopt($ch, CURLOPT_URL, $LOGINURL); 
    curl_setopt($ch, CURLOPT_USERAGENT, $agent); 

    curl_setopt($ch, CURLOPT_POST, 1); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS); 

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_REFERER, $reffer); 
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 

    $result = curl_exec($ch); 

    print $result; 

?> 
+0

estaría cau tious acerca de escribir en el mismo archivo de cookies de múltiples solicitudes simultáneas. – Bruno

Respuesta

15

Aquí está un ejemplo de trabajo que he creado desde el código. Esto utiliza una función getFormFields que escribí para una pregunta similar (primera referencia en la parte inferior de esta publicación) que inicia sesión en el mercado de Android.

Creo que puede haber un par de cosas en tu script que impidieron que el inicio de sesión funcionara. En primer lugar, debe urlencode los parámetros de URL como el correo electrónico y la contraseña en la cadena de publicaciones (cURL no lo hará por usted). En segundo lugar, creo que el valor x utilizado como parte de la URL de inicio de sesión puede ser necesario.

Aquí hay una solución que inicia sesión con éxito. Tenga en cuenta que reutilicé el controlador original cURL. Esto no es necesario, pero si especifica keep-alive, en realidad reutilizará la misma conexión, y también le evita tener que especificar las mismas opciones una y otra vez.

Una vez que tenga las cookies, puede crear un nuevo objeto cURL y especificar el COOKIEFILE y COOKIEJAR y se iniciará la sesión sin realizar los primeros pasos.

<?php 

// options 
$EMAIL   = '[email protected]'; 
$PASSWORD   = 'yourpassword'; 
$cookie_file_path = "/tmp/cookies.txt"; 
$LOGINURL   = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; 
$agent   = "Nokia-Communicator-WWW-Browser/2.0 (Geos 3.0 Nokia-9000i)"; 


// begin script 
$ch = curl_init(); 

// extra headers 
$headers[] = "Accept: */*"; 
$headers[] = "Connection: Keep-Alive"; 

// basic curl options for all requests 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   
curl_setopt($ch, CURLOPT_USERAGENT, $agent); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path); 
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path); 

// set first URL 
curl_setopt($ch, CURLOPT_URL, $LOGINURL); 

// execute session to get cookies and required form inputs 
$content = curl_exec($ch); 

// grab the hidden inputs from the form required to login 
$fields = getFormFields($content); 
$fields['emailAddress'] = $EMAIL; 
$fields['acctPassword'] = $PASSWORD; 

// get x value that is used in the login url 
$x = ''; 
if (preg_match('/op\.asp\?x=(\d+)/i', $content, $match)) { 
    $x = $match[1]; 
} 

//$LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?stage=signIn"; 
    $LOGINURL = "https://cart2.barnesandnoble.com/mobileacct/op.asp?x=$x"; 

// set postfields using what we extracted from the form 
$POSTFIELDS = http_build_query($fields); 

// change URL to login URL 
curl_setopt($ch, CURLOPT_URL, $LOGINURL); 

// set post options 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS); 

// perform login 
$result = curl_exec($ch); 

print $result; 


function getFormFields($data) 
{ 
    if (preg_match('/(<form action="op.*?<\/form>)/is', $data, $matches)) { 
     $inputs = getInputs($matches[1]); 

     return $inputs; 
    } else { 
     die('didnt find login form'); 
    } 
} 

function getInputs($form) 
{ 
    $inputs = array(); 

    $elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches); 

    if ($elements > 0) { 
     for($i = 0; $i < $elements; $i++) { 
      $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]); 

      if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) { 
       $name = $name[1]; 
       $value = ''; 

       if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) { 
        $value = $value[1]; 
       } 

       $inputs[$name] = $value; 
      } 
     } 
    } 

    return $inputs; 
} 

Esto funcionó para mí, espero que te ayude a seguir adelante.

Éstos son algunos otra respuesta cURL Tengo que pueden ayudar a aprender:

+1

Gracias, (muy apreciado) que funcionó. –

+2

De nada, me alegro de que haya ayudado. – drew010

+0

Drew, esta respuesta me ayudó a obtener la respuesta a mi propia pregunta, http://stackoverflow.com/questions/16611362/curl-login-into-ebay-co-uk/16614760#16614760 Espero que no te importe, pero usé algo de tu código. :) –

Cuestiones relacionadas