search
HomeBackend DevelopmentPHP TutorialThinkphp implements automatic verification and automatic completion, _PHP tutorial

Thinkphp implements automatic verification and automatic completion.

Thinkphp’s automatic verification and automatic completion are based on the content submitted by the form. After rule verification and processing of some data Insert into database.

1. Automatic verification format:

array(
  array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
  array(验证字段2,验证规则,错误提示,[验证条件,附加规则,验证时间]),
  ......
);

Verification conditions:
self::EXISTS_VALIDATE or 0, verify if the field exists (default)
self::MUST_VALIDATE or 1 must be verified
self::VALUE_VALIDATE or 2 Validate when the value is not empty
Verification time:
Self::MODEL_INSERT or 1 verify when adding new data
self::MODEL_UPDATE or 2 verify when editing data
self::MODEL_BOTH or 3 to verify in all cases (default)

2. Auto-complete format:

array(
  array(完成字段1,完成规则,[完成条件,附加规则]),
  array(完成字段2,完成规则,[完成条件,附加规则]),
   ......
);

Completion time:
self::MODEL_INSERT or 1 Processed when adding new data (default)
self::MODEL_UPDATE or 2 Processed when updating data
self::MODEL_BOTH or 3 All cases are handled

Small instance (registration)
HTML layout:

<form class="form-horizontal" action="{:U('Login/register')}" method="post" autocomplete="off" enctype="multipart/form-data">
  <div class="form-group">
    <label class="col-lg-2 control-label">用户名</label>
    <div class="col-lg-4">
      <input class="form-control" type="text" name="username" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">密码</label>
    <div class="col-lg-4">
      <input class="form-control" type="password" name="password" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">重复密码</label>
    <div class="col-lg-4">
      <input class="form-control" type="password" name="repassword" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">Thinkphp implements automatic verification and automatic completion, _PHP tutorial</label>
    <div class="col-lg-4">
      <input class="form-control" type="file" name="portrait" id="imgpath" />
      <img src="/static/imghwm/default1.png"  data-src="http://www.bkjia.com/uploads/allimg/151228/1T1411363-1.jpg?2015111993855?x-oss-process=image/resize,p_40"  class="lazy"    style="max-width:90%" id="showimgpath" alt="Thinkphp implements automatic verification and automatic completion, _PHP tutorial"/>
      <span class="help-block">关像的大小为80*80px</span>
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">性别</label>
    <div class="col-lg-4">
      <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default active">
          <input type="radio" name="gender" autocomplete="off" value="1" checked /> 男
        </label>
        <label class="btn btn-default">
          <input type="radio" name="gender" autocomplete="off" value="0" /> 女
        </label>
      </div>
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">电话号码</label>
    <div class="col-lg-4">
      <input class="form-control" type="input" name="phone" />
    </div>
  </div>
  <div class="form-group">
    <label class="col-lg-2 control-label">邮箱</label>
    <div class="col-lg-4">
      <input class="form-control" type="input" name="email" />
    </div>
  </div>
  <div class="form-group">
    <div class="col-lg-2 col-lg-offset-2">
      <button class="btn btn-primary btn-block btn-submit" type="submit">注册</button>
    </div>
  </div>
</form>

Model (MemberModel)

<&#63;php
namespace Admin\Model;
use Think\Model;
class MemberModel extends Model {

  /* 自动验证 */
  protected $_validate = array(
    array('username', '', '用户名是唯一的!', self::EXISTS_VALIDATE, 'unique', self::MODEL_INSERT),
    array('password', 'require', '没有填写密码!', self::EXISTS_VALIDATE, '', self::MODEL_INSERT),
    array('repassword', 'password', '重复密码不正确!', self::EXISTS_VALIDATE, 'confirm', self::MODEL_INSERT),
    array('phone','11','电话号码长度不对!', self::EXISTS_VALIDATE, 'length', self::MODEL_INSERT),
    array('email', 'email', '邮箱格式不正确!',self::EXISTS_VALIDATE, '', self::MODEL_INSERT)
  );

  /* 自动完成 */
  protected $_auto = array(
    array('password', 'encrypt', self::MODEL_INSERT, 'callback'),
    array('state','1',self::MODEL_INSERT),
    array('portrait', 'portrait', self::MODEL_INSERT, 'callback'),
    array('create_time', 'createTime', self::MODEL_INSERT, 'callback')
  );

  /* 给密码加密 */
  public function encrypt() {
    return md5(crypt(I('post.password/s'), 'zh'));
  }

  /* 创建时间 */
  public function createTime() {
    return time();
  }

  /* 上传Thinkphp implements automatic verification and automatic completion, _PHP tutorial */
  public function portrait() {
    if($_FILES['portrait']['name']) { // 如果上传的Thinkphp implements automatic verification and automatic completion, _PHP tutorial
      $upload = new \Think\Upload();// 实例化上传类
      $upload->maxSize  =   3145728 ;// 设置附件上传大小
      $upload->exts   =   array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
      $upload->rootPath =   './Uploads/portrait/'; // 设置附件上传根目录
      // 上传单个文件
      $info  =  $upload->uploadOne($_FILES['portrait']);
      if(!$info) {// 上传错误提示错误信息
        $this->error($upload->getError());
      }else{// 上传成功 获取上传文件信息
        $portraitPath = './Uploads/portrait/'.$info['savepath'].$info['savename'];
        $image = new \Think\Image();
        $image->open($portraitPath);
        // 生成一个居中裁剪为80*80的缩略图
        $image->thumb(150, 150,\Think\Image::IMAGE_THUMB_CENTER)->save($portraitPath);
        return $info['savepath'].$info['savename'];
      }
    }
  }
}

Corresponding data table structure:

Detect and insert into the database in the controller:

/* 注册 */
public function register() {
  if(IS_POST) {
    $member = D('member');
    if($member->create()) {
      if($member->add()) {
        $this->success('注册成功!');
      } else {
        $this->error('注册失败!');
      }
    } else {
      exit($member->getError());
    }
  }
  $this->display();
}

The above is the entire content of this article, I hope it will be helpful to everyone’s study

Articles you may be interested in:

  • php form verification implementation code
  • php session application instance login verification
  • php cookie login verification sample code
  • PHP verification code code (latest modification, fully customized!)
  • php mobile phone number verification regular expression
  • PHP code for session sharing and login verification through session id
  • A beautiful php verification code class (share)
  • PHP generates image verification codes, click to switch instances
  • PHP uses CURL to simulate login to websites with verification codes Method

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1084601.htmlTechArticleThinkphp implements automatic verification and automatic completion. Thinkphp’s automatic verification and automatic completion are based on the content submitted by the form. , perform rule verification and processing on part of the data and then insert it into the data...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor