In this project, you create a script that validates whether a credit card number contains only integers. The script will remove dashes and spaces from the string. After the dashes and spaces are removed, the script should reject the credit card if it contains any other nonnumeric characters.
1. Create a new document in your text editor.
2. Type the < !DOCTYPE> declaration, < html> element, document head, and < body> element. Use the strict DTD and "Validate Credit Card" as the comment of the < title> element.
3. Add the following text and elements to the document body:
< h1>Validate Credit Card< hr/>
4. Add the following script section to the document body:
< ?php
?>
5. Add the following form to the end of the document body. The < input> element includes PHP code that fills in the value from the $_GET['ccnumber'] autoglobal, if it exists.
< form action="ValidateCreditCard.php" method="get" enctype="application/x-www-form-urlencoded">
< p>< input type="text" name="ccnumber" size="20" value="< ?php if(!empty($_GET['ccnumber'])) echo $_GET['ccnumber'] ?>" />< /p>
< p>< input type="submit" value="Validate Credit Card" />
< /form>< hr />
6. Add the following if statement to the script section to determine whether a value is assigned to the $_GET['ccnumber'] autoglobal:
if(!isset($_GET['ccnumber']))
echo "< p>Enter your credit card number.< /p>";
7. Add the following else clause to validate the credit card number. The code uses str_replace() functions to remove any dashes and spaces in the number. Then, a nested if...else statement checks whether the new value is numeric. If the number is not numeric, a warning is printed. If the number is numeric, the modified credit card number is printed to the browser.
else {
$Payment = $_GET['ccnumber'];
$ValidPayment = str_replace("-", "", $Payment);
$ValidPayment = str_replace(" ", "", $ValidPayment);
if(!is_numeric($ValidPayment))
echo "< p>You did not enter a valid credit card number!< /p>";
else
echo "< p>Your credit card number is $ValidPayment.< /p>";
}
8. Save the document as ValidateCreditCard.php in the Projects directory for Chapter 5.
9. Open ValidCreditCard.php in your Web browser by entering the following URL: http://localhost/PHP_Projects/Chapter.05/Projects/ValidateCreditCard.php. Test the form to see if it correctly strips dashes and spaces from the numbers you enter. Also check whether the form only allows you to enter numeric values.
10. Close your Web browser window.