今天使用http://crazymud.iteye.com/blog/452293给出的代码进行PHP生成校验码功能的实现,发现firefox一直提示“图像.......因其本身有错无法显示”的问题,作者也提示了说“如果浏览器显示“图像XXX因其本身有错无法显示”,可尽量去掉文中空格”,但把代码中所有空格都去掉了还是不能显示检验图片。于是深度google,大部分的解决方案也是将“"Content-type: p_w_picpath/PNG");这句代码前使用ob_clean()清除输出,结果一试之下果然成功。现将原http://crazymud.iteye.com/blog/452293作者的代码修改后贴到下面,以备不时之需(使用方法参看原帖):

  1. session_start(); 
  2. session_register("login_check_number");   
  3. //先成生背景,再把生成的验证码放上去 
  4. $img_height=70;//先定义图片的长、宽 
  5. $img_width=25; 
  6. $authnum=''
  7. //生产验证码字符 
  8. $ychar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
  9. $list=explode(",",$ychar); 
  10. for($i=0;$i<4;$i++){ 
  11.     $randnum=rand(0,35); 
  12.     $authnum.=$list[$randnum]; 
  13. //把验证码字符保存到session 
  14. $_SESSION["login_check_number"] = $authnum;   
  15.  
  16. $aimg = p_w_picpathcreate($img_height,$img_width);    //生成图片 
  17. p_w_picpathcolorallocate($aimg, 255,255,255);            //图片底色,ImageColorAllocate第1次定义颜色PHP就认为是底色了 
  18. $black = p_w_picpathcolorallocate($aimg, 0,0,0);        //定义需要的黑色 
  19.  
  20. for ($i=1; $i<=100; $i++) { 
  21.     p_w_picpathstring($aimg,1,mt_rand(1,$img_height),mt_rand(1,$img_width),"@",p_w_picpathcolorallocate($aimg,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255))); 
  22.  
  23. //为了区别于背景,这里的颜色不超过200,上面的不小于200 
  24. for ($i=0;$i<strlen($authnum);$i++){ 
  25.     p_w_picpathstring($aimg, mt_rand(3,5),$i*$img_height/4+mt_rand(2,7),mt_rand(1,$img_width/2-2), $authnum[$i],p_w_picpathcolorallocate($aimg,mt_rand(0,100),mt_rand(0,150),mt_rand(0,200))); 
  26. p_w_picpathrectangle($aimg,0,0,$img_height-1,$img_width-1,$black);//画一个矩形 
  27. ob_clean();  //关键代码,防止出现'图像因其本身有错无法显示'的问题。
  28. Header("Content-type: p_w_picpath/PNG"); 
  29. ImagePNG($aimg);//生成png格式 
  30. ImageDestroy($aimg); 
  31. ?>