


PHP uses curl to simulate logging into a website with verification code
The demand is like this. You need to log in to a website with a verification code to obtain data. However, it is impossible to record the data manually all the time. I want to do it through automatic collection. The following is the result code from the test! If necessary, please refer to it!
<?php namespace Home\Controller; use Think\Controller; class LoginController extends Controller { protected $cookieName = array('cookie_verify', 'cookie_verify'); protected $cookiePath = '/cookie/'; protected $cookiePathFile = array(); public function index() { $this->display(); } public function _initialize(){ foreach($this->cookieName as $key => $name) { $this->cookiePathFile[] = ROOT_PATH . $this->cookiePath . $this->cookieName[$key] . '_xxx.txt'; } } /** * 登录xxx */ public function xxxLogin() { $username = I('username'); $password = I('password'); $verifyCode = I('verify'); $loginData = array( '__VIEWSTATE' => '/wEPDwUKMTU0MzAzOTU4NmQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFDExvZ2luX1N1Ym1pdL/yae69NsY163G3yuP0lxjz8oXu', //不把参数补全可能会不被响应哦 '__VIEWSTATEGENERATOR' => 'DC42DE27', 'txt_UserName' => $username, 'txt_PWD' => $password, 'txt_VerifyCode' => $verifyCode, 'SMONEY' => 'ABC', 'Login_Submit.x' => '52', 'Login_Submit.y' => '19', ); $getBack = $this->_cookieRequest('http://xxx.com/noLogin.aspx', $loginData); if(preg_match('/<div[^\<div]*?id\s*=\s*[\'\"]{1}div_msg[\'\"]{1}.*?>(.*?)<\/div>/s', $getBack, $match)){ echo 'matched\r\n'; print_r($match); }else{ echo $getBack, '<br />'; $paramsFull = parse_url($getBack); parse_str($paramsFull['query'], $paramsFull['parsedQuery']); if(!empty($paramsFull['parsedQuery']['Warn'])) { $msg = "您好,欢迎来P,请先登录。"; switch ($paramsFull['parsedQuery']['Warn']) { case '2': $msg = '您输入的验证码错误,请重试'; break; case '3': $msg = '该帐号不存在,还没帐号?'; break; case '5': $msg = '账户已注销'; break; case '6': $msg = '密码错误,如果连续错误3次半小时内不能登录!'; break; case '20': $msg = '今日密码错误3次及以上,请于半小时后再来登录!'; break; case '21': $msg = '今日您所在IP的所有帐号密码错误9次以上,请于半小时后再来登录!'; break; case '22': $msg = '登录失败,您所在IP今日登录的帐号过多!'; break; case '23': $msg = '登录失败,验证码失效!'; break; case '32': $msg = '该帐号已经绑定其他PC蛋蛋帐号!'; break; case '33': $msg = '一台电脑一天只能注册一个帐号!'; break; } $this->error($msg, '', 5); }else{ $_SESSION['user_id'] = '123456'; //登录设置session $this->success('登录P网站成功', U('Index/index'), 5); } } } /** * 获取验证码 */ public function getVerifyCode() { $img = $this->_cookieRequest('http://xxx.com/VerifyCode_Login.aspx?id=' . rand(10000,999999), null, true, 1); echo $img; } /** * 删除cookie */ public function clearCookie() { for($i = 0; $i <count($this->cookieName); $i++) { setcookie($this->cookieName[$i], '', time() - 3600); } // unlink($this->cookiePathFile); $this->success('清除cookie成功!'); } /** * 带COOKIE的访问curl * @param $url * @param null $data * @param bool $redirect * @return mixed */ public function _cookieRequest($url, $data = null, $redirect = false, $cookieNum = 0) { $ch = curl_init(); $params[CURLOPT_URL] = $url; //请求url地址 $params[CURLOPT_HEADER] = false; //是否返回响应头信息 $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回 $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向 $params[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1'; if($data) { $params[CURLOPT_POST] = true; $params[CURLOPT_POSTFIELDS] = http_build_query($data); } //判断是否有cookie,有的话直接使用 if (!empty($_COOKIE[$this->cookieName[$cookieNum]]) && is_file($this->cookiePathFile[$cookieNum])) { $params[CURLOPT_COOKIEFILE] = $this->cookiePathFile[$cookieNum]; //这里判断cookie } else { // $cookie_jar = tempnam($cookie_path, 'cookie'); //产生一个cookie文件 $params[CURLOPT_COOKIEJAR] = $this->cookiePathFile[$cookieNum]; //写入cookie信息 setcookie($this->cookieName[$cookieNum], $this->cookiePathFile[$cookieNum], time() + 120); //保存cookie路径 } curl_setopt_array($ch, $params); //传入curl参数 $content = curl_exec($ch); $headers = curl_getinfo($ch); // echo $content; curl_close($ch); if ($content != $headers && $redirect == false){ return $headers["url"]; } return $content; } }
The above introduces how PHP uses curl to simulate logging into a website with a verification code, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

The working principle of cookies involves the server sending cookies, the browser storing cookies, and the browser processing and storing cookies. Detailed introduction: 1. The server sends a cookie, and the server sends an HTTP response header containing the cookie to the browser. This cookie contains some information, such as the user's identity authentication, preferences, or shopping cart contents. After the browser receives this cookie, it will be stored on the user's computer; 2. The browser stores cookies, etc.

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

The effects of clearing cookies include resetting personalization settings and preferences, affecting ad experience, and destroying login status and password remembering functions. Detailed introduction: 1. Reset personalized settings and preferences. If cookies are cleared, the shopping cart will be reset to empty and products need to be re-added. Clearing cookies will also cause the login status on social media platforms to be lost, requiring re-adding. Enter your username and password; 2. It affects the advertising experience. If cookies are cleared, the website will not be able to understand our interests and preferences, and will display irrelevant ads, etc.
