当前位置: 编程技术>php
本页文章导读:
▪解析php类的注册与自动加载
工程目录如下:1、将需要注册的类放在一个数组中 代码如下:<?phpfinal class Utils { private function __construct() { } public static function getClasses($pre_path = '/') { $classes = array( .........
▪php 注册时输入信息验证器的实现详解
1、对输入信息进行验证的类(主要用于验证用户名,密码,重复密码,邮箱,可添加其它功能) 代码如下:<?php/** * Validator for Register. */final class RegisterValidator { private function __construct(.........
▪php解析html类库simple_html_dom(详细介绍)
下载地址:https://github.com/samacs/simple_html_dom解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找.........
[1]解析php类的注册与自动加载
来源: 互联网 发布时间: 2013-11-30
工程目录如下:
1、将需要注册的类放在一个数组中
代码如下:
<?php
final class Utils {
private function __construct() {
}
public static function getClasses($pre_path = '/') {
$classes = array(
'DBConfig' => $pre_path.'DBConfig/DBConfig.php',
'User' => $pre_path.'Model/User.php',
'Dao' => $pre_path.'Dao/Dao.php',
'UserDao' => $pre_path.'Dao/UserDao.php',
'UserMapper' => $pre_path.'Mapping/UserMapper.php',
);
return $classes;
}
}
?>
2、注册数组
注意:步骤1中的类的路径都是相对于init.php而言的,不是相对于Utils而言的,这是因为我们通过init.php里的自动加载函数spl_autoload_register来require类的
代码如下:
<?php
require_once '/Utils/Utils.php';
final class Init {
/**
* System config.
*/
public function init() {
// error reporting - all errors for development (ensure you have
// display_errors = On in your php.ini file)
error_reporting ( E_ALL | E_STRICT );
mb_internal_encoding ( 'UTF-8' );
//registe classes
spl_autoload_register ( array ($this,'loadClass' ) );
}
/**
* Class loader.
*/
public function loadClass($name) {
$classes = Utils::getClasses ();
if (! array_key_exists ( $name, $classes )) {
die ( 'Class "' . $name . '" not found.' );
}
require_once $classes [$name];
}
}
$init = new Init ();
$init->init ();
?>
3、本例中在使用处test.php里require init.php
代码如下:
<?php
require_once 'Init.php';
$dao = new UserDao();
$result = $dao->findByName('zcl');
?>
[2]php 注册时输入信息验证器的实现详解
来源: 互联网 发布时间: 2013-11-30
1、对输入信息进行验证的类(主要用于验证用户名,密码,重复密码,邮箱,可添加其它功能)
<?php
/**
* Validator for Register.
*/
final class RegisterValidator {
private function __construct() {
}
/**
* Validate the given username, password, repeat_password and email.
* @param $username, $password, $repeat_password and $email to be validated
* @return array array of {@link Error} s
*/
public static function validate($username, $password, $repeat_password, $email) {
$errors = array();
$username = trim($username);
$password = trim($password);
if (!$username) {
$errors[] = new Error('username', '用户名不能为空。');
} elseif (strlen($username)<3) {
$errors[] = new Error('username', '用户名长度不能小于3个字符。');
} elseif (strlen($username)>30) {
$errors[] = new Error('username', '用户名长度不能超过30个字符。');
} elseif (!preg_match('/^[A-Za-z]+$/',substr($username, 0, 1))) {
$errors[] = new Error('username', '用户名必须以字母开头。');
} elseif (!preg_match('/^[A-Za-z0-9_]+$/', $username)) {
$errors[] = new Error('username', '用户名只能是字母、数字以及下划线( _ )的组合。');
} elseif (!$password) {
$errors[] = new Error('password', '密码不能为空。');
} elseif (strlen($password)<6) {
$errors[] = new Error('password', '密码长度不能小于6个字符。');
} elseif (strlen($password)>30) {
$errors[] = new Error('password', '密码长度不能超过30个字符。');
} elseif (!preg_match('/^[A-Za-z0-9!@#\\$%\\^&\\*_]+$/', $password)) {
$errors[] = new Error('password', '密码只能是数字、字母或!@#$%^&*_等字符的组合。');
} elseif ($password != trim($repeat_password)) {
$errors[] = new Error('password', '两次输入密码不一致。');
} elseif (!Utils::isValidEmail($email)) {
$errors[] = new Error('email', '邮箱格式有误。');
} else {
// check whether user exists or not
$dao = new UserDao();
$user = $dao->findByName(trim($username));
if ($user) {
$errors[] = new Error('username', '该用户名已经被使用。');
}
$user = null;
// check whether email being used or not
$user = $dao->findByEmail(trim($email));
if ($user) {
$errors[] = new Error('email', '该邮箱已被注册。');
}
}
return $errors;
}
}
?>
2、在注册页面进行调用
$username = null;
$password = null;
$repeat_password = null;
$email = null;
$msg = "";
if (isset($_POST['username']) && isset($_POST['password'])
&& isset($_POST['repeat_password']) && isset($_POST['email'])) {
$username = addslashes(trim(stripslashes($_POST ['username'])));
$password = addslashes(trim(stripslashes($_POST ['password'])));
$repeat_password = addslashes(trim(stripslashes($_POST ['repeat_password'])));
$email = addslashes(trim(stripslashes($_POST ['email'])));
// validate
$errors = RegisterValidator::validate($username, $password, $repeat_password, $email);
// validate
if (empty($errors)) {
// save
$dao = new UserDao();
$user = new User();
$user->setEmail($email);
$last_login_ip = Utils::getIpAddress();
$user->setLastLoginIp($last_login_ip);
$user->setUsername($username);
$salt = substr(sha1(mt_rand()), 0, 22);
$hash_password = sha1($salt . $password);
$user->setPassword($hash_password);
$user->setSalt($salt);
$user = $dao->save($user);
if ($user) {
UserLogin::setUserInfo($user);
Flash::addFlash('注册成功!');
}
else {
Flash::addFlash('对不起,由于服务器内部错误,导致注册失败。请稍后再试。');
}
Utils::redirect('welcome');
}
foreach ($errors as $e) {
$msg .= $e->getMessage()."<br>";
}
3.代码中Error类用于记录验证时的错误信息
<?php
/**
* Validation error.
*/
final class Error {
private $source;
private $message;
/**
* Create new error.
* @param mixed $source source of the error
* @param string $message error message
*/
function __construct($source, $message) {
$this->source = $source;
$this->message = $message;
}
/**
* Get source of the error.
* @return mixed source of the error
*/
public function getSource() {
return $this->source;
}
/**
* Get error message.
* @return string error message
*/
public function getMessage() {
return $this->message;
}
}
?>
代码如下:
<?php
/**
* Validator for Register.
*/
final class RegisterValidator {
private function __construct() {
}
/**
* Validate the given username, password, repeat_password and email.
* @param $username, $password, $repeat_password and $email to be validated
* @return array array of {@link Error} s
*/
public static function validate($username, $password, $repeat_password, $email) {
$errors = array();
$username = trim($username);
$password = trim($password);
if (!$username) {
$errors[] = new Error('username', '用户名不能为空。');
} elseif (strlen($username)<3) {
$errors[] = new Error('username', '用户名长度不能小于3个字符。');
} elseif (strlen($username)>30) {
$errors[] = new Error('username', '用户名长度不能超过30个字符。');
} elseif (!preg_match('/^[A-Za-z]+$/',substr($username, 0, 1))) {
$errors[] = new Error('username', '用户名必须以字母开头。');
} elseif (!preg_match('/^[A-Za-z0-9_]+$/', $username)) {
$errors[] = new Error('username', '用户名只能是字母、数字以及下划线( _ )的组合。');
} elseif (!$password) {
$errors[] = new Error('password', '密码不能为空。');
} elseif (strlen($password)<6) {
$errors[] = new Error('password', '密码长度不能小于6个字符。');
} elseif (strlen($password)>30) {
$errors[] = new Error('password', '密码长度不能超过30个字符。');
} elseif (!preg_match('/^[A-Za-z0-9!@#\\$%\\^&\\*_]+$/', $password)) {
$errors[] = new Error('password', '密码只能是数字、字母或!@#$%^&*_等字符的组合。');
} elseif ($password != trim($repeat_password)) {
$errors[] = new Error('password', '两次输入密码不一致。');
} elseif (!Utils::isValidEmail($email)) {
$errors[] = new Error('email', '邮箱格式有误。');
} else {
// check whether user exists or not
$dao = new UserDao();
$user = $dao->findByName(trim($username));
if ($user) {
$errors[] = new Error('username', '该用户名已经被使用。');
}
$user = null;
// check whether email being used or not
$user = $dao->findByEmail(trim($email));
if ($user) {
$errors[] = new Error('email', '该邮箱已被注册。');
}
}
return $errors;
}
}
?>
2、在注册页面进行调用
代码如下:
$username = null;
$password = null;
$repeat_password = null;
$email = null;
$msg = "";
if (isset($_POST['username']) && isset($_POST['password'])
&& isset($_POST['repeat_password']) && isset($_POST['email'])) {
$username = addslashes(trim(stripslashes($_POST ['username'])));
$password = addslashes(trim(stripslashes($_POST ['password'])));
$repeat_password = addslashes(trim(stripslashes($_POST ['repeat_password'])));
$email = addslashes(trim(stripslashes($_POST ['email'])));
// validate
$errors = RegisterValidator::validate($username, $password, $repeat_password, $email);
// validate
if (empty($errors)) {
// save
$dao = new UserDao();
$user = new User();
$user->setEmail($email);
$last_login_ip = Utils::getIpAddress();
$user->setLastLoginIp($last_login_ip);
$user->setUsername($username);
$salt = substr(sha1(mt_rand()), 0, 22);
$hash_password = sha1($salt . $password);
$user->setPassword($hash_password);
$user->setSalt($salt);
$user = $dao->save($user);
if ($user) {
UserLogin::setUserInfo($user);
Flash::addFlash('注册成功!');
}
else {
Flash::addFlash('对不起,由于服务器内部错误,导致注册失败。请稍后再试。');
}
Utils::redirect('welcome');
}
foreach ($errors as $e) {
$msg .= $e->getMessage()."<br>";
}
3.代码中Error类用于记录验证时的错误信息
代码如下:
<?php
/**
* Validation error.
*/
final class Error {
private $source;
private $message;
/**
* Create new error.
* @param mixed $source source of the error
* @param string $message error message
*/
function __construct($source, $message) {
$this->source = $source;
$this->message = $message;
}
/**
* Get source of the error.
* @return mixed source of the error
*/
public function getSource() {
return $this->source;
}
/**
* Get error message.
* @return string error message
*/
public function getMessage() {
return $this->message;
}
}
?>
[3]php解析html类库simple_html_dom(详细介绍)
来源: 互联网 发布时间: 2013-11-30
下载地址:https://github.com/samacs/simple_html_dom
解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。
开始使用
上传类文件以后,有三种方式调用这个类:
从url中加载html文档
从字符串中加载html文档
从文件中加载html文档
<?php
// 新建一个Dom实例
$html = new simple_html_dom();
// 从url中加载
$html->load_file('http://www.');
// 从字符串中加载
$html->load('<html><body>从字符串中加载html文档演示</body></html>');
//从文件中加载
$html->load_file('path/file/test.html');
?>
如果从字符串加载html文档,需要先从网络上下载。建议使用cURL来抓取html文档并加载DOM中。
查找html元素
可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例:
<?php
//查找html文档中的超链接元素
$a = $html->find('a');
//查找文档中第(N)个超链接,如果没有找到则返回空数组.
$a = $html->find('a', 0);
// 查找id为main的div元素
$main = $html->find('div[id=main]',0);
// 查找所有包含有id属性的div元素
$divs = $html->find('div[id]');
// 查找所有包含有id属性的元素
$divs = $html->find('[id]');
?>
还可以使用类似jQuery的选择器来查找定位元素:
<?php
// 查找id='#container'的元素
$ret = $html->find('#container');
// 找到所有.foo');
// 查找多个html标签
$ret = $html->find('a, img');
// 还可以这样用
$ret = $html->find('a[title], img[title]');
?>
解析器支持对子元素的查找
<?php
// 查找 ul列表中所有的li项
$ret = $html->find('ul li');
//查找 ul 列表指定ul li.selected');
?>
如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素
<?php
// 返回父元素
$e->parent;
// 返回子元素数组
$e->children;
// 通过索引号返回指定子元素
$e->children(0);
// 返回第一个资源速
$e->first_child ();
// 返回最后一个子元素
$e->last _child ();
// 返回上一个相邻元素
$e->prev_sibling ();
//返回下一个相邻元素
$e->next_sibling ();
?>
元素属性操作
使用简单的正则表达式来操作属性选择器。
[attribute] – 选择包含某属性的html元素
[attribute=value] – 选择所有指定值属性的html元素
[attribute!=value]- 选择所有非指定值属性的html元素
[attribute^=value] -选择所有指定值开头属性的html元素
[attribute$=value] 选择所有指定值结尾属性的html元素
[attribute*=value] -选择所有包含指定值属性的html元素
在解析器中调用元素属性
在DOM中元素属性也是对象:
<?php
// 本例中将$a的锚链接值赋给$link变量
$link = $a->href;
?>
或者:
<?php
$link = $html->find('a',0)->href;
?
每个对象都有4个基本对象属性:
tag – 返回html标签名
innertext – 返回innerHTML
outertext – 返回outerHTML
plaintext – 返回html标签中的文本
在解析器中编辑元素
编辑元素属性的用法和调用它们是类似的:
<?php
//给$a的锚链接赋新值
$a->href = 'http://www.';
// 删除锚链接
$a->href = null;
// 检测是否存在锚链接
if(isset($a->href)) {
//代码
}
?>
解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用:
<?php
// 封装元素
$e->outertext = '<div >' . $e->outertext . '<div>';
// 删除元素
$e->outertext = '';
// 添加元素
$e->outertext = $e->outertext . '<div>foo<div>';
// 插入元素
$e->outertext = '<div>foo<div>' . $e->outertext;
?
保存修改后的html DOM文档也非常简单:
<?php
$doc = $html;
// 输出
echo $doc;
?>
如何避免解析器消耗过多内存
在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存绝对是对自己负责啦^_^
<?php
$html->clear();
?>
解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。
开始使用
上传类文件以后,有三种方式调用这个类:
从url中加载html文档
从字符串中加载html文档
从文件中加载html文档
代码如下:
<?php
// 新建一个Dom实例
$html = new simple_html_dom();
// 从url中加载
$html->load_file('http://www.');
// 从字符串中加载
$html->load('<html><body>从字符串中加载html文档演示</body></html>');
//从文件中加载
$html->load_file('path/file/test.html');
?>
如果从字符串加载html文档,需要先从网络上下载。建议使用cURL来抓取html文档并加载DOM中。
查找html元素
可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例:
代码如下:
<?php
//查找html文档中的超链接元素
$a = $html->find('a');
//查找文档中第(N)个超链接,如果没有找到则返回空数组.
$a = $html->find('a', 0);
// 查找id为main的div元素
$main = $html->find('div[id=main]',0);
// 查找所有包含有id属性的div元素
$divs = $html->find('div[id]');
// 查找所有包含有id属性的元素
$divs = $html->find('[id]');
?>
还可以使用类似jQuery的选择器来查找定位元素:
代码如下:
<?php
// 查找id='#container'的元素
$ret = $html->find('#container');
// 找到所有.foo');
// 查找多个html标签
$ret = $html->find('a, img');
// 还可以这样用
$ret = $html->find('a[title], img[title]');
?>
解析器支持对子元素的查找
代码如下:
<?php
// 查找 ul列表中所有的li项
$ret = $html->find('ul li');
//查找 ul 列表指定ul li.selected');
?>
如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素
代码如下:
<?php
// 返回父元素
$e->parent;
// 返回子元素数组
$e->children;
// 通过索引号返回指定子元素
$e->children(0);
// 返回第一个资源速
$e->first_child ();
// 返回最后一个子元素
$e->last _child ();
// 返回上一个相邻元素
$e->prev_sibling ();
//返回下一个相邻元素
$e->next_sibling ();
?>
元素属性操作
使用简单的正则表达式来操作属性选择器。
[attribute] – 选择包含某属性的html元素
[attribute=value] – 选择所有指定值属性的html元素
[attribute!=value]- 选择所有非指定值属性的html元素
[attribute^=value] -选择所有指定值开头属性的html元素
[attribute$=value] 选择所有指定值结尾属性的html元素
[attribute*=value] -选择所有包含指定值属性的html元素
在解析器中调用元素属性
在DOM中元素属性也是对象:
代码如下:
<?php
// 本例中将$a的锚链接值赋给$link变量
$link = $a->href;
?>
或者:
代码如下:
<?php
$link = $html->find('a',0)->href;
?
每个对象都有4个基本对象属性:
tag – 返回html标签名
innertext – 返回innerHTML
outertext – 返回outerHTML
plaintext – 返回html标签中的文本
在解析器中编辑元素
编辑元素属性的用法和调用它们是类似的:
代码如下:
<?php
//给$a的锚链接赋新值
$a->href = 'http://www.';
// 删除锚链接
$a->href = null;
// 检测是否存在锚链接
if(isset($a->href)) {
//代码
}
?>
解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用:
代码如下:
<?php
// 封装元素
$e->outertext = '<div >' . $e->outertext . '<div>';
// 删除元素
$e->outertext = '';
// 添加元素
$e->outertext = $e->outertext . '<div>foo<div>';
// 插入元素
$e->outertext = '<div>foo<div>' . $e->outertext;
?
保存修改后的html DOM文档也非常简单:
代码如下:
<?php
$doc = $html;
// 输出
echo $doc;
?>
如何避免解析器消耗过多内存
在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存绝对是对自己负责啦^_^
代码如下:
<?php
$html->clear();
?>
最新技术文章: