Advertisement
Guest User

CAPTCHA PHP

a guest
Jun 16th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.10 KB | None | 0 0
  1. <?php
  2.  
  3. // --- 1. On démarre les sessions
  4. session_start();
  5.  
  6. // --- 2. On créé le captcha aux dimensions 100x35
  7. $captcha = imagecreatetruecolor(100, 35);
  8.  
  9. // --- 3. On sélectionne une image dont on prendra une partie pour l'arrière-plan du captcha
  10. $fond = imagecreatefromjpeg("fond.jpg");
  11.  
  12. // On découpe un rectangle de dimensions 100x35 quelque part au hasard dans l'image choisie
  13. $ix = mt_rand(0,imagesx($fond)-100);
  14. $iy = mt_rand(0,imagesy($fond)-35);
  15.  
  16. // On place le rectangle pixel par pixel sur le captcha (on aura ainsi l'arrière-plan)
  17. for($i=$ix;$i<100+$ix;$i++)
  18. {
  19.   for($y=$iy;$y<35+$iy;$y++)
  20.   {
  21.     $couleur_pixel = imagecolorat($fond,$i,$y);
  22.     $rouge = ($couleur_pixel>>16)&0xFF;
  23.     $vert = ($couleur_pixel>>8)&0xFF;
  24.     $bleu = $couleur_pixel&0xFF;
  25.  
  26.     imagesetpixel($captcha,$i-$ix,$y-$iy,imagecolorallocate($captcha,$rouge,$vert,$bleu));
  27.   }
  28. }
  29.  
  30. // On n'a plus besoin de l'image qui a servi pour le fond, on la supprime
  31. imagedestroy($fond);
  32.  
  33. // --- 4. On créé le texte du captcha au hasard
  34. $texte = random_int(1000,999);
  35.  
  36. // Si votre version de PHP ne supporte pas la fonction random_int, utilisez :
  37. // mt_rand(1000,9999);
  38.  
  39. // Notez que la fonction random_int() est préférable car elle génère du "hasard" cryptographique :
  40. // http://php.net/manual/fr/function.random-int.php
  41.  
  42. // On enregistre le texte dans la session
  43. $_SESSION["texte_captcha"] = $texte;
  44.  
  45. // --- 5. On place le texte sur notre captcha avec des couleurs aléatoires
  46. for($i=0;$i<4;$i++)
  47. {
  48.   $couleur = imagecolorallocate($captcha, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
  49.   imagettftext($captcha, mt_rand(20,25), mt_rand(0,20)-10, 5+$i*22, 30, $couleur, "font.ttf", $texte[$i]);
  50. }
  51.  
  52. // --- 6. Et on applique des filtres sur l'image au hasard
  53. if(mt_rand(0,5)==2) imagefilter($captcha, IMG_FILTER_NEGATE);
  54. if(mt_rand(0,5)==2) imagefilter($captcha, IMG_FILTER_EMBOSS);
  55. if(mt_rand(0,5)==2) imagefilter($captcha, IMG_FILTER_EDGEDETECT);
  56.  
  57.  
  58. // On envoie l'image au navigateur
  59. header('Content-type: image/png');
  60. imagepng($captcha);
  61.  
  62. // On libère les ressources
  63. imagedestroy($captcha);
  64.  
  65. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement