tag site plugin metadescription manager keywords keys how description php curl

php - site - seo keywords wordpress



código de enrutamiento de inicio de sesión de PHP no funciona como se esperaba (2)

Estás haciendo varias cosas mal:

  1. Está intentando iniciar sesión antes de tener una sesión de cookies, pero el sitio requiere que tenga una sesión de cookies antes de enviar la solicitud de inicio de sesión.

  2. Hay un token CSRF vinculado a su sesión de cookies, aquí llamado, que necesita analizar desde la página de inicio de sesión html y proporcionar con su solicitud de inicio de sesión, que su código no recupera.

  3. Lo más importante es que hay una imagen captcha vinculada a su sesión de cookies que necesita recuperar y resolver, y el texto que necesita adjuntar a su solicitud de inicio de sesión, que su código ignora por completo.

  4. Su solicitud de inicio de sesión necesita el encabezado x-requested-with: XMLHttpRequest , pero su código no agrega ese encabezado.

  5. Su solicitud de inicio de sesión necesita los campos com=account y t=submitLogin en los datos POST, pero su código no los está agregando (intenta agregarlos a su URL, pero se supone que no están en la url , se supone que deben estar en los datos POST, también conocido como su matriz $ postValues, no la url)

Esto es lo que necesitas hacer:

  • Primero haga una solicitud GET normal a la página de inicio de sesión. Esto le dará una identificación de cookie de sesión, el token CSRF y la url a su imagen captcha.
  • Almacene la identificación de la cookie y asegúrese de proporcionarla con todas las demás solicitudes, luego analice el token csrf (está en el html y se ve como <input type="hidden" name="at" value="5aabxxx5dcac0" /> ), y la url para la imagen captcha (es diferente para cada sesión de cookies, así que no la codifique).
  • Luego, obtenga la imagen captcha, resuélvala y agréguelas todas a los datos POST de su solicitud de inicio de sesión, junto con el nombre de usuario, la contraseña, la respuesta captcha, com y t , y agregue el encabezado http x-requested-with: XMLHttpRequest a la solicitud de inicio de sesión también, envíelo a https://www.banggood.com/login.html , ¡entonces debe estar registrado!

Aquí hay una implementación de ejemplo que utiliza hhb_curl para las solicitudes web (es un curl_ wrapper que se ocupa de las cookies, convierte los errores de curl_ silenciosos en RuntimeExceptions, etc.), DOMDocument para analizar el token CSRF y el api de deathbycaptcha.com para romper el captcha.

Ps: el código de ejemplo no funcionará hasta que proporcione un nombre de usuario / contraseña api de deathbycaptcha.com acreditado real en las líneas 6 y 7, también el captcha parece tan simple que creo que romperlo podría automatizarse si está lo suficientemente motivado. ''m no. - edit, parece que mejoraron su captcha desde que escribí eso, ahora parece muy difícil. Además, la cuenta de banggood es solo una cuenta de prueba temporal, no se produce ningún daño por estar comprometida, lo que obviamente sucede cuando publico el nombre de usuario / contraseña aquí)

<?php declare(strict_types = 1); require_once (''hhb_.inc.php''); $banggood_username = ''[email protected]''; $banggood_password = ''[email protected]''; $deathbycaptcha_username = ''?''; $deathbycaptcha_password = ''?''; $hc = new hhb_curl ( '''', true ); $html = $hc->exec ( ''https://www.banggood.com/login.html'' )->getStdOut (); $domd = @DOMDocument::loadHTML ( $html ); $xp = new DOMXPath ( $domd ); $csrf_token = $xp->query ( ''//input[@name="at"]'' )->item ( 0 )->getAttribute ( "value" ); $captcha_image_url = ''https://www.banggood.com/'' . $domd->getElementById ( "get_login_image" )->getAttribute ( "src" ); $captcha_image = $hc->exec ( $captcha_image_url )->getStdOut (); $captcha_answer = deathbycaptcha ( $captcha_image, $deathbycaptcha_username, $deathbycaptcha_password ); $html = $hc->setopt_array ( array ( CURLOPT_POST => 1, CURLOPT_POSTFIELDS => http_build_query ( array ( ''com'' => ''account'', ''t'' => ''submitlogin'', ''email'' => $banggood_username, ''pwd'' => $banggood_password, ''at'' => $csrf_token, ''login_image_code'' => $captcha_answer ) ), CURLOPT_HTTPHEADER => array ( ''x-requested-with: XMLHttpRequest'' ) ) )->exec ()->getStdOut (); var_dump ( // $hc->getStdErr (), $html ); function deathbycaptcha(string $imageBinary, string $apiUsername, string $apiPassword): string { $hc = new hhb_curl ( '''', true ); $response = $hc->setopt_array ( array ( CURLOPT_URL => ''http://api.dbcapi.me/api/captcha'', CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array ( ''Accept: application/json'' ), CURLOPT_POSTFIELDS => array ( ''username'' => $apiUsername, ''password'' => $apiPassword, ''captchafile'' => ''base64:'' . base64_encode ( $imageBinary ) // use base64 because CURLFile requires a file, and i cba with tmpfile() .. but it would save bandwidth. ), CURLOPT_FOLLOWLOCATION => 0 ) )->exec ()->getStdOut (); $response_code = $hc->getinfo ( CURLINFO_HTTP_CODE ); if ($response_code !== 303) { // some error $err = "DeathByCaptcha api retuned /"$response_code/", expected 303, "; switch ($response_code) { case 403 : $err .= " the api username/password was rejected"; break; case 400 : $err .= " we sent an invalid request to the api (maybe the API specs has been updated?)"; break; case 500 : $err .= " the api had an internal server error"; break; case 503 : $err .= " api is temorarily unreachable, try again later"; break; default : { $err .= " unknown error"; break; } } $err .= '' - '' . $response; throw new /RuntimeException ( $err ); } $response = json_decode ( $response, true ); if (! empty ( $response [''text''] ) && $response [''text''] !== ''?'') { return $response [''text'']; // sometimes the answer might be available right away. } $id = $response [''captcha'']; $url = ''http://api.dbcapi.me/api/captcha/'' . urlencode ( $id ); while ( true ) { sleep ( 10 ); // check every 10 seconds $response = $hc->setopt ( CURLOPT_HTTPHEADER, array ( ''Accept: application/json'' ) )->exec ( $url )->getStdOut (); $response = json_decode ( $response, true ); if (! empty ( $response [''text''] ) && $response [''text''] !== ''?'') { return $response [''text'']; } } }

Estoy intentando usar la función de curl en php para iniciar sesión en una página específica. Por favor, compruebe el código de abajo. Me conecto con mi correo electrónico y contraseña en banggood.com y luego me gustaría redirigir a otra página privada pero no funciona como se esperaba. No consigo errores. En mi lugar, me redireccionan a esta página ( https://www.banggood.com/index.php?com=account ) utilizando el siguiente código Después de iniciar sesión, quiero acceder a una página privada donde existen mis pedidos. Cualquier ayuda apreciada.

//The username or email address of the account. define(''EMAIL'', ''[email protected]''); //The password of the account. define(''PASSWORD'', ''mypassword''); //Set a user agent. This basically tells the server that we are using Chrome ;) define(''USER_AGENT'', ''Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.2309.372 Safari/537.36''); //Where our cookie information will be stored (needed for authentication). define(''COOKIE_FILE'', ''cookie.txt''); //URL of the login form. define(''LOGIN_FORM_URL'', ''https://www.banggood.com/login.html''); //Login action URL. Sometimes, this is the same URL as the login form. define(''LOGIN_ACTION_URL'', ''https://www.banggood.com/login.html''); //An associative array that represents the required form fields. //You will need to change the keys / index names to match the name of the form //fields. $postValues = array( ''email'' => EMAIL, ''password'' => PASSWORD ); //Initiate cURL. $curl = curl_init(); //Set the URL that we want to send our POST request to. In this //case, it''s the action URL of the login form. curl_setopt($curl, CURLOPT_URL, LOGIN_ACTION_URL); //Tell cURL that we want to carry out a POST request. curl_setopt($curl, CURLOPT_POST, true); //Set our post fields / date (from the array above). curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postValues)); //We don''t want any HTTPS errors. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //Where our cookie details are saved. This is typically required //for authentication, as the session ID is usually saved in the cookie file. curl_setopt($curl, CURLOPT_COOKIEJAR, COOKIE_FILE); //Sets the user agent. Some websites will attempt to block bot user agents. //Hence the reason I gave it a Chrome user agent. curl_setopt($curl, CURLOPT_USERAGENT, USER_AGENT); //Tells cURL to return the output once the request has been executed. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //Allows us to set the referer header. In this particular case, we are //fooling the server into thinking that we were referred by the login form. curl_setopt($curl, CURLOPT_REFERER, LOGIN_FORM_URL); //Do we want to follow any redirects? curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); //Execute the login request. curl_exec($curl); //Check for errors! if(curl_errno($curl)){ throw new Exception(curl_error($curl)); } //We should be logged in by now. Let''s attempt to access a password protected page curl_setopt($curl, CURLOPT_URL, ''https://www.banggood.com/index.php?com=account&t=ordersList''); //Use the same cookie file. curl_setopt($curl, CURLOPT_COOKIEJAR, COOKIE_FILE); //Use the same user agent, just in case it is used by the server for session validation. curl_setopt($curl, CURLOPT_USERAGENT, USER_AGENT); //We don''t want any HTTPS / SSL errors. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //Execute the GET request and print out the result. curl_exec($curl);


Establezca CURLOPT_FOLLOWLOCATION en 1 o verdadero, también puede necesitar CURLOPT_AUTOREFERER lugar del REFERER estático.

¿Consigues algunas cookies en tu COOKIEJAR (cookie.txt)? Recuerde que el archivo ya debe existir y PHP necesita permisos de escritura.

Si tiene PHP ejecutándose en localhost, entonces una herramienta de red podría ayudar a solucionar el problema, intente con Wireshark o algún software equivalente. Porque tal vez la solicitud todavía se pierda algunos encabezados HTTP importantes como Host