使用PHP Curl实现跨站登录遇阻,请求排查脚本问题
Hey, let's break down the issues in your cURL login script and get it working properly:
Undefined
$postfieldsvariable
You created the$post_login_clientarray with your login credentials, but you never assigned it to$postfields—the variable you're passing toCURLOPT_POSTFIELDS. That means your script is sending empty POST data, which is why the login is failing.Manual
multipart/form-dataheader conflict
When you pass an array toCURLOPT_POSTFIELDS, cURL automatically handles generating the correctmultipart/form-dataheader and boundary string. By manually setting this header, you're overriding cURL's auto-generated one, which causes the server to fail parsing your POST data. Remove that custom header entirely.Unreachable
curl_closecall
You're returning the result ofcurl_execimmediately, which means thecurl_close($login);line never runs. While this won't break the login, it's bad practice—always clean up your cURL resources after use.Optional: SSL certificate verification
If you're testing against a site with a self-signed SSL certificate or your server doesn't have the root CA certs installed, you might need to temporarily disable SSL verification (never do this in production!) to avoid connection errors.
Corrected Script
$post_login_client = array( "account_number" => 1234123, "pin" => 123123, "submit" => "" ); // Initialize cookie file (ensure the directory is writable!) $cookieFile = "cookie-website.txt"; $fp = fopen($cookieFile, "w"); fclose($fp); $login = curl_init(); // Cookie handling curl_setopt($login, CURLOPT_COOKIEJAR, $cookieFile); curl_setopt($login, CURLOPT_COOKIEFILE, $cookieFile); // Basic cURL settings curl_setopt($login, CURLOPT_TIMEOUT, 40); curl_setopt($login, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($login, CURLOPT_URL, "https://secure.website.com/client/login"); curl_setopt($login, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($login, CURLOPT_FOLLOWLOCATION, TRUE); // POST settings curl_setopt($login, CURLOPT_POST, TRUE); curl_setopt($login, CURLOPT_POSTFIELDS, $post_login_client); // Use the correct array variable // Optional: Disable SSL verification (only for testing!) // curl_setopt($login, CURLOPT_SSL_VERIFYPEER, false); // curl_setopt($login, CURLOPT_SSL_VERIFYHOST, false); // Execute and clean up $response = curl_exec($login); curl_close($login); return $response;
A few extra notes:
- Make sure the directory where
cookie-website.txtis stored is writable by your web server. If not, cURL won't be able to save the cookies, and subsequent requests won't be authenticated. - If the target site expects URL-encoded form data instead of multipart, you can use
http_build_query($post_login_client)instead of passing the array directly toCURLOPT_POSTFIELDS.
内容的提问来源于stack exchange,提问作者Azivans

