使用php创建一个注册表单,如何实现一个简单的注册表单
創建一個注冊表單是非常容易的 - 它事實上意味著,你只需要創建一個表單,表單將更新一些User的模型對象(這個例子是一個Doctrine實體)并保存它。
受歡迎的FOSUserBundle 提供了一個注冊表單,重置密碼表單和其他用戶管理功能。
如果你先前沒有一個User實體和能工作的登錄系統,你要先從怎樣從數據庫加載安全用戶開始。
你的User實體至少應該有以下字段:
username
他是用來登錄的,除非你想用email來替代你的用戶(在那種情況下,這個字段就不是必要的了)。
這是一條不錯的信息,很值得收集。您也可以允許用戶通過email登錄。
password
編譯的密碼
plainPassword
這個字段不會被持久化:(注意沒有上面的@ORM\Column)。他將臨時存儲注冊表單的明文密碼。此字段可以被驗證,然后被用于password字段的填充。
添加了一些驗證,你的類可能看起來像這樣:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity
* @UniqueEntity(fields="email", message="Email already taken")
* @UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
* @ORM\Column(type="string", length=255, unique=true)
* @Assert\NotBlank()
*/
private $username;
/**
* @Assert\NotBlank()
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
* The below length depends on the "algorithm" you use for encoding
* the password, but this works well with bcrypt.
*
* @ORM\Column(type="string", length=64)
*/
private $password;
// other properties and methods
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
// other methods, including security methods like getRoles()
}
UserInterface要求要有一些其他的方法,并且你的security.yml文件需要被正確配置,來讓User實體工作。更多完整的例子,參見實體提供器文章。
為什么限制4096密碼??
注意,plainPassword字段的最大長度是4096字符。為了安全起見(CVE-2013-5750),當編譯它時,Symfony限制明文密碼長度到4096字符。添加此約束來確保如果有人嘗試了一個超長的密碼,你的表單應該提示一個驗證錯誤。
你需要添加這個約束到你應用程序任何需要用戶提交明文密碼的地方(如,修改密碼表單)。唯一不需要你擔心的就是你的登錄表單,因為symfony安全組件會替你處理。
為實體創建一個表單??
下一步,給User實體創建表單:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33// src/AppBundle/Form/UserType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class)
->add('username', TextType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat Password'),
)
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
));
}
}
這里有兩個字段:email, username 和 plainPassword(重復確認輸入的密碼)。
探索更多關于表單組件的事情,請閱讀表單指南。
處理表單提交??
下一步,你需要一個控制器去處理表單渲染和提交。如果表單被提交,控制器執行驗證并保存數據到數據庫:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46// src/AppBundle/Controller/RegistrationController.php
namespace AppBundle\Controller;
use AppBundle\Form\UserType;
use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class RegistrationController extends Controller
{
/**
* @Route("/register", name="user_registration")
*/
public function registerAction(Request $request)
{
// 1) build the form
$user = new User();
$form = $this->createForm(UserType::class, $user);
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 3) Encode the password (you could also do this via Doctrine listener)
$password = $this->get('security.password_encoder')
->encodePassword($user, $user->getPlainPassword());
$user->setPassword($password);
// 4) save the User!
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute('replace_with_some_route');
}
return $this->render(
'registration/register.html.twig',
array('form' => $form->createView())
);
}
}
在安全配置中配置上面步驟3的編碼器,來定義用于編譯密碼的算法:
1
2
3
4# app/config/security.ymlsecurity:encoders:AppBundle\Entity\User:bcrypt
1
2
3
4
5
6
7
8
9
10
11
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:srv="http://symfony.com/schema/dic/services"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
bcrypt
1
2
3
4
5
6// app/config/security.php
$container->loadFromExtension('security', array(
'encoders' => array(
'AppBundle\Entity\User' => 'bcrypt',
),
));
這個案例我們推薦使用bcrypt 算法。了解更多關于如何編碼用戶密碼的細節請看安全章節。
如果您決定不使用注釋方式的路由(如上),那么你需要創建一個這個控制器的路由:
1
2
3
4# app/config/routing.ymluser_registration:path: /registerdefaults:{ _controller:AppBundle:Registration:register }
1
2
3
4
5
6
7
8
9
10
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
AppBundle:Registration:register
1
2
3
4
5
6
7
8
9
10// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('user_registration', new Route('/register', array(
'_controller' => 'AppBundle:Registration:register',
)));
return $collection;
下一步,創建模板:
1
2
3
4
5
6
7
8
9
10{# app/Resources/views/registration/register.html.twig #}
{{ form_start(form) }}
{{ form_row(form.username) }}
{{ form_row(form.email) }}
{{ form_row(form.plainPassword.first) }}
{{ form_row(form.plainPassword.second) }}
Register!
{{ form_end(form) }}
1
2
3
4
5
6
7
8
9
10
11
<?php echo $view['form']->start($form) ?>
<?php echo $view['form']->row($form['username']) ?>
<?php echo $view['form']->row($form['email']) ?>
<?php echo $view['form']->row($form['plainPassword']['first']) ?>
<?php echo $view['form']->row($form['plainPassword']['second']) ?>
Register!
<?php echo $view['form']->end($form) ?>
參見如何自定義表單渲染,里面有更多細節。
更新你的數據庫結構??
如果你在這個教程中已經更新了User實體,你必須要使用下面的命令去更新數據庫結構:
1$ php bin/console doctrine:schema:update --force
就是這樣!來到/register來嘗試一下吧!
注冊表單只有Email(沒有 Username)??
如果你想要你的用戶通過email登錄并不需要用戶名,那么你可以從你的User實體中徹底移除他。相反,讓getUsername()返回email屬性:
1
2
3
4
5
6
7
8
9
10
11
12
13
14// src/AppBundle/Entity/User.php
// ...
class User implements UserInterface
{
// ...
public function getUsername()
{
return $this->email;
}
// ...
}
下一步,只更改你security.yml文件的providers 部分,以便Symfony知道如何去通過email屬性加載你的用戶來登錄。參見如何自定義表單渲染。
添加一個“打上勾”的Checkbox??
有時,你想要一個“你接受這個條款和聲明嗎?”的Checkbox,出現在你的注冊表單。唯一竅門,讓你要去添加這個字段到你的表單中,而你永遠不需要添加多余的termsAccepted屬性到你的User實體。
要做到這一點,要添加一個termsAccepted字段到你的表單,但設置它的 mapped 選項為false:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20// src/AppBundle/Form/UserType.php
// ...
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class);
// ...
->add('termsAccepted', CheckboxType::class, array(
'mapped' => false,
'constraints' => new IsTrue(),
))
);
}
}
constraints配置也被使用了,它允許我們添加驗證,盡管沒有User中沒有termsAccepted屬性。
總結
以上是生活随笔為你收集整理的使用php创建一个注册表单,如何实现一个简单的注册表单的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用键盘操作将桌面计算机图标隐藏,win
- 下一篇: 动态规划算法php,php算法学习之动态