一般在把数据写入数据库之前,先对将要写入的数据进行校验,可以避免出现比较严重的安全问题(例如一般性的SQL注入攻击)。
mayfish 可以灵活的自定义将要执行写入的数据内容的校验规则,以减少开发人员手动对每一个字段的数据进行校验的麻烦。
例子如下:
一、首先定义数据库模块
复制代码 代码如下:
class MemberModel extends AppModel
{
/** 设置数据库表名称 **/
protected $tableName = "members";
/**
* 数据验证规则
*/
protected $verify = array(
array("NotEmpty", "username", "用户名不能留空"),
array("hasOne", "username", "此用户已经存在,请换另一个用户名称再试一次"),
array("NotEmpty", "password", "密码不能留空"),
array("NotEmpty", "email", "邮箱地址不能留空"),
array("isEmail", "email", "邮箱地址格式不正确"),
array("hasOne", "email", "邮箱地址已经被占用")
);
/**
* 覆盖父类添加数据入库的方法
* 先对用户密码进行md5加密,再调用父类的方法写入数据库中
*/
public function create($data) {
$data = array_map("addslashes", $data); //将数据中的标点符号(单、双引号)进行安全转义
$data["password"] = md5($data["password"]);
return parent::create($data);
}
}
?>
二、执行数据写入操作
复制代码 代码如下:
//执行写入数据的片段...
//执行数据入库的操作
private function PostData() {
$fields = array("username", "password", "email");
$post = array_map("trims", $_POST); //清除所有数据两边多余的空格
$post = parseHTML($post, $fields); //将指定的字段内容进行清除HTML处理
$data = parseFields($post, $fields); //提取可以写入数据库的字段(防止别人绕过你的页面进行提交一些别有用心的数据)
$DB = & M("member");
//进行数据验证
if (!$DB->verify($data)) {
//验证失败,取出失败的原因,并提交到模板页面中
$this->assign("error", $DB->getVerifyError());
//把提交过来的数据也提交到模板中(用以实现用户好像没有离开过页面的感觉)
$this->assign("default", $post);
//渲染注册页面模板
$this->display("/register.html");
}
else {
//写入数据库
$result = $DB->create($data);
//返回布尔型,说明数据写入失败,渲染注册页面模板
if (is_bool($result)) {
$this->assign("default", $post);
$this->display("/register.html");
}
else {
//注册成功,渲染注册成功页面模板
$this->assign("username", $data["username"]);
$this->display("/reg_success.html");
}
}
}
可执行验证的规则有
NotEmpty 不能为空
Number 只能是整数
isEmail 邮箱地址是否正确
hasOne 是否是唯一(是否重复,是否已经存在)
Regex 自定义正则表达式
验证的格式为
array(验证方法, 进行验证的字段名称, 验证错误的提示信息)
对于正则表达示的验证
array("Regex", "mobile", '/^13\d{9}$/', "用户名不能留空")
MayFish 下载

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
