Setting up a Makeshift Test Environment for Experimenting with PHP Code
There are times I need to experiment with new code or re-familiarizing myself with code already in use. But there are times when other project code (sending out emails, updating databases, etc.) gets in the way of the tests. The code could be commented out to prevent it from executing, but that may be more work than it's worth. Plus I may forget to uncomment something when the tests are over. Instead, it can be easier to create a new file and focus on the code at hand.
Example Problem
I've developed several management tools where customers can submit information and make modifications to their submissions throughout the year. In some of the forms a reference ID is passed to indicate which database record they are trying to update. When the form is submitted, several checks are done on the back-end to make sure the request is valid. One of those checkpoints is to make sure the reference ID only contains numbers.
The code in place for validating the ID works fine, but I've been looking for a more efficient way. Well recently I heard about a PHP function called ctype_digit() which checks if a string only contains numbers. Although the function looks promising, I wanted to run some tests before making the switch. And due to the complicated nature of the forms, I started a new page before running the tests.
Testing the Code
There are multiple ways to set up your testing environment, but some are more efficient than others depending on how many scenarios you plan to run through. For example, you could create a variable which holds the test value, run the test, and display the results.
<?php
$value_to_test = '8000';
if(ctype_digit($value_to_test)) {
    echo "$value_to_test is a number";
} else {
    echo "$value_to_test contains characters other than numbers";
}
?>
But this solution gets a little cumbersome with multiple values. Every test requires that you modify the $value_to_test variable and re-upload the script.
When there are many values to test, I prefer to pass the test value through the URL (http://www.example.com/testcode.php?value=8000 for example). Then I just need to use $_GET to retrieve the value.
<?php
$value_to_test = $_GET['value'];
if(ctype_digit($value_to_test)) {
    echo "$value_to_test is a number";
} else {
    echo "$value_to_test contains characters other than numbers";
}
?>
Now I can test until my heart is content without needing to re-upload the code.
0 Comments
There are currently no comments.
Leave a Comment