* 基本图片处理,用于完成图片缩入,水印添加
* 当水印图超过目标图片尺寸时,水印图能自动适应目标图片而缩小
* 水印图可以设置跟背景的合并度
源代码在最后下载。例子:
<?php
//JPG格式
require_once('lib/thumb.class.php');
$t = new ThumbHandler();
// 基本使用
$t->setSrcImg("img/test1.jpg");
$t->setDstImg("tmp/new_test1.jpg");
$t->setDstImgBorder(4,"#dddddd");
// 指定缩放比例
$t->createImg(300,200);
?>
<?php
//GIF格式
require_once('lib/thumb.class.php');
$t = new ThumbHandler();
// 基本使用
$t->setSrcImg("img/test2.gif");
$t->setDstImg("tmp/new_test2.gif");
$t->setDstImgBorder(4,"#dddddd");
// 指定缩放比例
$t->createImg(100,100);
?>
<?php
//PNG格式
require_once('lib/thumb.class.php');
$t = new ThumbHandler();
// 基本使用
$t->setSrcImg("img/test3.png");
$t->setDstImg("tmp/new_test3.png");
$t->setDstImgBorder(4,"#dddddd");
//指定压缩级别(0~9),重要
$t->setImgDisplayQuality(9);
// 指定缩放比例
$t->createImg(50,50);
?>
<?php
//JPG格式
require_once('lib/thumb.class.php');
$t = new ThumbHandler();
// 基本使用
$t->setSrcImg("img/test1.jpg");
$t->setMaskFontColor("#000000");
//设置文字水印
$t->setMaskWord("test");
//指定水印位置
$t->setMaskPosition(4);
$t->setDstImg("tmp/new_test4.jpg");
// 指定缩放比例
$t->createImg(300,280);
?>
<?php
require_once('lib/thumb.class.php');
$t = new ThumbHandler();
$t->setSrcImg("img/test1.jpg");
// 指定字体文件地址
$t->setMaskFont("fonts/TitilliumMaps29L002.otf");
$t->setMaskFontSize(20);
$t->setMaskFontColor("#000000");
$t->setMaskWord("hello world");
//设置水印横向偏移
$t->setMaskOffsetX(50);
//设置水印纵向偏移
$t->setMaskOffsetY(55);
//设置文字合并程度
$t->setMaskTxtPct(20);
//设置缩略图边框
$t->setDstImg("tmp/new_test5.jpg");
$t->setDstImgBorder(10,"#dddddd");
$t->createImg(300,200);
?>
<?php
// 自动裁切:
// 程序会按照图片的尺寸从中部裁切最大的正方形,并按目标尺寸进行缩略
require_once ('lib/thumb.class.php');
$t = new ThumbHandler ();
$t->setSrcImg ( "img/test1.jpg" );
$t->setCutType ( 1 ); //这一句就OK了
$t->setDstImg ( "tmp/new_test6.jpg" );
$t->createImg ( 300, 200 );
?>
<?php
//手工裁切:
// 程序会按照指定的位置从源图上取图
require_once ('lib/thumb.class.php');
$t = new ThumbHandler ();
$t->setSrcImg ( "img/test1.jpg" );
$t->setCutType ( 2 ); //指明为手工裁切
$t->setSrcCutPosition ( 100, 100 ); // 源图起点坐标
$t->setRectangleCut ( 300, 200 ); // 裁切尺寸
$t->setDstImg ( "tmp/new_test7.jpg" );
$t->createImg ( 300, 200 );
?>
下载源代码
PS:补充一些关于网络图片的一些基础知识
2012年6月18日星期一
图片延迟加载 jQuery插件
图片延迟加载 - 前端开发技能必备系列
在网上经常会看到一些很长的网页会延迟加载其中的图片,我认为这是一种按需分配的做法,网页只为那些想继续浏览网页的人加载后面的图片,在不影响用户体验的前提下,最大程度地减少服务器负担和流量。目前,主要的购物网站都采用了这种加载方式。今天在一个网友的站里发现一个图片延迟加载的插件,很好用,在这里介绍一下。
先介绍一下图片延迟加载原理。我们需要先将图片的真实地址保存在一个自定义的属性中(属性名任你发挥吧,这里我用的是lazy-src),而图片的src属性中用一个占位图片来替代,这个占位图片当然是越小越好,它基本上只干活、不露面。
<img src="images/placeholder.png" lazy-src="images/realimg.jpg" alt="" /> <!-- 如果浏览器禁用了js,我们也不能不让网页显示图片撒,所以最好是加上下面一句备用代码 --> <noscript><img src="images/realimg.jpg" alt="" /></noscript>
首先。页面开始加载时浏览器会获取所有图片在当前页面中的位置并缓存(获取offset的值时,页面的reflow会被引发),计算出可视区域,当图片的位置出现在可视区域中,利用js动态地将图片标签中的src值替换成图片真实的地址,这时,刚刚出现在可视区域的图片便开始加载。
其次。当用户向下滚动页面时,通过js再次计算是否有图片初次出现可视区域内,如果有,刚对这些图片的src值进行替换,并开始加载真实图片。为了避免重复操作引起的内存泄漏,需要在全部图片加载完后,卸载掉相应的触发事件。
最后。本文是将整个窗口看成是一个大容器,如果愿意,也可以在页面中设置一个小容器,在小容器中也同样可以实现图片的延迟加载。原理虽然简单,但是应用是多样的。
从下面的地址可以看到图片延迟加载的演示,不过尽量使用相应的工具(firebug、Fiddler2)监测图片延迟加载的效果。
http://www.threesnow.com/code/091/
http://www.threesnow.com/code/091/
图片延迟加载插件的代码如下:
图片延迟加载插件代码(function( $ ){ $.fn.imglazyload = function( options ){ var o = $.extend({ attr : 'lazy-src', container : window, event : 'scroll', fadeIn : false, threshold : 0, vertical : true }, options ), event = o.event, vertical = o.vertical, container = $( o.container ), threshold = o.threshold, // 将jQuery对象转换成DOM数组便于操作 elems = $.makeArray( $(this) ), dataName = 'imglazyload_offset', OFFSET = vertical ? 'top' : 'left', SCROLL = vertical ? 'scrollTop' : 'scrollLeft', winSize = vertical ? container.height() : container.width(), scrollCoord = container[ SCROLL ](), docSize = winSize + scrollCoord; // 延迟加载的触发器 var trigger = { init : function( coord ){ return coord >= scrollCoord && coord <= ( docSize + threshold ); }, scroll : function( coord ){ var scrollCoord = container[ SCROLL ](); return coord >= scrollCoord && coord <= ( winSize + scrollCoord + threshold ); }, resize : function( coord ){ var scrollCoord = container[ SCROLL ](), winSize = vertical ? container.height() : container.width(); return coord >= scrollCoord && coord <= ( winSize + scrollCoord + threshold ); } }; var loader = function( triggerElem, event ){ var i = 0, isCustom = false, isTrigger, coord, elem, $elem, lazySrc; // 自定义事件只要触发即可,无需再判断 if( event ){ if( event !== 'scroll' && event !== 'resize' ){ isCustom = true; } } else{ event = 'init'; } for( ; i < elems.length; i++ ){ isTrigger = false; elem = elems[i]; $elem = $( elem ); lazySrc = $elem.attr( o.attr ); if( !lazySrc || elem.src === lazySrc ){ continue; } // 先从缓存获取offset值,缓存中没有才获取计算值, // 将计算值缓存,避免重复获取引起的reflow coord = $elem.data( dataName ); if( coord === undefined ){ coord = $elem.offset()[ OFFSET ]; $elem.data( dataName, coord ); } isTrigger = isCustom || trigger[ event ]( coord ); if( isTrigger ){ // 加载图片 elem.src = lazySrc; if( o.fadeIn ){ $elem.hide().fadeIn(); } // 移除缓存 $elem.removeData( dataName ); // 从DOM数组中移除该DOM elems.splice( i--, 1 ); } } // 所有的图片加载完后卸载触发事件 if( !elems.length ){ if( triggerElem ){ triggerElem.unbind( event, fire ); } else{ container.unbind( o.event, fire ); } $( window ).unbind( 'resize', fire ); elems = null; } }; var fire = function( e ){ loader( $(this), e.type ); }; // 绑定事件 container = event === 'scroll' ? container : $( this ); container.bind( event, fire ); $( window ).bind( 'resize', fire ); // 初始化 loader(); return this; }; })( jQuery );
有关这个的插件API说明如下:
attr string
存放图片真实地址的属性名,与HTML对应,默认是lazy-src。
container dom & selector
默认的容器为window,可自定义容器。
event stirng
触发图片加载的事件类型,默认为window.onscroll事件
fadeIn boolean
是否使用jQuery的fadeIn效果来显示,默认是false。
threshold number
页面滚动到离图片还有指定距离的时候就进行加载,默认是0。
vertical boolean
是否横向滚动,默认为true(纵向)。
loadScript(增强版的功能) boolean
是否无阻塞加载javascript广告图片,默认为false。
存放图片真实地址的属性名,与HTML对应,默认是lazy-src。
container dom & selector
默认的容器为window,可自定义容器。
event stirng
触发图片加载的事件类型,默认为window.onscroll事件
fadeIn boolean
是否使用jQuery的fadeIn效果来显示,默认是false。
threshold number
页面滚动到离图片还有指定距离的时候就进行加载,默认是0。
vertical boolean
是否横向滚动,默认为true(纵向)。
loadScript(增强版的功能) boolean
是否无阻塞加载javascript广告图片,默认为false。
2012年5月29日星期二
MySQL无法远程连接主机
今天在做项目想用局域网的IP连接本地MySQL的时候,总是提示以下的信息:
ERROR 1045 (28000): Access denied for user 'root'@'fujiayl-PC' (using password:NO)
搞了半天,终于找到解决方法:用phpMyAdmin添加多以下一条记录就可以了
ERROR 1045 (28000): Access denied for user 'root'@'fujiayl-PC' (using password:NO)
搞了半天,终于找到解决方法:用phpMyAdmin添加多以下一条记录就可以了
2012年5月26日星期六
PHP XML 的 DOMDocument 读取功能
1、XML常识知识补充
XML(eXtensible Markup Language)即可扩展标记语言,它与HTML一样,都是属于SGML标准通用标记语言。XML是Internet环境中跨平台的,依赖于内容的技术,是独立于软件和硬件的信息传输工具。不同的应用程序都能够访问您的数据,不仅仅在 HTML 页中,也可以从 XML 数据源中进行访问。
XML与HTML的设计区别是:XML 被设计为传输和存储数据,其焦点是数据的内容, 旨在传输信息 。HTML 被设计用来显示数据,其焦点是数据的外观,旨在显示信息。
更多关于XML的资源访问: http://www.w3school.com.cn/x.asp
2、什么是DOM、什么是PHP DOM XML解析
DOM (Document Object Model,文档对象模型)定义了访问和操作文档的标准方法。使用DOM,开发人员可以创建XML或HTML文档,操作它们的结果,增加、修改和删除文档 元素及内容。可以从任何编程语言访问DOM,本文使用PHP 5 DOM扩展,它是PHP核心的一部分,因此除了PHP外,不需要安装其它软件。
根据 DOM,XML 文档中的每个成分都是一个节点。
DOM 是这样规定的:
DOM 是这样规定的:
- 整个文档是一个文档节点
- 每个 XML 标签是一个元素节点
- 包含在 XML 元素中的文本是文本节点
- 每一个 XML 属性是一个属性节点
- 注释属于注释节点
DOM树节点在PHP中的实现方法如下所示:
- Document节点 -- 表示DOMDocument接口
- Element节点 -- 表示DOMElement接口
- Attribute节点 -- 表示DOMAttr接口
- Comment节点 -- 表示DOMComment接口
- Text节点 -- 表示DOMText接口
3、使用PHP DOM 读取一个XML
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book>
<title>PHP100中文网</title>
</book>
</bookstore>
============php==============
$doc = new DOMDocument();
$doc->load('book.xml');$books = $doc->getElementsByTagName( "book" );
$title = $doc->getElementsByTagName( “title" );
echo $title >item(0)->nodeValue;
PHP通过Socket发送邮件
本文主要探讨的是发送邮件底层的技术原理,然后通过PHP的Socket来发送邮件。
首先你有必要先了解以下相关协议
在PHP中发送邮件是很简单的,可以通过系统自带的mail()函数直接发送,但是用mail()函数需要类似sendmail这样的组件支持,即系统要在php.ini配置SMTP服务器的相关信息才能发送成功,设置起来有点麻烦,移植性比较差。
发送邮件主要是通过SMTP协议来传输的,SMTP是 TCP/IP 协议的一种实现,负责把邮件发送到另一台计算机。
我们知道,计算机之间的通信都是基于TCP/IP协议的。我们平时用浏览器浏览网页时,也是使用 TCP/IP 来连接因特网的。 浏览器使用 TCP/IP 来访问因特网服务器,服务器使用 TCP/IP 向浏览器传回 HTML。同样,电子邮件程序必须使用 TCP/IP 来连接因特网,这样才能收发邮件。
即PHP只是充当一个客户端的角色,你用mail()函数发送邮件,只是相当于向SMTP服务器发送了一个命令,具体的发送过程还是要靠SMTP服务器来实现。
如果你没有自己的SMTP服务器,要想发送邮件,就必须用第三方的SMTP服务器,这时,mail()函数根本就没有用了,我们必须通过socket方式来发送邮件。
resource fsockopen ( string target [, int port [, int &errno [, string &errstr [, float timeout]]]] )
这里由于要使用SMTP协议,所以端口号为25。在打开连接成功后,会返回一个socket句柄,使用它就可以象使用文件句柄一样的。可使用的操作有fputs(),fgets(),feof(),fclose()。
在socket连接过程中,会返回以下相关信息。
220 服务就绪(在socket连接成功时,会返回此信息)
221 正在处理
250 请求邮件动作正确,
354 开始发送数据,结束以 .
500 语法错误,命令不能识别
550 命令不能执行,邮箱无效
552 中断处理:用户超出文件空间
还好网上已经有大牛把这样的程序给写出来了。我们直接调用就行。以下是一个邮件类文件,功能很强悍,移植性好又易用。把它命名为 email.class.php
<?php
class smtp {
/* Public Variables */
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
/* Private Variables */
var $sock;
/* Constractor */
function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass) {
$this->debug = FALSE;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 30; //is used in fsockopen()
#
$this->auth = $auth; //auth
$this->user = $user;
$this->pass = $pass;
#
$this->host_name = "localhost"; //is used in HELO command
$this->log_file = "";
$this->sock = FALSE;
}
/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") {
$mail_from = $this->get_address ( $this->strip_comment ( $from ) );
$body = ereg_replace ( "(^|(\r\n))(\\.)", "\\1.\\3", $body );
$header .= "MIME-Version:1.0\r\n";
if ($mailtype == "HTML") {
$header .= "Content-Type:text/html\r\n";
}
$header .= "To: " . $to . "\r\n";
if ($cc != "") {
$header .= "Cc: " . $cc . "\r\n";
}
$header .= "From: $from<" . $from . ">\r\n";
$header .= "Subject: " . $subject . "\r\n";
$header .= $additional_headers;
$header .= "Date: " . date ( "r" ) . "\r\n";
$header .= "X-Mailer:By Redhat (PHP/" . phpversion () . ")\r\n";
list ( $msec, $sec ) = explode ( " ", microtime () );
$header .= "Message-ID: <" . date ( "YmdHis", $sec ) . "." . ($msec * 1000000) . "." . $mail_from . ">\r\n";
$TO = explode ( ",", $this->strip_comment ( $to ) );
if ($cc != "") {
$TO = array_merge ( $TO, explode ( ",", $this->strip_comment ( $cc ) ) );
}
if ($bcc != "") {
$TO = array_merge ( $TO, explode ( ",", $this->strip_comment ( $bcc ) ) );
}
$sent = TRUE;
foreach ( $TO as $rcpt_to ) {
$rcpt_to = $this->get_address ( $rcpt_to );
if (! $this->smtp_sockopen ( $rcpt_to )) {
$this->log_write ( "Error: Cannot send email to " . $rcpt_to . "\n" );
$sent = FALSE;
continue;
}
if ($this->smtp_send ( $this->host_name, $mail_from, $rcpt_to, $header, $body )) {
$this->log_write ( "E-mail has been sent to <" . $rcpt_to . ">\n" );
} else {
$this->log_write ( "Error: Cannot send email to <" . $rcpt_to . ">\n" );
$sent = FALSE;
}
fclose ( $this->sock );
$this->log_write ( "Disconnected from remote host\n" );
}
echo "<br>";
echo $header;
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "") {
if (! $this->smtp_putcmd ( "HELO", $helo )) {
return $this->smtp_error ( "sending HELO command" );
}
#auth
if ($this->auth) {
if (! $this->smtp_putcmd ( "AUTH LOGIN", base64_encode ( $this->user ) )) {
return $this->smtp_error ( "sending HELO command" );
}
if (! $this->smtp_putcmd ( "", base64_encode ( $this->pass ) )) {
return $this->smtp_error ( "sending HELO command" );
}
}
#
if (! $this->smtp_putcmd ( "MAIL", "FROM:<" . $from . ">" )) {
return $this->smtp_error ( "sending MAIL FROM command" );
}
if (! $this->smtp_putcmd ( "RCPT", "TO:<" . $to . ">" )) {
return $this->smtp_error ( "sending RCPT TO command" );
}
if (! $this->smtp_putcmd ( "DATA" )) {
return $this->smtp_error ( "sending DATA command" );
}
if (! $this->smtp_message ( $header, $body )) {
return $this->smtp_error ( "sending message" );
}
if (! $this->smtp_eom ()) {
return $this->smtp_error ( "sending <CR><LF>.<CR><LF> [EOM]" );
}
if (! $this->smtp_putcmd ( "QUIT" )) {
return $this->smtp_error ( "sending QUIT command" );
}
return TRUE;
}
function smtp_sockopen($address) {
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx ( $address );
} else {
return $this->smtp_sockopen_relay ();
}
}
function smtp_sockopen_relay() {
$this->log_write ( "Trying to " . $this->relay_host . ":" . $this->smtp_port . "\n" );
$this->sock = @fsockopen ( $this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out );
if (! ($this->sock && $this->smtp_ok ())) {
$this->log_write ( "Error: Cannot connenct to relay host " . $this->relay_host . "\n" );
$this->log_write ( "Error: " . $errstr . " (" . $errno . ")\n" );
return FALSE;
}
$this->log_write ( "Connected to relay host " . $this->relay_host . "\n" );
return TRUE;
;
}
function smtp_sockopen_mx($address) {
$domain = ereg_replace ( "^.+@([^@]+)$", "\\1", $address );
if (! @getmxrr ( $domain, $MXHOSTS )) {
$this->log_write ( "Error: Cannot resolve MX \"" . $domain . "\"\n" );
return FALSE;
}
foreach ( $MXHOSTS as $host ) {
$this->log_write ( "Trying to " . $host . ":" . $this->smtp_port . "\n" );
$this->sock = @fsockopen ( $host, $this->smtp_port, $errno, $errstr, $this->time_out );
if (! ($this->sock && $this->smtp_ok ())) {
$this->log_write ( "Warning: Cannot connect to mx host " . $host . "\n" );
$this->log_write ( "Error: " . $errstr . " (" . $errno . ")\n" );
continue;
}
$this->log_write ( "Connected to mx host " . $host . "\n" );
return TRUE;
}
$this->log_write ( "Error: Cannot connect to any mx hosts (" . implode ( ", ", $MXHOSTS ) . ")\n" );
return FALSE;
}
function smtp_message($header, $body) {
fputs ( $this->sock, $header . "\r\n" . $body );
$this->smtp_debug ( "> " . str_replace ( "\r\n", "\n" . "> ", $header . "\n> " . $body . "\n> " ) );
return TRUE;
}
function smtp_eom() {
fputs ( $this->sock, "\r\n.\r\n" );
$this->smtp_debug ( ". [EOM]\n" );
return $this->smtp_ok ();
}
function smtp_ok() {
$response = str_replace ( "\r\n", "", fgets ( $this->sock, 512 ) );
$this->smtp_debug ( $response . "\n" );
if (! ereg ( "^[23]", $response )) {
fputs ( $this->sock, "QUIT\r\n" );
fgets ( $this->sock, 512 );
$this->log_write ( "Error: Remote host returned \"" . $response . "\"\n" );
return FALSE;
}
return TRUE;
}
function smtp_putcmd($cmd, $arg = "") {
if ($arg != "") {
if ($cmd == "")
$cmd = $arg;
else
$cmd = $cmd . " " . $arg;
}
fputs ( $this->sock, $cmd . "\r\n" );
$this->smtp_debug ( "> " . $cmd . "\n" );
return $this->smtp_ok ();
}
function smtp_error($string) {
$this->log_write ( "Error: Error occurred while " . $string . ".\n" );
return FALSE;
}
function log_write($message) {
$this->smtp_debug ( $message );
if ($this->log_file == "") {
return TRUE;
}
$message = date ( "M d H:i:s " ) . get_current_user () . "[" . getmypid () . "]: " . $message;
if (! @file_exists ( $this->log_file ) || ! ($fp = @fopen ( $this->log_file, "a" ))) {
$this->smtp_debug ( "Warning: Cannot open log file \"" . $this->log_file . "\"\n" );
return FALSE;
}
flock ( $fp, LOCK_EX );
fputs ( $fp, $message );
fclose ( $fp );
return TRUE;
}
function strip_comment($address) {
$comment = "\\([^()]*\\)";
while ( ereg ( $comment, $address ) ) {
$address = ereg_replace ( $comment, "", $address );
}
return $address;
}
function get_address($address) {
$address = ereg_replace ( "([ \t\r\n])+", "", $address );
$address = ereg_replace ( "^.*<(.+)>.*$", "\\1", $address );
return $address;
}
function smtp_debug($message) {
if ($this->debug) {
echo $message . "<br>";
}
}
function get_attach_type($image_tag) { //
$filedata = array ();
$img_file_con = fopen ( $image_tag, "r" );
unset ( $image_data );
while ( $tem_buffer = AddSlashes ( fread ( $img_file_con, filesize ( $image_tag ) ) ) )
$image_data .= $tem_buffer;
fclose ( $img_file_con );
$filedata ['context'] = $image_data;
$filedata ['filename'] = basename ( $image_tag );
$extension = substr ( $image_tag, strrpos ( $image_tag, "." ), strlen ( $image_tag ) - strrpos ( $image_tag, "." ) );
switch ($extension) {
case ".gif" :
$filedata ['type'] = "image/gif";
break;
case ".gz" :
$filedata ['type'] = "application/x-gzip";
break;
case ".htm" :
$filedata ['type'] = "text/html";
break;
case ".html" :
$filedata ['type'] = "text/html";
break;
case ".jpg" :
$filedata ['type'] = "image/jpeg";
break;
case ".tar" :
$filedata ['type'] = "application/x-tar";
break;
case ".txt" :
$filedata ['type'] = "text/plain";
break;
case ".zip" :
$filedata ['type'] = "application/zip";
break;
default :
$filedata ['type'] = "application/octet-stream";
break;
}
return $filedata;
}
}
?>
例子说明
你可以到163申请一个邮箱,把下面的相关配置改一下即可运行。
<?php
require_once ('email.class.php');
$smtpserver = "smtp.163.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "";//SMTP服务器的用户邮箱
$smtpemailto = "";//发送给谁
$smtpuser = "";//SMTP服务器的用户帐号
$smtppass = "";//SMTP服务器的用户密码
$mailsubject = "PHP100测试邮件系统";//邮件主题
$mailbody = "<h1> 这是一个测试程序 </h1>";//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = false;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>
首先你有必要先了解以下相关协议
在PHP中发送邮件是很简单的,可以通过系统自带的mail()函数直接发送,但是用mail()函数需要类似sendmail这样的组件支持,即系统要在php.ini配置SMTP服务器的相关信息才能发送成功,设置起来有点麻烦,移植性比较差。
![]() |
| php.ini中SMTP的配置 |
发送邮件主要是通过SMTP协议来传输的,SMTP是 TCP/IP 协议的一种实现,负责把邮件发送到另一台计算机。
我们知道,计算机之间的通信都是基于TCP/IP协议的。我们平时用浏览器浏览网页时,也是使用 TCP/IP 来连接因特网的。 浏览器使用 TCP/IP 来访问因特网服务器,服务器使用 TCP/IP 向浏览器传回 HTML。同样,电子邮件程序必须使用 TCP/IP 来连接因特网,这样才能收发邮件。
即PHP只是充当一个客户端的角色,你用mail()函数发送邮件,只是相当于向SMTP服务器发送了一个命令,具体的发送过程还是要靠SMTP服务器来实现。
如果你没有自己的SMTP服务器,要想发送邮件,就必须用第三方的SMTP服务器,这时,mail()函数根本就没有用了,我们必须通过socket方式来发送邮件。
通过socket方式发送原理
使用fsockopen函数打开一个Internet连接
在socket连接过程中,会返回以下相关信息。
221 正在处理
250 请求邮件动作正确,
354 开始发送数据,结束以 .
500 语法错误,命令不能识别
550 命令不能执行,邮箱无效
552 中断处理:用户超出文件空间
<?php
class smtp {
/* Public Variables */
var $smtp_port;
var $time_out;
var $host_name;
var $log_file;
var $relay_host;
var $debug;
var $auth;
var $user;
var $pass;
/* Private Variables */
var $sock;
/* Constractor */
function smtp($relay_host = "", $smtp_port = 25, $auth = false, $user, $pass) {
$this->debug = FALSE;
$this->smtp_port = $smtp_port;
$this->relay_host = $relay_host;
$this->time_out = 30; //is used in fsockopen()
#
$this->auth = $auth; //auth
$this->user = $user;
$this->pass = $pass;
#
$this->host_name = "localhost"; //is used in HELO command
$this->log_file = "";
$this->sock = FALSE;
}
/* Main Function */
function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "") {
$mail_from = $this->get_address ( $this->strip_comment ( $from ) );
$body = ereg_replace ( "(^|(\r\n))(\\.)", "\\1.\\3", $body );
$header .= "MIME-Version:1.0\r\n";
if ($mailtype == "HTML") {
$header .= "Content-Type:text/html\r\n";
}
$header .= "To: " . $to . "\r\n";
if ($cc != "") {
$header .= "Cc: " . $cc . "\r\n";
}
$header .= "From: $from<" . $from . ">\r\n";
$header .= "Subject: " . $subject . "\r\n";
$header .= $additional_headers;
$header .= "Date: " . date ( "r" ) . "\r\n";
$header .= "X-Mailer:By Redhat (PHP/" . phpversion () . ")\r\n";
list ( $msec, $sec ) = explode ( " ", microtime () );
$header .= "Message-ID: <" . date ( "YmdHis", $sec ) . "." . ($msec * 1000000) . "." . $mail_from . ">\r\n";
$TO = explode ( ",", $this->strip_comment ( $to ) );
if ($cc != "") {
$TO = array_merge ( $TO, explode ( ",", $this->strip_comment ( $cc ) ) );
}
if ($bcc != "") {
$TO = array_merge ( $TO, explode ( ",", $this->strip_comment ( $bcc ) ) );
}
$sent = TRUE;
foreach ( $TO as $rcpt_to ) {
$rcpt_to = $this->get_address ( $rcpt_to );
if (! $this->smtp_sockopen ( $rcpt_to )) {
$this->log_write ( "Error: Cannot send email to " . $rcpt_to . "\n" );
$sent = FALSE;
continue;
}
if ($this->smtp_send ( $this->host_name, $mail_from, $rcpt_to, $header, $body )) {
$this->log_write ( "E-mail has been sent to <" . $rcpt_to . ">\n" );
} else {
$this->log_write ( "Error: Cannot send email to <" . $rcpt_to . ">\n" );
$sent = FALSE;
}
fclose ( $this->sock );
$this->log_write ( "Disconnected from remote host\n" );
}
echo "<br>";
echo $header;
return $sent;
}
/* Private Functions */
function smtp_send($helo, $from, $to, $header, $body = "") {
if (! $this->smtp_putcmd ( "HELO", $helo )) {
return $this->smtp_error ( "sending HELO command" );
}
#auth
if ($this->auth) {
if (! $this->smtp_putcmd ( "AUTH LOGIN", base64_encode ( $this->user ) )) {
return $this->smtp_error ( "sending HELO command" );
}
if (! $this->smtp_putcmd ( "", base64_encode ( $this->pass ) )) {
return $this->smtp_error ( "sending HELO command" );
}
}
#
if (! $this->smtp_putcmd ( "MAIL", "FROM:<" . $from . ">" )) {
return $this->smtp_error ( "sending MAIL FROM command" );
}
if (! $this->smtp_putcmd ( "RCPT", "TO:<" . $to . ">" )) {
return $this->smtp_error ( "sending RCPT TO command" );
}
if (! $this->smtp_putcmd ( "DATA" )) {
return $this->smtp_error ( "sending DATA command" );
}
if (! $this->smtp_message ( $header, $body )) {
return $this->smtp_error ( "sending message" );
}
if (! $this->smtp_eom ()) {
return $this->smtp_error ( "sending <CR><LF>.<CR><LF> [EOM]" );
}
if (! $this->smtp_putcmd ( "QUIT" )) {
return $this->smtp_error ( "sending QUIT command" );
}
return TRUE;
}
function smtp_sockopen($address) {
if ($this->relay_host == "") {
return $this->smtp_sockopen_mx ( $address );
} else {
return $this->smtp_sockopen_relay ();
}
}
function smtp_sockopen_relay() {
$this->log_write ( "Trying to " . $this->relay_host . ":" . $this->smtp_port . "\n" );
$this->sock = @fsockopen ( $this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out );
if (! ($this->sock && $this->smtp_ok ())) {
$this->log_write ( "Error: Cannot connenct to relay host " . $this->relay_host . "\n" );
$this->log_write ( "Error: " . $errstr . " (" . $errno . ")\n" );
return FALSE;
}
$this->log_write ( "Connected to relay host " . $this->relay_host . "\n" );
return TRUE;
;
}
function smtp_sockopen_mx($address) {
$domain = ereg_replace ( "^.+@([^@]+)$", "\\1", $address );
if (! @getmxrr ( $domain, $MXHOSTS )) {
$this->log_write ( "Error: Cannot resolve MX \"" . $domain . "\"\n" );
return FALSE;
}
foreach ( $MXHOSTS as $host ) {
$this->log_write ( "Trying to " . $host . ":" . $this->smtp_port . "\n" );
$this->sock = @fsockopen ( $host, $this->smtp_port, $errno, $errstr, $this->time_out );
if (! ($this->sock && $this->smtp_ok ())) {
$this->log_write ( "Warning: Cannot connect to mx host " . $host . "\n" );
$this->log_write ( "Error: " . $errstr . " (" . $errno . ")\n" );
continue;
}
$this->log_write ( "Connected to mx host " . $host . "\n" );
return TRUE;
}
$this->log_write ( "Error: Cannot connect to any mx hosts (" . implode ( ", ", $MXHOSTS ) . ")\n" );
return FALSE;
}
function smtp_message($header, $body) {
fputs ( $this->sock, $header . "\r\n" . $body );
$this->smtp_debug ( "> " . str_replace ( "\r\n", "\n" . "> ", $header . "\n> " . $body . "\n> " ) );
return TRUE;
}
function smtp_eom() {
fputs ( $this->sock, "\r\n.\r\n" );
$this->smtp_debug ( ". [EOM]\n" );
return $this->smtp_ok ();
}
function smtp_ok() {
$response = str_replace ( "\r\n", "", fgets ( $this->sock, 512 ) );
$this->smtp_debug ( $response . "\n" );
if (! ereg ( "^[23]", $response )) {
fputs ( $this->sock, "QUIT\r\n" );
fgets ( $this->sock, 512 );
$this->log_write ( "Error: Remote host returned \"" . $response . "\"\n" );
return FALSE;
}
return TRUE;
}
function smtp_putcmd($cmd, $arg = "") {
if ($arg != "") {
if ($cmd == "")
$cmd = $arg;
else
$cmd = $cmd . " " . $arg;
}
fputs ( $this->sock, $cmd . "\r\n" );
$this->smtp_debug ( "> " . $cmd . "\n" );
return $this->smtp_ok ();
}
function smtp_error($string) {
$this->log_write ( "Error: Error occurred while " . $string . ".\n" );
return FALSE;
}
function log_write($message) {
$this->smtp_debug ( $message );
if ($this->log_file == "") {
return TRUE;
}
$message = date ( "M d H:i:s " ) . get_current_user () . "[" . getmypid () . "]: " . $message;
if (! @file_exists ( $this->log_file ) || ! ($fp = @fopen ( $this->log_file, "a" ))) {
$this->smtp_debug ( "Warning: Cannot open log file \"" . $this->log_file . "\"\n" );
return FALSE;
}
flock ( $fp, LOCK_EX );
fputs ( $fp, $message );
fclose ( $fp );
return TRUE;
}
function strip_comment($address) {
$comment = "\\([^()]*\\)";
while ( ereg ( $comment, $address ) ) {
$address = ereg_replace ( $comment, "", $address );
}
return $address;
}
function get_address($address) {
$address = ereg_replace ( "([ \t\r\n])+", "", $address );
$address = ereg_replace ( "^.*<(.+)>.*$", "\\1", $address );
return $address;
}
function smtp_debug($message) {
if ($this->debug) {
echo $message . "<br>";
}
}
function get_attach_type($image_tag) { //
$filedata = array ();
$img_file_con = fopen ( $image_tag, "r" );
unset ( $image_data );
while ( $tem_buffer = AddSlashes ( fread ( $img_file_con, filesize ( $image_tag ) ) ) )
$image_data .= $tem_buffer;
fclose ( $img_file_con );
$filedata ['context'] = $image_data;
$filedata ['filename'] = basename ( $image_tag );
$extension = substr ( $image_tag, strrpos ( $image_tag, "." ), strlen ( $image_tag ) - strrpos ( $image_tag, "." ) );
switch ($extension) {
case ".gif" :
$filedata ['type'] = "image/gif";
break;
case ".gz" :
$filedata ['type'] = "application/x-gzip";
break;
case ".htm" :
$filedata ['type'] = "text/html";
break;
case ".html" :
$filedata ['type'] = "text/html";
break;
case ".jpg" :
$filedata ['type'] = "image/jpeg";
break;
case ".tar" :
$filedata ['type'] = "application/x-tar";
break;
case ".txt" :
$filedata ['type'] = "text/plain";
break;
case ".zip" :
$filedata ['type'] = "application/zip";
break;
default :
$filedata ['type'] = "application/octet-stream";
break;
}
return $filedata;
}
}
?>
你可以到163申请一个邮箱,把下面的相关配置改一下即可运行。
<?php
require_once ('email.class.php');
$smtpserver = "smtp.163.com";//SMTP服务器
$smtpserverport =25;//SMTP服务器端口
$smtpusermail = "";//SMTP服务器的用户邮箱
$smtpemailto = "";//发送给谁
$smtpuser = "";//SMTP服务器的用户帐号
$smtppass = "";//SMTP服务器的用户密码
$mailsubject = "PHP100测试邮件系统";//邮件主题
$mailbody = "<h1> 这是一个测试程序 </h1>";//邮件内容
$mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
$smtp = new smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
$smtp->debug = false;//是否显示发送的调试信息
$smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
?>
订阅:
博文 (Atom)


