php method to obtain verification code: [
The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.
We often use the verification code function in our daily life, so if How should we implement a verification code function ourselves? Below we give the specific implementation code for your reference!
If you are a beginner, then I strongly recommend that you follow the code Comment step by step instead of copying the code directly.
Create a new captcha.php:
<?php //11>設(shè)置session,必須處于腳本最頂部 session_start(); /*$image = imagecreatetruecolor(100, 30); //1>設(shè)置驗(yàn)證碼圖片大小的函數(shù) //5>設(shè)置驗(yàn)證碼顏色 imagecolorallocate(int im, int red, int green, int blue); $bgcolor = imagecolorallocate($image,255,255,255); //#ffffff //6>區(qū)域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的區(qū)域著色,col 表示欲涂上的顏色 imagefill($image, 0, 0, $bgcolor); //10>設(shè)置變量 $captcha_code = "";*/ //7>生成隨機(jī)數(shù)字 for($i=0;$i<4;$i++){ //設(shè)置字體大小 $fontsize = 6; //設(shè)置字體顏色,隨機(jī)顏色 $fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //0-120深顏色 //設(shè)置數(shù)字 $fontcontent = rand(0,9); //10>.=連續(xù)定義變量 $captcha_code .= $fontcontent; //設(shè)置坐標(biāo) $x = ($i*100/4)+rand(5,10); $y = rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } //10>存到session $_SESSION['authcode'] = $captcha_code; //8>增加干擾元素,設(shè)置雪花點(diǎn) for($i=0;$i<200;$i++){ //設(shè)置點(diǎn)的顏色,50-200顏色比數(shù)字淺,不干擾閱讀 $pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200)); //imagesetpixel — 畫一個單一像素 imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor); } //9>增加干擾元素,設(shè)置橫線 for($i=0;$i<4;$i++){ //設(shè)置線的顏色 $linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220)); //設(shè)置線,兩點(diǎn)一線 imageline($image,rand(1,99), rand(1,29),rand(1,99), rand(1,29),$linecolor); } //2>設(shè)置頭部,image/png header('Content-Type: image/png'); //3>imagepng() 建立png圖形函數(shù) imagepng($image); //4>imagedestroy() 結(jié)束圖形函數(shù) 銷毀$image imagedestroy($image);
Then comes the code for the static page: index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標(biāo)題文檔</title> </head> <body> <form method="post" action="./form.php"> <p>驗(yàn)證碼: <img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/894/977/896/1632296083303197.png" class="lazy" id="captcha_img" border='1' src='./captcha.php?r=echo rand(); ? alt="How to obtain verification code in php" >' style="max-width:90%" /> <a href="javascript:void(0)" onclick="document.getElementById('captcha_img').src='./captcha.php?r='+Math.random()">換一個?</a> </p> <P>請輸入驗(yàn)證碼:<input type="text" name='authcode' value=''/></p> <p><input type='submit' value='提交' style='padding:6px 5px;'/></p> </form> </body> </html>
From index .html, you can see that the submitted form is to form.php, so there is also a judgment form.php code:
<?php header("Content-Type:text/html;charset=utf-8"); //設(shè)置頭部信息 //isset()檢測變量是否設(shè)置 if(isset($_REQUEST['authcode'])){ session_start(); //strtolower()小寫函數(shù) if(strtolower($_REQUEST['authcode'])== $_SESSION['authcode']){ //跳轉(zhuǎn)頁面 echo "<script language=\"javascript\">"; echo "document.location=\"./form.php\""; echo "</script>"; }else{ //提示以及跳轉(zhuǎn)頁面 echo "<script language=\"javascript\">"; echo "alert('輸入錯誤!');"; echo "document.location=\"./form.php\""; echo "</script>"; } exit(); }
The displayed page is as follows:
To add numbers and English verification code, you only need to change 7》 in the captcha.php page. The other two pages do not need to be touched. The code is as follows:
<?php //11>設(shè)置session,必須處于腳本最頂部 session_start(); $image = imagecreatetruecolor(100, 30); //1>設(shè)置驗(yàn)證碼圖片大小的函數(shù) //5>設(shè)置驗(yàn)證碼顏色 imagecolorallocate(int im, int red, int green, int blue); $bgcolor = imagecolorallocate($image,255,255,255); //#ffffff //6>區(qū)域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的區(qū)域著色,col 表示欲涂上的顏色 imagefill($image, 0, 0, $bgcolor); //10>設(shè)置變量 $captcha_code = ""; //7>生成隨機(jī)的字母和數(shù)字 for($i=0;$i<4;$i++){ //設(shè)置字體大小 $fontsize = 8; //設(shè)置字體顏色,隨機(jī)顏色 $fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //0-120深顏色 //設(shè)置需要隨機(jī)取的值,去掉容易出錯的值如0和o $data ='abcdefghigkmnpqrstuvwxy3456789'; //取出值,字符串截取方法 strlen獲取字符串長度 $fontcontent = substr($data, rand(0,strlen($data)),1); //10>.=連續(xù)定義變量 $captcha_code .= $fontcontent; //設(shè)置坐標(biāo) $x = ($i*100/4)+rand(5,10); $y = rand(5,10); imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); } //10>存到session $_SESSION['authcode'] = $captcha_code; //8>增加干擾元素,設(shè)置雪花點(diǎn) for($i=0;$i<200;$i++){ //設(shè)置點(diǎn)的顏色,50-200顏色比數(shù)字淺,不干擾閱讀 $pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200)); //imagesetpixel — 畫一個單一像素 imagesetpixel($image, rand(1,99), rand(1,29), $pointcolor); } //9>增加干擾元素,設(shè)置橫線 for($i=0;$i<4;$i++){ //設(shè)置線的顏色 $linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220)); //設(shè)置線,兩點(diǎn)一線 imageline($image,rand(1,99), rand(1,29),rand(1,99), rand(1,29),$linecolor); } //2>設(shè)置頭部,image/png header('Content-Type: image/png'); //3>imagepng() 建立png圖形函數(shù) imagepng($image); //4>imagedestroy() 結(jié)束圖形函數(shù) 銷毀$image imagedestroy($image);
The displayed page is as follows:
Generate Chinese character verification code. During the operation, a garbled error message is displayed, which cannot be displayed and cannot be resolved. The code is as follows:
php //11>設(shè)置session,必須處于腳本最頂部 session_start(); //1>設(shè)置驗(yàn)證碼圖片大小的函數(shù) $image = imagecreatetruecolor(200, 60); //5>設(shè)置驗(yàn)證碼顏色 imagecolorallocate(int im, int red, int green, int blue); $bgcolor = imagecolorallocate($image,255,255,255); //#ffffff //6>區(qū)域填充 int imagefill(int im, int x, int y, int col) (x,y) 所在的區(qū)域著色,col 表示欲涂上的顏色 imagefill($image, 0, 0, $bgcolor); //7>設(shè)置ttf字體 $fontface = 'FZYTK.TTF'; //7>設(shè)置字庫,實(shí)現(xiàn)簡單的數(shù)字儲備 $str='天地不仁以萬物為芻狗圣人不仁以百姓為芻狗這句經(jīng)常出現(xiàn)在控訴暴君暴政上地殘暴不仁把萬物都當(dāng)成低賤的豬狗來看待而那些高高在上的所謂圣人們也沒兩樣還不是把我們老百姓也當(dāng)成豬狗不如的東西但實(shí)在正取的解讀是地不情感用事對萬物一視同仁圣人不情感用事對百姓一視同仁執(zhí)子之手與子偕老當(dāng)男女主人公含情脈脈看著對方說了句執(zhí)子之手與子偕老女方淚眼朦朧含羞地回一句討厭啦這樣的情節(jié)我們是不是見過很多但是我們來看看這句的原句死生契闊與子成說執(zhí)子之手與子偕老于嗟闊兮不我活兮于嗟洵兮不我信兮意思是說戰(zhàn)士之間的約定說要一起死現(xiàn)在和我約定的人都走了我怎么活啊赤裸裸的兄弟江湖戰(zhàn)友友誼啊形容好基友的基情比男女之間的愛情要合適很多吧'; //str_split()切割字符串為一個數(shù)組,一個中文在utf_8為3個字符 $strdb = str_split($str,3); //>11 $captcha_code = ''; //8>生成隨機(jī)的漢子 for($i=0;$i<4;$i++){ //設(shè)置字體顏色,隨機(jī)顏色 $fontcolor = imagecolorallocate($image, rand(0,120),rand(0,120), rand(0,120)); //0-120深顏色 //隨機(jī)選取中文 $in = rand(0,count($strdb)); $cn = $strdb[$in]; //將中文記錄到將保存到session的字符串中 $captcha_code .= $cn; /*imagettftext (resource $image ,float $size ,float $angle ,int $x ,int $y,int $color, string $fontfile ,string $text ) 幕布 ,尺寸,角度,坐標(biāo),顏色,字體路徑,文本字符串 mt_rand()生成更好的隨機(jī)數(shù),比rand()快四倍*/ imagettftext($image, mt_rand(20,24),mt_rand(-60,60),(40*$i+20),mt_rand(30,35),$fontcolor,$fontface,$cn); } //11>存到session $_SESSION['authcode'] = $captcha_code; //9>增加干擾元素,設(shè)置點(diǎn) for($i=0;$i<200;$i++){ //設(shè)置點(diǎn)的顏色,50-200顏色比數(shù)字淺,不干擾閱讀 $pointcolor = imagecolorallocate($image,rand(50,200), rand(50,200), rand(50,200)); //imagesetpixel — 畫一個單一像素 imagesetpixel($image, rand(1,199), rand(1,59), $pointcolor); } //10>增加干擾元素,設(shè)置線 for($i=0;$i<4;$i++){ //設(shè)置線的顏色 $linecolor = imagecolorallocate($image,rand(80,220), rand(80,220),rand(80,220)); //設(shè)置線,兩點(diǎn)一線 imageline($image,rand(1,199), rand(1,59),rand(1,199), rand(1,59),$linecolor); } //2>設(shè)置頭部,image/png header('Content-Type: image/png'); //3>imagepng() 建立png圖形函數(shù) imagepng($image); //4>imagedestroy() 結(jié)束圖形函數(shù) 銷毀$image imagedestroy($image);
Recommended learning: php training
The above is the detailed content of How to obtain verification code in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w
