php 编辑表单以清理/验证电话号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15978667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Editing form to sanitize/validate phone number
提问by user2275638
I have very limited experience with PHP and I'm really hoping someone can help me.
我对 PHP 的经验非常有限,我真的希望有人能帮助我。
What I want to do is sanitize/validate the phone number input so that only numbers are allowed.
我想要做的是清理/验证输入的电话号码,以便只允许输入数字。
I think I need to use FILTER_SANITIZE_NUMBER_INT
but I'm not sure where or how to use it.
我想我需要使用,FILTER_SANITIZE_NUMBER_INT
但我不确定在哪里或如何使用它。
Here is my code:
这是我的代码:
<?php
// Replace the email address with the one that should receive the contact form inquiries.
define('TO_EMAIL', '########');
$aErrors = array();
$aResults = array();
/* Functions */
function stripslashes_if_required($sContent) {
if(get_magic_quotes_gpc()) {
return stripslashes($sContent);
} else {
return $sContent;
}
}
function get_current_url_path() {
$sPageUrl = "http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
$count = strlen(basename($sPageUrl));
$sPagePath = substr($sPageUrl,0, -$count);
return $sPagePath;
}
function output($aErrors = array(), $aResults = array()){ // Output JSON
$bFormSent = empty($aErrors) ? true : false;
$aCombinedData = array(
'bFormSent' => $bFormSent,
'aErrors' => $aErrors,
'aResults' => $aResults
);
header('Content-type: application/json');
echo json_encode($aCombinedData);
exit;
}
// Check supported version of PHP
if (version_compare(PHP_VERSION, '5.2.0', '<')) { // PHP 5.2 is required for the safety filters used in this script
$aErrors[] = 'Unsupported PHP version. <br /><em>Minimum requirement is 5.2.<br />Your version is '. PHP_VERSION .'.</em>';
output($aErrors);
}
if (!empty($_POST)) { // Form posted?
// Get a safe-sanitized version of the posted data
$sFromEmail = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$sFromName = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$sMessage = "Name: ".stripslashes_if_required($_POST['name']);
$sMessage .= "\r\nEmail: ".stripslashes_if_required($_POST['email']);
$sMessage .= "\r\nBusiness: ".stripslashes_if_required($_POST['business']);
$sMessage .= "\r\nAddress: ".stripslashes_if_required($_POST['address']);
$sMessage .= "\r\nPhone: ".stripslashes_if_required($_POST['phone']);
$sMessage .= "\r\nMessage: ".stripslashes_if_required($_POST['message']);
$sMessage .= "\r\n--\r\nEmail sent from ". get_current_url_path();
$sHeaders = "From: '$sFromName' <$sFromEmail>"."\r\n";
$sHeaders .= "Reply-To: '$sFromName' <$sFromEmail>";
if (filter_var($sFromEmail, FILTER_VALIDATE_EMAIL)) { // Valid email format?
$bMailSent = mail(TO_EMAIL, "New inquiry from $sFromName", $sMessage, $sHeaders);
if ($bMailSent) {
$aResults[] = "Message sent, thank you!";
} else {
$aErrors[] = "Message not sent, please try again later.";
}
} else {
$aErrors[] = 'Invalid email address.';
}
} else { // Nothing posted
$aErrors[] = 'Empty data submited.';
}
output($aErrors, $aResults);
回答by Kyle
Have you looked into PHP's preg_replacefunction? You can strip out any non-numeric character by using preg_replace('/[^0-9]/', '', $_POST['phone'])
.
你有没有研究过 PHP 的preg_replace函数?您可以使用 去除任何非数字字符preg_replace('/[^0-9]/', '', $_POST['phone'])
。
Once you filter out the character data, you can always check to see if it is of a desired length:
过滤掉字符数据后,您可以随时检查它是否具有所需的长度:
$phone = preg_replace('/[^0-9]/', '', $_POST['phone']);
if(strlen($phone) === 10) {
//Phone is 10 characters in length (###) ###-####
}
You can also use PHP's preg_matchfunction as discussed in this other SO question.
您还可以使用 PHP 的preg_match函数,如this other SO question中所述。
回答by Bravo Delta
There are a couple of ways to do it... examples:
有几种方法可以做到这一点......示例:
// If you want to clean the variable so that only + - . and 0-9 can be in it you can:
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
// If you want to clean it up manually you can:
$phone = preg_replace('/[^0-9+-]/', '', $_POST['phone']);
// If you want to check the length of the phone number and that it's valid you can:
if(strlen($_POST['phone']) === 10) {
if (!preg_match('/^[0-9-+]$/',$var)) { // error } else { // good }
}
Obviously some edits may need to be made dependent on the country and other misc factors.
显然,可能需要根据国家/地区和其他杂项因素进行一些编辑。
回答by Ken Koch
You could try using preg_replace to filter out any non-numeric characters, then you can check the length of whats remaining to see if its a phone number (should be either 7,9 or maybe 10 digits)
您可以尝试使用 preg_replace 过滤掉任何非数字字符,然后您可以检查剩余的长度以查看它是否是电话号码(应该是 7,9 或 10 位数字)
// remove anything thats not a number from the string
function only_numbers($number) { return preg_replace('/[^0-9]/', '', $number) };
// test that the string is only 9 numbers long
function isPhone($number) { return strlen(only_numbers($number)) == 9; }
Just make sure to use the only_numbers
value when using the value after validating it.
只需确保only_numbers
在验证后使用该值时使用该值。
-Ken
-肯