1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP For Beginnersチュートリアル その8 値チェックについて

Posted at

このシリーズの目的

体系的なwebコーディングの訓練ができるようになるために、PHPの初学のきっかけかつ、PHPでログインフォームやフォームを実装することができるようになるために

PHP For Beginners

上記のチュートリアルを進めているのでその備忘録。

前回

内容

今回のチュートリアル

PHP Tutorial: PHP Forms Handling & Validation Tutorial

このチュートリアルでやること

・コンタクトフォームに値チェックを入れることでエラーメッセージを返せるようにする

成果物

index.php
<?php 

	$msg= "";
	
	if(isset($_POST['submit'])) {
		$name = $_POST['username'];
		$email = $_POST['email'];
		$message = $_POST['body'];


	if(strlen($name) < 3) {
		$msg = "Please check your name!";

	} else if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
		$msg = "please check your email!";

	} else if(strlen($message) <10 ) {
		$msg = "Message is Short. Please check your Message!";

	} else {
		$msg = "Your data is Alllight. Sending an email.";
	}

	echo $msg;
}

 ?>



<!DOCTYPE html>
<html>
<head>
	<title>PHP function Tutorial</title>
</head>
<body>

<form action="index.php" method="post">
<input type="text" name="username" placeholder="Name......"><br>
<input type="text" name="email" placeholder="Email......"><br>
<textarea name="body" placeholder="what`s up? ......."></textarea><br>
<!-- <input type="file" name="attachment"><br> -->
<input type="submit" name="submit" value="Send">
</form>

</body>
</html>


今回のコードの注釈

filter_varについて

 if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
        $msg = "please check your email!";
}


/*filter_varは指定したフィルタでデータをフィルタリングする関数である。
第一引数に検証する値を、第2引数にフィルタを指定する。
フィルタには様々な型があるが今回は検証フィルタの中で値が妥当なe-mailアドレスかどうか検証するFILTER_VALIDATE_EMAILを使う。

*/


strlen関数

if(strlen($message) <10 ) {
	$msg = "Message is Short. Please check your Message!";
}


/*strlen関数は引数に設定した変数の長さを返す関数。
ここで注意しなければならないのはstrlenは長さを文字数で返すのではなく、バイト数で返すこと。
文字数で返したければmb_strlen関数を使う。
詳しくはマニュアルを見よう。
*/

参考

strlen
[filter_var]
(https://www.php.net/manual/ja/function.filter-var.php)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?