mayfish 資料入庫驗證代碼_PHP教程

來源:互聯網
上載者:User
一般在把資料寫入資料庫之前,先對將要寫入的資料進行校正,可以避免出現比較嚴重的安全問題(例如一般性的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 自訂Regex

驗證的格式為
array(驗證方法, 進行驗證的欄位名稱, 驗證錯誤的提示資訊)
對於正則表達示的驗證
array("Regex", "mobile", '/^13\d{9}$/', "使用者名稱不能留空")

MayFish 下載

http://www.bkjia.com/PHPjc/321655.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/321655.htmlTechArticle一般在把資料寫入資料庫之前,先對將要寫入的資料進行校正,可以避免出現比較嚴重的安全問題(例如一般性的SQL注入攻擊)。 mayfish 可以靈...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.