Mobile Phone Validation - Php - php

Apologies to bother you with a question that may seem quite blunt to some of you but I was wondering if any of you could shed some light on the validation side of things
Ive got a text field and I need validation on a mobile number so i need to validate that it has +44 at the beginning and including the +44 that it is 13 digits long , I found a few different techniques but nothing that defined it step by step only just copy and paste , Id like to learn how to do it so I know for future reference.
Any help would be appreciated
Thanks

Although this can be done simply with PHP string functions, I would urge you take this opportunity to learn regular expressions. Once you are ready you can use PHP PCRE functions to apply that regular expression.
Note: This answer is intentionally generalized in the interest of teaching a man to fish, per the OP request. I encourage posting a separate, more specific question after reviewing these resources.

Easy way:
php code:
if (isset($_POST['send'])) {
$mobile = $_POST['mobilenumber'];
// get the first 3 string
$begin = substr($mobile,0,3);
// get the rest of the posted string and add it to 0 to make it to number
// 'intval($variable)' and '(int) $variable' do the same
$theOthers = 0+substr($mobile,3);
// OR $theOthers = intval(substr($mobile,3));
// OR $theOthers = (int) substr($mobile,3);
$ok = true;
echo strlen($mobile);
// check the first 3 string
// if it's not equal with "+44", the entry is wrong
if ($begin != "+44") {
$ok = false;
} else {
// check the length of the input
// if it's not equal with 13, the entry is wrong
if (strlen($mobile)!=13) {
$ok = false;
}
}
if ($ok) {
// do something
}
}
html code:
<form method="post">
<input type="text" name="mobilenumber" maxlength="13" value="+44">
<input type="submit" name="send" value="Send">
</form>

Related

Form validation with a php array

I'm hoping someone could help me finish off some php code (the avon guy already kindly helped me with this but I'm still struggling with the last bit).
All it is, is I have a form where I have 10 particular sequences of digits, which if entered, allows the form to redirect to the following page. If anything else is entered I want the page to deny access with some kind of error prompt.
At top of the php, in the part before any php is printed, avon guy suggested an array to check the 10 correct sequences against.
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) != false) {
//match code in here
} else {
// fail code in here
}
I'm not sure what to put in the //match code in here AND the //fail code in here, bits. Can someone help me with this last bit please?
Many thanks
Jon
If you are just trying to redirect to another page using php, you can use header('Location: mypage.php');. More information on header here.
So for your code example (edited based on comment):
invitation.php
<?php
//invitation.php
$possibles = array('rva858', 'anothersequence', 'andanother');
$match = $_POST['nextpage'];
if (array_search($match, $possibles) === false)
{
//If fail
header('Location: formpage.php?errorMessage=Incorrect code!');
exit();
}
//If success:
//All of the invitation.php html and success code below
formpage.php
<?php
//formpage.php
if(!empty($_GET['errorMessage'])){
echo '<span>' . $_GET['errorMessage'] . '</span>';
}
?>
<form action="invitation.php" method="post">
<input name="rsvp" type="text" />
<input type="submit" value="Submit" name="submit" />
</form>

How to pre-fill a type="url" form field with "http://" using html or php?

Problem: on a form asking for the user's website, a type="url" form field returns an error unless "http://" precedes the domain name (there's even an error with "www.").
Outcome I am seeking: a PHP/HTML* method of partly pre-filling the type="url" field with "http://" so it's more user-friendly for users to type "companywebsite.com" into the field and submit without the error.
In other words, a user just fills in companywebsite.com and I want to pre-fill that with http:// so the end result is http://companywebsite.com
<h5>Website</h5>
<input type="url" name="company_website" id="company_website" value="" />
Image below is a screenshot of a form entry that has returned an error (because "http://" does not precede the stackoverflow.com domain).
* I did find a .js method (https://gist.github.com/cvan/117bc1f88e4dfca6dba7) but I'm a novice and just learning php
There are a couple of ways you could go about this:
<input type="url" name="company_website" id="company_website" value="http://" />
However, I would advise against this because you can never trust the user to input correctly. Instead, assuming you are submitting your form via the POST method, in your php code,
<?php
if(isset($_POST['company_website'])){
$pos = strpos($_POST['company_website'], "http://");
if($pos != 0){
$website = "http://".$_POST['company_website'];
}
// do the rest
}
?>
Well then. For the purpose of learning something about security, I'll write this answer with some example code, so you know how to do this kind of stuff safely in the future.
First, lets write a small form:
<form method="POST" action="your_php_file.php" accept-charset="utf-8">
<input type="url" name="company_website" id="company_website" value="" />
<input type="submit" value="Update website" />
</form>
Now lets start writing our PHP file based on this. First we need to be sure the user is submitting new data and not an empty string:
if(isset($_POST['company_website']) && !empty($_POST['company_website'])){
Next we'll write a function that checks if the string is a website or not:
function isWebsite($url){
To see if a string matches a website, we'll be using regular expressions. Regex can be quite complicated, so at the end of this answer, I'll post a link to learn more about them.
$pattern = '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';
Now lets write a simple if statement that returns us true or false. To keep it simple, this statement compares the variable $url (which contains the user data) with the above regular expression pattern in $pattern. It will return true if $url contains a valid website, or false if it doesn't.
if(preg_match($pattern, $url)){
return true;
} else {
return false;
}
}
Next we'll write a function that adds 'http://' in front of the data send by the user:
function addHttp($url){
$url = "http://". $url;
return $url;
}
Now that our functions are complete, all we have to do is use them. First we'll check if the user already sent a valid website:
if(isWebsite($_POST['company_website'])){
//The website is valid, so you can safely add it your database here
} else {
//The website is not valid, but the user might simply have forgotten
//to add http:// in front of it. So lets do it for him:
$website = addHttp($_POST['company_website']);
//Still we can't be sure if it's a valid website. It might be a string
//that will try to mess with your database. So lets verify it again:
if(isWebsite($website)){
//The website is now valid, so you can safely add it your database here
} else {
//The website is still not valid, so we need to return an error
//to your user:
echo "It seems you didn't enter a valid website. Please try again!";
exit;
}
}
}
As you might have noticed, we have 2 places in our code where we need to write the same code to insert everything in the database. You could use a function for that as well:
function addToDatabase($url){
//Write your code to add everything to database here. $url will contain the website
}
So the complete code would become as follows:
<?php
if(isset($_POST['company_website']) && !empty($_POST['company_website'])){
function isWebsite($url){
$pattern = '#((https?|ftp)://(\S*?\.\S*?))([\s)\[\]{},;"\':<]|\.\s|$)#i';
if(preg_match($pattern, $url)){
return true;
} else {
return false;
}
}
function addHttp($url){
$url = "http://". $url;
return $url;
}
function addToDatabase($url){
//Write your code to add everything to database here. $url will contain the website
}
if(isWebsite($_POST['company_website'])){
addToDatabase($_POST['company_website']);
} else {
//The website is not valid, try adding 'http://'
$website = addHttp($_POST['company_website']);
if(isWebsite($website)){
addToDatabase($website);
} else {
//The website is still not valid, return error
echo "It seems you didn't enter a valid website. Please try again!";
exit;
}
}
}
?>
I should add that it still might not be safe to just blindly add the website to your database. To make it absolutely secure, you'll need to use PDO() or MySQLi() in combination with Prepared Statements. But explaining that in this answer would turn this into a book. So make sure to learn about it!
Lastly I promissed to give a resource to learn more about Regular Expressions. The best and safest resource would be from the official PHP website itself. You can find it here: PHP: Pattern Syntax

Simple Captcha in PHP with rand()

I'm trying to make a simple captcha in PHP, but it does not work. The query is not currently executing. This is my current code:
<?php
$Random = rand(1, 100);
$Random2 = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
<input type="text" name="r_input"/><br />
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $Random+$Random2;
if(isset($_POST['myButton']) and trim($Var) and trim($Var2) and trim($Var3) and $Cap==$Result){
//My Query
}
When you use rand() to generate 2 values, and show those 2 values, and give the form for the user to enter the answer, ...
... the user enters the answer and submits back to the server ...
... the server gets the answer, and then GENERATES 2 NEW VALUES, that don't correspond to the answer given by the user.
Try using session variables to store the generated values in, and match against when the user submits the form!
<?php
session_start();
$captcha_id = 'captcha_' . rand();
$_SESSION['$captcha_id']['val1'] = rand(1,1000);
$_SESSION['$captcha_id']['val2'] = rand(1,1000);
echo "
<form action='' method='post'>
<p>Result: {$_SESSION['$captcha_id']['val1']} + {$_SESSION['$captcha_id']['val2']} = </p>
<input type='hidden' name='captcha_id' value='{$captcha_id}' />
<input type='text' name='captcha_answer' />
<p>?</p>
</form>
";
if (
isset($_POST['captcha_id'])
&& isset($_SESSION[$_POST['captcha_id']])
&& isset($_POST['captcha_answer'])
&& $_SESSION[$_POST['captcha_id']]['val1'] + $_SESSION[$_POST['captcha_id']]['val2'] == intval($_POST['captcha_answer'])
) {
unset($_SESSION[$_POST['captcha_id']]); // don't let this answer be reused anymore.
// do allowed stuff
}
?>
Because $Random and $Random2 have a different value each time.
When you show the form for the first time, they may have the values $Random = 12 and $Random2 = 26. The User sees those, adds them up correctly and types in 38 (which is the correct answer for those two values). The answer is sent to the script again, the values of $Random and $Random2 are generated again (this time as $Random = 23 and $Random2 = 30 which equals 53) and the answer the user has sent is not correct any more.
So you would need to store those values in hidden fields and add these up, instead of the generated ones, like so:
<input type="hidden" name="rand_1" value="<?php echo $Random; ?>">
<input type="hidden" name="rand_2" value="<?php echo $Random2; ?>">
<?php
if ($_POST['rand_1'] + $_POST['rand_2'] == $_POST['r_input']) {
// Query etc.
EDIT: As suggested by #nl-x you should use the Session variables instead of hidden fields to prevent abuse of the captcha:
<?php
$Random = $_SESSION['rand_1'] = rand(1, 100);
$Random2 = $_SESSION['rand_2'] = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
And check those values against the given result afterwards:
<?php
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $_SESSION['rand_1'] + $_SESSION['rand_2'];
if ($Result == $Cap) {
// ...
You never re-enter PHP mode after you output your form field:
<input type="text" name="r_input"/><br />
<?php // <----this is missing
$Cap = mysql_real_escape_string($_POST['r_input']);
Pardon me, but you are not making a real captcha. The purpose of the captcha is to distinguish the human from the bots. I would highly suggest you to pick a image database, and randomize a function to call a image. Internally, i would check if the text/description of the image matches with what the user typed.
The only thing you will rand() is what image to load from your image database.
That's a not-healthy way to do it, and there are plenty of better ways to do this. But it's more closer to a captcha than just your current code.
There is also a lot of libraries and engines that can do the job for you.
I'm not a pro at PHP, or even programming at all, but i think you're going to the wrong side - your code won't block any... malicious actions at all, or whatever kind of action that you will try to prevent with the captcha.
Search google for the libraries. PhpCaptcha is one of them. And here is a very simple quickstart guide for phpcaptcha.
Here's a code example, extracted from PHPCaptch that I linked above.
At the desired position in your form, add the following code to display the CAPTCHA image:
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
Next, add the following HTML code to create a text input box:
<input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
On the very first line of the form processor, add the following code:
<?php session_start(); ?>
The following php code should be integrated into the script that processes your form and should be placed where error checking is done. It is recommended to place it after any error checking and only attempt to validate the captha code if no other form errors occured. It should also be within tags.
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage source code and creates a new Securimage object that is responsible for creating, managing and validating captcha codes.
Next we will check to see if the code typed by the user was entered correctly.
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
Following the directions above should get Securimage working with minimal effort.
This code is included here as well.
Good luck!

php validation concept

First of all, I don't want to use any framework but I am looking for a good way to use whitelist validation. I am going to apply it on all the user input I receive, I need validation for XSS protection and I also want to apply different formats for example:
Example 1 XSS.
<input type="text" name="test" value="<script>alert('test');</script" />
Example 2 Date.
<input type="text" name="test" value="31-05-2012" />
Example 3 Time.
<input type="text" name="test" value="15:00" />
Example 4 Max length.
<input type="text" name="test" value="short description" />
Example 5 Min length.
<input type="text" name="test" value="min description" />
Example 6 Alphabetic and default symbols only
<input type="text" name="test" value="hello world. This is à ö text input :P :) :S :$ =D !! ??" />
Example 7 Numeric only
<input type="text" name="test" value="1234567890" />
My idea is to build a clientside and server site validation, if the user gets passed through the clientside validation (jQuery) they will get marked as hacker, since it is impossible for default users to pass through the clientside validation.
My question is: What would be the best way to apply client+serverside validation to prevent XSS and apply regular expressions on fields. Are there any lightweight PHP libraries for validation?
I have looked at:
ctype_alpha
preg_match
But I am not quit sure what would be the best one to use, and ctype_alpha is not allowing default symbols etc.
Any advises? Examples? Thanks for your time and reading, and sorry for the hectic question.
It seems you just need some basic validation, not "whitelist" one.
the idea is quite simple.
Create a server-side validation. with ctype_alpha, preg_match and such. (I hope that your question is not about teaching you these functions from scratch).
Create cleint-side validation if you want, by making AJAX calls to the very same validation routines you've used for the (1).
Of course, you have to use both anyway.
Marking users as a hackers seems not the best idea. What you gonna do with marked users?
I've had a similar problem and ended up writing my own "Input-Datatype" classes. This might be a bit excessive if you only use them for validating input though. But you could build validation functions that use a mix of PHP functions such as preg_match, is_numeric, strtotime etc...
An example for date validation would be:
public function validate(&$value) {
$date = strtotime($value);
if($date === false){
//Error no valid date
}else{
if(isset($this->maxDate)){
if($date>strtotime($this->maxDate)){ //maxDate being the maximal date allowed
//Error max date exceeded
}
}
if(isset($this->minDate)){
if($date<strtotime($this->minDate)){ //minDate being the minimal date allowed
//Error date too low
}
}
$value = strftime($this->format,$date); //format being the format in which the date should be saved
}
Another example for validating text could be:
public function validate(&$value) {
if (isset($value) && $value != "") {
if(isset($this->maxLength)&&$this->maxLength!= ""){ //maxLength being the maximal number of characters
if (strlen($value) > $this->maxLength) {
//Error max length exceeded
}
}
} else {
if (!$this->allowNull) { //allowNull being a boolean: true if text can be empty
//Error value is empty
}
}
if(isset($this->regex)&&$this->regex!= ""){ //regex can be any regular expression, e.g: /[A-Za-z]/ for letters only
if(!preg_match($this->regex, $value)){
//Error value does not match expression
}
}
}
As far as XSS goes, make sure you use prepared statements when interacting with a database and use htmlentities when displaying user inputted data.
Hope this helps.
Some time ago, i've written a lightweight-validation class. Maybe you can use it.
For example:
$oValidator = new Validator();
$oValidator->setLanguage('en');
$oValidator->isValid('short description', 'max_length[4]');
echo $oValidator->getLastErrorMessage();
//The input can not exceed 4 characters in length.
$oValidator->isValid('min description', 'min_length[5]');
$oValidator->isValid('hello world. This is à ö text input :P :) :S :$ =D !! ??', 'min_length[5]');
$oValidator->isValid('1234567890', 'digits');
Rule definition:
/**
* #ErrorMessage[lang=de] Die Eingabe muss mindestens %d Zeichen lang sein.
* #ErrorMessage[lang=en] The input must be at least %d characters in length.
*/
public function check_min_length($mValue, $aParams)
{
return (strlen($mValue) >= $aParams[0]);
}
Example:
http://sklueh.de/2013/01/lightweight-php-validator-neue-version/
github:
https://github.com/sklueh/Lightweight-PHP-Validator

PHP can't iterate through too high or too low

[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to learn, thank you.]
The code below runs, the only problem is that it does not tell the user when the number is too high or too low, I am doing something wrong, but I can't see the error?
<?php
//Starts our php document
if (!$number)
//if we have already defined number and started the game, this does not run
{
Echo"Please Choose a Number 1-100 <p>";
//gives the user instructions
$number = rand (1,100) ;
//creates number
}
else {
//this runs if the game is already in progress
if ($Num >$number)
{
Echo "Your number, $Num, is too high. Please try again<p>";
}
//if the number they guessed is bigger than number, lets user know, guess was high
elseif ($Num == $number)
{
Echo "Congratulations you have won!<p>";
//if the number they guessed was correct it lets them know they won
Echo "To play again, please Choose a Number 1-100 <p>";
$number = rand (1,100) ;
//it then starts the game again by choosing a new value for $number that they can guess
}
else
{
Echo "Your number, $Num, is too low. Please try again<p>";
}
//if the answer is neither correct or to high, it tells them it is too low
}
?>
<form action = "<?php Echo $_SERVER[’PHP_SELF’]; ?>" method = "post"> <p>
<!--this sends the form back to the same page we are on-->
Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<!--Allows the user to input their guess-->
<input type = "hidden" name = "number" value=<?php Echo $number ?>>
<!--keeps passing along the number value to keep it consistent till it is guessed-->
</form>
</body>
</html>
I am assuming $Num is undefined and I am assuming you are assuming it will be defined be cause it is defined in the form.
Try this at the start of your script:
if(!empty($_POST)) {
$Num = (int) $_POST['Num'];
}
$number is not automatically set to the value the <input> field has. (It was in early versions of PHP). You now have to use $_POST['number'] and $_POST['Num'] for this.
register_globals in your php.ini is probably Off (and that's a good thing) and therefore you can only access those variables through $_POST['Num'] and $_POST['number'] (you can just assign $number=$_POST['number'] at the beggining of your script)
also, sending the secret $number through form is not nice, you might want to read about php sessions
Suggestions:
1) use echo, not Echo
2) do not forget to close the p tag

Categories