background image

PHP 新手上路(十四)

   13.1 生成图像  

  PHP 可以操作处理图像。如果你已经安装了 GD 库,你甚至可以利用 PHP 生成图像。  
<?  
Header("Content-type: image/gif");  
$string=implode($argv," ");  
$im = imagecreatefromgif("images/button1.gif");  
$orange = ImageColorAllocate($im, 220, 210, 60);  
$px = (imagesx($im)-7.5*strlen($string))/2;  
ImageString($im,3,$px,9,$string,$orange);  
ImageGif($im);  
ImageDestroy($im);  
?>  

(译者注:以上代码段缺少注释,请读者参考 PHP Manual 的图像处理函数部分)  

  这段代码在其他页面中通过以下标记<img src="button.php3?text">调用,然后以上的那段 button.php3 代码取得 text 值并在另外
取得的图像文件中加上该值--在以上的代码中该图像文件是 images/button1.gif--最后输出到浏览器。假如你想在表单域中使用图像按钮,但
是又不希望在每次按钮上的文字改变后不得不重新生成新的图像,就可以利用这样简单的方法动态生成图像文件。  

13.2 Cookies  

  PHP 支持基于 HTTP 的 cookies。在需要时你可以像使用一般变量一样方便的使用 cookie。Cookies 是浏览器保存于客户端的一些信息片
段,由此你可以知道是否一台特定 PC 上的任何人都访问过你的站点,浏览者者在你的站点上的踪迹等等。使用 cookies 的典型例子就是对浏
览者偏好的甄别。Cookies 由函数 setcookie()设定。与输出 HTTP 标头的函数 header()一样,setcookie()必须在任何实际内容杯输出到浏览
器之前调用。以下是一个简单例子:  

<?  
if (empty($VisitedBefore))  
{  
// 如果没有设定 cookie,为 cookie 赋上当前时间值  
// 函数中的最后一个参数声明了该 cookie 保存的时间  
// 在这个例子中是 1 年  
// time()函数返回自 1970 年 1 月 1 日以来的以秒数计的时间  
SetCookie("VisitedBefore",time(), time()+(60*60*24*365));  
}  
else  
{  
// 欢迎浏览者再次光临  
echo "Hello there, welcome back<BR>";  
// 读取 cookie 并判断  
if ( (time() - $VisitedBefore) >= "(60*60*24*7)" )  
echo "Why did you take a week to come back. You should be here more often!? ";  
}  
?>