In this article, we show how to create a global variable in PHP.
A global variable is a variable that can be used in any part of a PHP program. The opposite of this is a lcoal variable, which is a variable that can only be used in a certain part of a program.
To create a global variable in PHP, all you have to do is put the keyword global in front of the variable.
So if we have a variable named $variable_name, to make this variable a global variable, you simply put global in front of the variable.
global $variable_name;
So if now the variable_name is a global and can be used in any part of our PHP program.
When would we want to make a variable global?
A perfect example may be in a function.
If a variable is declared and initialized in a function, it is a local variable. It can only be utilized in that function.
If you try to get its value outside of the function, you will not be able to do so. It's only local to that function. Only through the function would you be able to access it.
However, if you declare that variable global within the function, then it can be used and accessed outside of the function.
Let's say we have the code shown below.
function uservalue()
{
$number= 2;
}
echo "This is the number: $number"; //This will produce a blank number output
So we have a function called uservalue().
This function has a variable that has been set to the value of 2.
If we then try to access this function outside of this function in any way, we will not be able to do so.
It's local only to the uservalue() function.
So when we echo out the value of the number, it will be a blank output. The $number variable cannot be accessed outside of the function.
However, if we make this variable, it can.
Below is the code making this variable global.
function uservalue()
{
global $number;
$number= 2;
}
echo "This is the number: $number"; //This will produce an output
Now this code will produce 2 at the output for the $number variable.
This is because the $number variable is now global.
It can be referenced now even outside of the function.
So this is just a quick tutorial on making a PHP variable global.
Related Resources
How to Retrieve Data from a Radio Button with PHP
There are two methods which you can use to retrieve information from a web form, the POST and GET
methods.
In this article, we discuss the difference between the POST and GET method, so you can know which one to utilize during information retrieval of form data.
Difference Between POST and GET MethodPOST Method
The POST method retrieves information and can add it directly to a web form. Let's say you have
the following web form below which asks for a user's first name, last name, email address, and telephone number.
<fieldset>
<form action="customerinfo.php" method="POST">
<table>
<tr><td><label>First Name:</label></td><td><input type="text"name="FirstName"/></td></tr>
<tr><td><label>Last Name:</label></td><td><input type="text"name="LastName"/></td></tr>
<tr><td><label>Email Address:</label></td><td><input type="text"name="EmailAddress"/></td></tr>
<tr><td><label>Telephone Number:</label></td><td><input type="text"name="TelephoneNumber"/></td></tr>
</table>
<input name="form" type="submit" value="Submit"/>
</form>
</fieldset>
The POST method can take all these filled-in fields of the form and write them to a web page, such as the confirmation page that this form creates when the submit button is pressed.
The POST method is the most used method when retrieving information from an HTML form using PHP.
GET Method
The GET method retrieves the information from a form and appends it to the URL of the website in use. Unlike the POST method, it cannot output information directly to a web page, but adds the user-added information from the form fields to the URL.
Below is the same exact form above but with the method of the form action attribute changed to "GET".
<fieldset>
<form action="customerinfo2.php" method="GET">
<table>
<tr><td><label>First Name:</label></td><td><input type="text"name="FirstName"/></td></tr>
<tr><td><label>Last Name:</label></td><td><input type="text"name="LastName"/></td></tr>
<tr><td><label>Email Address:</label></td><td><input type="text"name="EmailAddress"/></td></tr>
<tr><td><label>Telephone Number:</label></td><td><input type="text"name="TelephoneNumber"/></td></tr>
</table>
<input name="form" type="submit" value="Submit"/>
</form>
</fieldset>
Once you fill in the form fields and press the submit button, just like before, it takes you to a confirmation page but does not print the data to the web page, like the POST Method.
However if you look at the URL, you can see the information appended to the URL.
So, for example, if you typed in "Peter" as the first name, "Williams" as the last name, "PeterWilliams@yahoo.com"
as the email address, and "800-489-7849" as the telephone number, you will see as output the URL:
http://learningaboutelectronics.com/Articles/Difference-between-the-post-and-get-method-in-PHP?
FirstName=Peter&LastName=Williams&EmailAddress=PeterWilliams@yahoo.com&TelephoneNumber=800-489-7849
&form=Submit+Query
This URL broken down so that you can see better is:
http://learningaboutelectronics.com/Articles/Difference-between-the-post-and-get-method-in-PHP
?FirstName=Peter&LastName=Williams&EmailAddress=PeterWilliams@yahoo.com&TelephoneNumber=800-489-7849&form=Submit+Query
This is how the GET method works.
Because of its functions, it is used much less than the POST method. Also, because it appends
all of the user's information to the URL, it is much less secure and safe to use than the POST method.
Create a Line Break
In this article, we show how to create a line break in PHP.
Many times when writing PHP code, you may need to add a line break to space out PHP lines appropriately.
To create a line break in PHP, you use the line:
echo "<br>";
This line creates a line break so that any new information that is entered appears on the next line.
With data on the line, a concatenation operator (.) must be used with the br tag in double quotes, not single quotes.
If placed in single quotes, the PHP echo statement will display the output, just as is.
If placed in double quotes, the PHP echo function will process what is inside of the quotes, meaning the br tag and create a line break.
The difference between single and double quotes in PHP is that, with single quotes, the PHP echo command passes functions, exactly as is, and with double quotes, the information, variables, HTML commands, etc, gets processed.
An example is shown below:
echo "This is a line with a br tag added to create line space<br>";
This statement above will create a line break so that the next statement you write will start on a new line.
Example
These students are going on the trip:1)Sarah 2)Bill 3)Ryan
You can see in this example how everything is jumbled on one line.
It would be much better put on separate lines.
Below are the statements with line breaks:
These students are going on the trip:<br>1)Sarah<br>2)Bill<br>3)Ryan
PHP Code
The PHP Code to create the above code is:
<?php
echo "These students are going on the trip:<br>";
echo "1)Sarah<br>";
echo "2)Bill<br>";
echo "3)Ryan<br>";
?>
Format and Display the Date
In this tutorial, we go over how to format and display dates in PHP.
PHP offers a great deal of dynamic ability to display dates in pretty any format we would like to.
We can display the day alone, the month alone, the year alone, or any combination of these 3. We can display the year with the last 2 numbers such as 13 or we can display the full 4 numbers, 2013.
We can show dates separated by slashes (ex. 1/12/2012) or show dates separated by dots (1.12.2012).
PHP offers a wide range of options.
To format and display the date in PHP, the date() function is used.
The date() function uses 4 characters to help denote the date, shown below:
Character
Description
Y
A four-digit year such as 2012
y
A two-digit year such as 12
m
Displays the month with leading zeroes (01)(for january)
d
Dispalys the day with leading zeroes (09)(for the 9th of the month)
Formatting the DateYear-month-day
$date= date('Y-m-d'); // 2012-02-10
month/day/year
$date= date('m/d/y'); // 02/10/12
month.day.Year
$date= date('d.m.Y'); // 10.02.2012
Year
$date= date ('Y'); // 2012
Displaying the Date
Once you have formatted the date above and assigned it to a variable, you then display the date
by using the echo function to display the date.
$date= date('Y-m-d');
echo $date; // 2012-02-10
$date= date('m/d/y');
echo $date; // 02/10/12
$date= date('d.m.Y');
echo $date;// 10.02.2012
$date= date ('Y');
echo $date; //2012
Actual PHP Output
2022-02-22 02/22/22 22.02.2022 2022
Note- PHP's date() function is very useful and used because it displays the real-time date. This isn't a function used to display past dates. For past static dates which don't change, you can just manually type in the date with plain HTML. PHP's date() function is used because it always provides the current real-time date. This is why you see the today's current date
above below the Actual PHP Output. Javascript has a similar function which allows real-time current dates to be shown as well.
Generate a Random Number
To generate a random number in PHP, we use the mt_rand function.
The general form to generate a random number is:
$random_number= mt_rand(minimum_number_range, maximum_number_range);
where
minimum_number_range is the minimum number value that the mt_rand function can generate
maximum_number_range is the maximum number value that the mt_rand function can generate
The $random_number variable stores the random number which you generate from the mt_rand() function.
For example, if you want to generate a random number from 50 to 70, the minimum number range would be 50 and the maximum number range would be 70, because you want to generate a random number between 50 and 70.
Example
To generate and display a number from 1 to 100, the code to do this is:
$random_number= mt_rand(1, 100);
echo $random_number;
Actual PHP Output
Refresh this page to see a new generated random number:
11
Find and Replace Text
In this article, we will go over how you can find and replace text in PHP.
The function to find and replace text in PHP is the str_replace() function which accepts the following parameters in the format:
str_replace(text_to_replace, word/phrase_to_replace_text_with, which_block_of_text_this_affects);
This function will now be explained:
text_to_replace- The first parameter is the word/phrase which you want to replace. For example, if you want to replace the word 'John' in your paragraph with the word 'Kevin', John is the word that you want to replace. Therefore, it would be the first parameter of the str_replace() function.
word/phrase_to_replace_text_with- This is the parameter of the word you want to replace the text with. Let's use the same example as before. If you want to replace the word 'John' with 'Kevin', Kevin would be the 2nd parameter of this function, since you want 'Kevin' to replace 'John'.
which_block_of_text_this_affects- This is the of the block of code which you want the find/replace function to apply to. This can be a paragraph tag, a text box, a text area, any element on the web page. For example, if you want to carry out this function on a paragraph tag with a name attribute of paragraph1, then paragraph1 would be the 3rd parameter.
Example
Now that we've gone over the str_replace() function, let's do an example to get a practical and real-world feel of it.
Below rare 2 text boxes and 1 text area. You can type your main text into the text area and can find and replace strings with the text boxes.
<form action="#replace" method="post">
Find: <input type="text" name="find" value=''/>
Replace: <input type="text" name="replace" value=''/>
<input type="submit" name="submitbutton" value="Replace"/>
</form>
You can see above that the main text area to type your text into is the text area, which is a multi-line input
area for typing text, such as a paragraph. The text boxes above this text area are the Find and Replace text boxes. These text boxes will find the text you want and replace it with the text you want, much like a standard Find & Replace feature that are common to many text editors or word programs, such as Microsoft Word and Notepad.
HTML Code
The HTML Code to create the above text boxes and text area is:
<form action="" method="post">
Find: <input type="text" name="find" value='<?php echo $find; ?>'/><br><br>
Replace: <input type="text" name="replace" value='<?php echo $replace; ?>'/><br><br>
<input type="submit" value="Replace"/><br><br>
<textarea name="maintext" rows="8" cols="80"><?php echo $newtext; ?></textarea>
</form>
Notice how all the form fields must have a name attribute. This is because we use this name attribute to allow PHP to extract data from each of the form fields, as
you'll see below. PHP uses the name attribute to know which form field you are referring to.
PHP Code
The PHP code to create the find/replace function is:
<?php
$find= $_POST['find'];
$replace= $_POST['replace'];
$text= $_POST['maintext'];
$submitbutton= $_POST['submitbutton'];
if (isset($find) && isset($replace))
{
$newtext= str_replace($find, $replace, $text);
}
?>
The PHP code extracts the information from each of the form fields. If it finds the word present which you want to replace in the text area of the main text, it will replace it with the text on the 'Replace' form field.
We extract the data from the form fields with the superglobal $_POST array. If the $find and $replace variables are set, then we carry out the str_replace function and assign it to the variable $newtext.
If you go back to the HTML code above, we echo out this $newtext in the text area, so that when the user presses the 'Replace' button, the new updated text will be displayed. This, again, is echoed between the <textarea></textarea>
tags.
And this is how you can create a Find/Replace functionality on a web page.
Related Resources
How to Upload Images to a Website Using PHPHow to Upload Files to a Website Using PHPHow to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP
Remove Whitespace from a String
In this article, we show how to remove whitespace either from the left side of a string or the right side of a string using the PHP trim() function.
The trim() function erases white space from the left and right side of a string.
This will be demonstrated below.
So, if we have the string "GPS ", after passing it through the trim() function, the string
would then change to "GPS".
The trim() function erases white space from the left and right sides of a string. So if the string is " GPS", and we apply the trim() function, it would change to "GPS". Similarly, the string, " GPS ", would change to "GPS".
Example
Below is an example of the trim() function in action, which removes all whitespace from the left and right side of a string
<php
$string1= "GPS ";
$string2= " GPS";
$string3= " GPS ";
$trimmed1= trim($string1);
$trimmed2= trim($string2);
$trimmed3= trim($string3);
echo $trimmed1 . "<br>";
echo $trimmed2 . "<br>";
echo $trimmed3 . "<br>";
?>
Actual PHP Output
GPS GPS GPS
The trim() function is a very useful and powerful PHP function. An example of prime use of the trim() function is a search box, where a user enters in a search term. For example, say if a user is looking up hotels in Hawaii, he or she may add a space at the beginning or end of the search query by mistake. In PHP, " hotels" is not equal to "hotels". To prove this, let's run the following PHP code.
<?php
if ("hotels" == " hotels"){
echo "These two are the same";
}
else {
echo "These two are not recognized as the same";
}
?>
The output of the above PHP code is:
These two are not recognized as the same
So you can see that PHP does not recognize the 2 strings as being equal. "hotels" is not the same as " hotels". Neither is "hotels " the same as "hotels". However, if a user enters
in these search queries, we know that the search queries mean the same thing. To make them the same, we use built-in PHP trim() function. This erases all white space before the beginning of a string and all white space after the end of a string. After we use it, then all the search queries will be the same, despite the white space.
To prove this, run the following PHP code:
<?php
$string1= "hotels";
$string2= " hotels";
$string3= "hotels ";
echo "Before the trim() function ";
if ($string1 == $string2){
echo "These 2 strings are the same ";
}
else {
echo "These 2 strings are not the same ";
}
if ($string1 == $string3){
echo "These 2 strings are also the same
";
}
else {
echo "These 2 strings are also not the same
";
}
$trimmed1= trim($string1);
$trimmed2= trim($string2);
$trimmed3= trim($string3);
echo "After the trim() function ";
if ($trimmed1 == $trimmed2){
echo "These 2 strings are the same ";
}
else {
echo "These 2 strings are not the same ";
}
if ($string1 == $string3){
echo "These 2 strings are also the same ";
}
else {
echo "These 2 strings are also not the same ";
}
?>
The output of the above PHP code is:
Before the trim() function These 2 strings are not the same These 2 strings are also not the same
After the trim() function These 2 strings are the same These 2 strings are also the same
So this is the perfect example to illustrate the power of the PHP trim() function to equalize strings that vary only in the white space before or after them.
How to Remove All Spaces in a String
So the PHP trim() function we demonstrated above removes whitespace from the front or end of a string.
If we want to remove all spaces in a string with PHP, the trim() function would not be used. Instead,
we could use the str_replace() function in the following way.
<?php
$string= "What day of the week is July 4th this year?";
$string= str_replace(" ", "", $string);
echo $string;
?>
The str_replace() takes in 3 parameters. The first parameter is the character(s) you want to replace. The second
parameter is what you want to replace it with. And the third parameter is the string that you want to change, the object of the replacement.
Since we want to replace whitespace with none, the first parameter is whitespace (" "). The second parameter is to replace the whitespace with none (no whitespace). The third parameter is the string that we want to manipulation with these replacements.
This will remove all whitespace from a string.
Actual PHP Output
WhatdayoftheweekisJuly4ththisyear?
Sometimes this may be the case where you want to remove all whitespace from a string. Usually this is not the intention.
The trim() function is more popular, especially when considering search queries. Normally whitespace just needs to be removed from the beginning or end of a string.
However, we demonstrate how to do both just in case you need to use both approaches.
Capitalize the First Word of a String
In this article, we go over how to capitalize the first word of a string in PHP using the ucfirst() function.
The ucfirst() function capitalizes the first word in a string.
So, if we have the string "bob went to the park today", after passing it through the ucfirst() function, the string
would then change to "Bob went to the park today."
Example
Below is an example of the ucfirst() function in action.
<php
$string= "bob went to the store";
$capitalized= ucfirst($string);
echo $capitalized;
?>
Actual PHP Output
Bob went to the storeThe ucfirst() function is the function to use when you want to capitalize the first word in a string.
Capitalize Each Word of a String
In this article, we go over how to capitalize each (and every) word in a string using the ucwords() function.
The ucwords() function capitalizes the first letter of all the words in a string.
So, if we have the string "wild at heart", after passing it through the ucwords() function, the string
would then change to "Wild at Heart".
Example
Below is an example of the Ucwords() function in action.
<php
$string= "wild at heart";
$capitalized= ucwords($string);
echo $capitalized;
?>
Actual PHP Output
Wild At HeartThe ucwords() function is the function to use when you want to capitalize the first letter of all the words in a string. This is useful for such strings as headlines or titles of articles or books, where all words are usually capitalized.
PHP- print_r() Function
In this article, we will go over the PHP print_r() function.
The print_r() function is a function which can be used to show the contents, or make-up, of an array.
Let's say, for example, we create the following array in PHP.
$students= array("Steve", "Bob", "Tom", "Gary");
If we just used the following line to show display the array, it would not work:
echo $students;
This would produce the following output in PHP:
Array
An array is a special object in PHP. A programmer cannot print out the contents of an array, as shown above, simply with the echo or print function.
However, applying the print_r() function, can be used for showing all of the contents of an array.
So the line of code would be:
print_r($students);
The above line of code would yield the following in PHP:
Array
(
[0] => Steve
[1] => Bob
[2] => Tom
[3] => Gary
)
The following print_r() function shows all of the contents of the array. Since we created an array of 4 elements, the array has elements with keys of 0-3. 0 is the first element and 3 is the last element. Since our first element is "Steve", it is assigned to the 0 key. Since our second element is "Bob", it assigned to key 1. Since our third element is "Tom", it is assigned to key 2. Since our fourth element is "Gary", it is assigned to key 3.
Thus, the print_r() function will show all the keys and values of an array.
Another Example
The print_r() function can be used with any type of array.
Another example we will show its use with is an array where the elements are assigned a value.
Let's create the array:
$children= array("Peter"=>age 7, "John"=>age 4, "Lisa"=>age 9);
If we print out the following line with the print_r() function, with the line:
print_r($children);
This line would produce the following PHP code:
Array
(
[Peter] => 7
[John] => 4
[Lisa] => 9
)
You can see that now because of the print_r function, we can see that the keys for the $children array are "Peter", "John", and "Lisa" and the values are 7, 4, and 9.
This can be a good array if we wanted to have an array with a list of children and their ages.
We can also assign strings to strings for arrays.
Check out the following array:
$people= array("James"=>gmail, "Scott"=>yahoo, "Fred"=>gmail);
When printing this out, with the line:
print_r($people);
We get the following PHP output:
Array
(
[James] => gmail
[Scott] => yahoo
[Fred] => gmail
)
This is a good array when you have a list of people with the type of email accounts they have.
This is how the print_r function works. It is a good function for finding out all of the contents of an array, the keys and values, for troubleshooting purposes.
It normally is not
used just to display the array, since it is formatted so strictly. There are better ways to display an array that comes out in a much prettier manner.
PHP- foreach Loop
In this article, we will go over the PHP foreach loop.
The foreach loop allows us to print out all the contents of an array.
The foreach loop goes through each element of an array, one by one, and using an echo statement, we can print out the contents of an array. The number of times the loop will execute will be equal to the number of elements in the array.
There are 2 ways for that the foreach loop can be used. If an array only has values assigned to them, with no keys, we use the foreach loop, only to specify the values of each of the elements in the array. This is shown in the first example.
The 2nd way we can use the foreach loop is with arrays with the keys and values specified. This is shown in the second example.
foreach Loop with Only Values
Say, that we have an array that only has values specified, and not keys.
For example, let's take the following array below:
$ages= array(10, 12, 15, 16, 17);
For an array like this, many times we are only interested in the values of the elements of the array. Even though PHP creates the keys 0, 1, 2, 3, 4 as an index, many times we aren't interested in these values. We just want to know the values of the elements in the array.
Using the foreach loop in the following format below, we can print out all the values of the above array:
<?php>
$ages= array(10, 12, 15, 16, 17);
foreach ($ages as $value)
{
echo "$value<br>";
}
?>Actual PHP Output
10 12 15 16 17
You can see that the foreach loop prints out all of the elements of the array.
Realize that although the variable $value is used with the as keyword, it can be named anything.
We can change value to $value to $kids, so that our new code is:
<?php>
$ages= array(10, 12, 15, 16, 17);
foreach ($ages as $kids)
{
echo "$kids<br>";
}
?>
In other words, PHP will know that the variable after the as keyword is the variable which stores the values of the array, and it can be named anything.
Foreach loop with Keys and Values
The other way a foreach loop can be used is to specify both the keys and values of an array.
Let's say we have the following array below:
$children= array("John"=>11, "Peter"=>12, "Bill"=>10);
Here in this array, the keys are John, Peter, and Bill. The values are 11, 12, and 10. Here, the keys represent the names of the children and the values represent their ages.
So when printing out the array, we want to know and print out both the keys and values of each element of the array.
And we can do this, using the foreach loop in the following format:
<?php
foreach($children as $key=>$value)
{
echo "$key is $value years old<br>";
}
?>Actual PHP Output
John is 11 years old Peter is 12 years old Bill is 10 years old
Here print out all the children names along with their ages.
Again, just like with the first loop, we don't have the use the variables $key and $value; we can really names these variables anything.
For example, we can change them to $name and $age, so that you can know what each one represents.
So we can change the above code to:
<?php
$children= array("John"=>11, "Peter"=>12, "Bill"=>10);
foreach($children as $name=>$age)
{
echo "$name is $age years old<br>";
}
?>
And it will work the same as the before code.
Printing the key and value of an array can also work for arrays where only values are specified.
Say, we have the following array:
$children_ages= array(10, 9, 8, 12, 13, 7);
The keys which will be created for this array by PHP are 0-5, to represent each element.
Even though we created an array and only specified values, we can also print out the assigned keys which PHP creates for them, starting with index 0 and going up 1 each successive element.
To print out the above array $children_ages, we use the code:
<?php
$children_ages= array(10, 9, 8, 12, 13, 7);
foreach ($children_ages as $key=>$value){
echo "Key $key is $value$lt;br>";
}
?>Actual PHP Output
Key 0 is 10 Key 1 is 9 Key 2 is 8 Key 3 is 12 Key 4 is 13 Key 5 is 7
So even though we did not specify keys with the array, PHP automatically assigns integer keys to the array, and we can output each integer keys with the code above.
And this is how foreach loops work. They go through each element of an array and can echo out either the value alone or the key and the value.
Check if a Variable is Empty
In this article, we go over how to check if a variable is empty or not in PHP.
To check if a variable is empty in PHP, you use the empty function in PHP.
empty($variable)
Below is code that uses an if statement to check if the variable $name is empty or not.
If it is empty (contains nothing), the statement, 'The string is empty' is displayed. If it isn't (contains something), it echos the statement, 'The string is not empty'.
if (empty($name)) {
echo 'The string is empty'
}
else {
echo 'The string is not empty';
If the string $name is empty, it will print the first echo statement.
If the string is not empty, it will print out the last echo statement.
Example
<form action="#form1" method="POST">
<label>Enter your first name:</label><input type="text" name="first_name">
<input type="submit" name="submit" value="submit"/>
</form>
You have left the name field empty. You must enter a name.
HTML Code
The following code below is the HTML code needed to create the form shown above.
<form action="" method="POST">
<label>Enter your first name:</label><input type="text" name="first_name"><br>
<input type="submit" name="submit" value="submit"/>
</form>
PHP Code
Since the name attribute of the text box in HTML was first_name, the
PHP code to generate the program above is:
<?php
$first_name= $_POST['first_name'];
$submitbutton= $_POST['submit'];
if ($submitbutton){
if (empty($first_name)) {
echo 'You have left the name field empty. You must enter a name.';
}
else {
echo 'The name that you entered is ' . $first_name;
}
}
?>
The code above works very well but there is one problem with this code, though.
It's usually not desired to show that the form hasn't been empty before a user has even clicked the submit button.
For example, when you first reach a form on a website to fill in, you normally don't want to see the message, "You left this field blank" before you even got a chance to fill in the form.
Therefore, it normally is not desired to show the statement, "You have left the name field empty. You must enter
a name" until you have clicked the submit button and really left it empty while trying to submit the form.
To remedy this, we need to get data from the submit button to determine if it has been clicked or not. If it has not been clicked, we don't want to display the statement, "You have left the name field empty. You must enter a name", until the user
clicks the submit button and left it empty.
Second Example
The example again is shown below.
<form action="#form2" method="POST">
<label>Enter your first name:</label><input type="text" name="first_name2">
<input type="submit" name="submit2" value="submit"/>
</form>
This code now probably mirrors what you more want.
If a user has now left a field empty and clicked the submit button of the form, then we echo that s/he has left
the field blank which needs to be filled. If a user has filled in the field and clicked the submit button, then we echo the name
that the user has entered.
The HTML code to build the example right above is unchanged.
PHP Code
The PHP code to build the example above is shown below.
<?php
$first_name= $_POST['first_name'];
$submitbutton= $_POST['submit'];
if ($submitbutton){
if (empty($first_name)) {
echo 'You have left the name field empty. You must enter a name.';
}
else {
echo 'The name that you entered is ' . $first_name;
}
}
?>
So this is a very easy way of checking if a variable is empty or not in PHP.
Measure the Length of a String
We will show you how using PHP, you can measure the length of a string to find out how many characters
are in the string.
This can be useful in very applications such as when a user is typing a string into a form field, such as a password, and the password must be between a range of characters, such as between 6 and 25 characters.
We measure the string that the user enters when registering a password. If the password is less than 6 characters
or greater than 25 characters, we can send a message, stating to the user that this password
is not acceptable.
PHP Code to Measure the Length of a String
To meausre the length of a password in PHP, we use the strlen() function in
PHP, following the format below:
<?php
$fruit= "Cantaloupe";
$length_of_string= strlen($fruit);
echo "The string length of the fruit cantaloupe is $length_of_string";
?>
Actual PHP Output
The string length of the fruit cantaloupe is 10
To find the length of a string in PHP, all we must do is put the string inside of the strlen() function either directly by the string being enclosed in double quotes ("") or by variable.
Since the word 'Cantaloupe' has 10 letters, the PHP strlen function will return '10' as output.
String Length Measurer
Enter any string into the text box below. Once you enter a string and press the 'Find Length of String' button, it will output the length of that string in the text box right beneath it.
<form action="#result" method="POST">
Enter string: <input type="text" name="string_value" value=''/>
Length of String: <input type="text" value='' READONLY/>
<input type="submit" name="submitbutton" value="Find Length of String"/>
</form>
This text box, above, again takes the string and computes its length through the strlen() function.
HTML Code
The HTML code to create the above text boxes and submit button are:
<form action="" method="POST">
Enter string: <input type="text" name="string_value" value='<?php echo $string; ?>'/>
Length of String: <input type="text" value='<?php echo $length; ?>' READONLY/><br>
<input type="submit" value="Find Length of String"/>
</form>
PHP Code
The PHP code to compute the length of the entered string is:
<?php
$string= $_POST['string_value'];
$submitbutton= $_POST['submitbutton'];
if (isset($submitbutton)){
$length= strlen($string);
}
?>
PHP extracts the information entered into the text box and assigns it to the $string variable. It then uses the strlen() function to find the length of this string, which it stores inside of the $length variable. This variable is then output into the second text box to show the length of the entered string.
Get the Current Page URL of a Web Page
In this tutorial, we show how to get the current page URL of a web page using PHP.
Full URL of Current Page
To get the full URL of the current page, which takes the form http://www.website.com/Directory/pagename.html, you can use the following code below.
<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
The $_SERVER['HTTP_HOST'] gets the www.website.com name of the website in use. For this web page you are current on, this would return www.learningaboutelectronics.com
The $_SERVER['REQUEST_URI'] returns the directory pathway and file name of the page you are on.
Actual PHP Output of this Page
http://www.learningaboutelectronics.com/Articles/How-to-get-the-current-page-url-of-a-web-page-using-PHP.php
Directory Pathway and File name
To return just the directory pathway and the file name of the web page, you can use the following code below.
This is the part after http://www.website.com/
<?php echo $_SERVER['REQUEST_URI'];
?>
So this code above returns the part after the type of domain name the web page is.
Actual PHP Output of this Page
/Articles/How-to-get-the-current-page-url-of-a-web-page-using-PHP.php
Just the Directory Pathway
To return just the directory pathway of the current web page URL, you can use the following code below.
<?php
$url= $_SERVER['REQUEST_URI'];
$positionslash= strrpos($url, "/");
$pathway= substr($url, 0, $positionslash);
echo $pathway;
?>
This code above returns just the directory pathway to the current page URL.
Just the File Name
To just return the file name of the current page, you can use the following code below.
<?php
$url= $_SERVER['REQUEST_URI'];
$positionslash= strrpos($url, "/");
$filename= substr($url, $positionslash + 1);
echo $filename;
?>
This code above returns only the file name of the current page URL.
Actual PHP Output of this Page
How-to-get-the-current-page-url-of-a-web-page-using-PHP.php
Just the File Name Without the File Extension
Sometimes you may just want to return the file name without the file extension.
To do this, you can use the following code below.
<?php
$url= $_SERVER['REQUEST_URI'];
$positionperiod= strpos($url, ".");
$extensionremoved= substr($url, 0, $positionperiod);
$positionslash= strrpos($extensionremoved, "/");
$filename_without_extension= substr($extensionremoved, $positionslash + 1);
echo $filename_without_extension;
?>
The code above returns just the file name without the file extension included.
Actual PHP Output of this Page
How-to-get-the-current-page-url-of-a-web-page-using-PHP
Related Resources
How to Create a Global Variable in PHPDifference between the POST and GET Method in PHPHow to Create a Line Break in PHPHow to Format and Display the Date in PHPHow to Generate a Random Number in PHPHow to Find and Replace Text in PHPHow to Remove Whitespace from a String in PHPHow to Capitalize the First Word of a String in PHPHow to Capitalize Each Word of a String in PHPPHP print_r() functionPHP foreach loopHow to Check if a Variable is Empty In PHPHow to Measure the Length of a String in PHP
Merge Arrays
To merge arrays in PHP, the array_merge function is used with the following general syntax, as shown below:
array_merge($array1, $array2, ...)
where
$array2 is now appended to $array1
The array_merge function returns an array with the elements of two or more arrays into a single array.
Example
So if we wanted to join together two arrays, $Male_students and $Female_students, we would do it with the following code.
$Male_students= array('John', 'Steve', 'Rick', 'Greg');
$Female_students= array('Lisa', 'Michelle', 'Elizabeth');
$All_students= array_merge($Male_students, $Female_students);
echo implode (', ', $All_students);
The implode function decides what separates the elements in the two arrays. In this example, we specify and separate them with a comma (, ).
Actual PHP Output
John, Steve, Rick, Greg, Lisa, Michelle, Elizabeth
Example Merging 3 Arrays
If you want to merge three arrays together, an example of PHP code to do so would be:
$Group1= array ('John', 'Michelle', 'Jeff');
$Group2= array('Steve', 'Elizabeth', 'Lisa');
$Group3= array('Rick', 'Greg', 'Kobe');
$Total_groups= array_merge ($Group1, $Group2, $Group3);
echo implode (', ', $Total_groups);Actual PHP Output
John, Michelle, Jeff, Steve, Elizabeth, Lisa, Rick, Greg, Kobe
As can be seen, we can merge as many arrays as we want with the array_merge function.
Fill an Array
In this article, we go over how to fill an array in PHP.
To fill an array means to load it with a certain number of elements of a specified value, such as:
all 100s: 100, 100, 100, 100, 100
all 50s: 50, 50, 50, 50, 50, 50, 50, 50, 50, 50
The reason why some languages such as PHP have a function to fill an array is to save time for the programmer. Say, if a programmer wants an array with 70 repeated 100 times in the array. Without the array_fill function, a programmer would have to manually type out '70' 100 times. This is tedious. With the array_fill function, we just type in '70' and how many times we want it repeated. This way, we save a lot of time programming.
To fill an array in PHP, we use the array_fill PHP function using the following general syntax:
$array_name= array_fill($start, $count, $value)
where
$start is the index at which the array starts
$count is the number of elements that is in the array
$value is the value of each of the elements in the array
So the array_fill function returns an array filled with $count $values starting at index
$start.
Example
So, to create an array that has 7 elements of the number 10 and starts at index 0, the PHP code to do this would be:
$array_name= array_fill(0, 7, 10) //10, 10, 10, 10, 10, 10, 10PHP Output
10 10 10 10 10 10 10
So the array is filled with 7 10s.
Pad an Array
Padding an array means adding elements to an array.
This could adding elements to the beginning of the array or the end of the array.
Below is an example of an array:
(10, 2, 4, 5, 6)
Padding 4 7s to the end of the array would produce:
(10, 2, 4, 5, 6, 7, 7, 7, 7)
So, again, padding an array just means appending new elements to the array.
To pad an array, we use the array_pad PHP function using the following general syntax below:
$array_name= array_pad($array, $size, $value);
where
$array is the original array in which you want to pad elements onto
$size is number of elements that the new padded array will contain in total
$value is the value of the elements which are padded onto the array
So the array_pad function returns an array with $value added to the end of
$array until it contains $size elements. If $size is negative, the value is added to the start of the array.
Examples
If we have our orignal array named $numbers and we want to pad onto it 3 10s, the PHP code to do this would be:
$numbers= array(7, 2, 3, 4, 8);
$numbers_2= array_pad($numbers, 8, 10);PHP Output
7 2 3 4 8 10 10 10
In this example, $size is 8, since we want the total number of elements in our array to be 8 in total when the 3 10s are padded onto it. And $value is 10, since we want to add 10s into the array.
In the example above we padded elements onto the end of the array. In this example, we will pad elements to the beginning of an array. We will use the same array as our last example and pad on the same 3 10s, but this time to the beginning of the array.
The PHP code to do so is:
$numbers= array(7, 2, 3, 4, 8);
$numbers_2= array_pad($numbers, -8, 10);PHP Output
10 10 10 7 2 3 4 8
In this array, we have almost identifical conditions to our first example. The only difference is the minus sign ("-") in front of the $size. The value of 8 is still the same, since
the total number of elements in the array will still be 8, but with the minus sign in front of the 8, the new elements will be padded to the beginning of the array and not to the end of it.
Slice an Array
In this tutorial, we go over how to slice an array in PHP.
Slicing an array means cutting off part of the whole array so that you only have a part of the array
remaining in the end. Essentially, you're cutting off part of it.
Any part of an array can be sliced off.
Below is an example of an array:
(Greg, Steve, John, Harry, Tom, Bill, Dwayne)
Now the array is sliced from John all the way to the end of the array to Dwayne, so that it leaves
the following array:
(John, Harray, Tom, Bill, Dwayne)
So Greg and Steve got sliced out of the array.
This is what is meant by slicing an array, cutting off or erasing part of the array.
To slice an array in PHP, we use the array_slice function following the general syntax below:
array_slice ($array, $index, $len)
where
$array is the original array in which you want to slice
$index is the index number of the element that you start at and want to keep
$len is the number of elements that you want to keep
Array_slice returns part of an array starting from $index and containing $len elements.
If $len is omitted, it returns the elements to the end of the array.
Example
$Students= array('Greg', 'Lisa', 'Bobby', 'Tom', 'Troy', 'Matthew', 'Peter', 'John');
$Students_going_on_trip= array_slice($Students, 2);
echo implode (', ', $Students_going_on_trip);
Actual PHP Output
Bobby, Tom, Troy, Matthew, Peter, John
The above array originally has 8 elements, representing 8 names of students.
Here we only specify the $array and the $index. Since we specify an index of 2, we cut off all elements before index 2. Thus, 'Greg' and 'Lisa' are cut off, since they are before
index 2. We start at the name 'Bobby'. Since we don't specify the length of elements we want, we keeps all elements to the end of the array.
Now let's take the same array as above and slice not to the end but up until Matthew, which is index
element 5. The PHP Code to do this would be:
$Students= array('Greg', 'Lisa', 'Bobby', 'Tom', 'Troy', 'Matthew', 'Peter', 'John');
$Students_going_on_trip= array_slice($Students, 2, 4);
echo implode (', ', $Students_going_on_trip);
All we have to do is specify the number 4, because from index 2 to index 5, there are 4 elements (
2, 3, 4, 5). This will slice the array from Bobby to Matthew.
Actual PHP Output
Bobby, Tom, Troy, Matthew
Create an Associative Array
How to Create an Associative Array in PHP
To create an associate array in PHP, we can either create it all using one statement or we can do it in multiple statements.
One Statement
To create an associative array all in one statement, we must declare and initialize the values of the array all on one line.
We do this by the following general format:
$array_name= array('key1' => 'value1, 'key2' => 'value2', 'key3' => 'value3');
ExamplesInteger Assignment
$telephone_extensions= array('John' => 345, 'Lisa' => 678, 'Terry' => 456);
String Assignment
$Eye_color= array ('George' => 'Brown', 'Mary' => 'Blue', 'Marie' => 'Green');
Multiple Statements
To create an associative array in multiple lines, we first declare the array and then we
assign values to each element using separate lines.
The format to create an associative array using multiple lines is:
array_name= array();
array_name['key1']= value1;
array_name['key2']= value2;
array_name['key3']= value3;
ExamplesInteger Assignment
$telephone_extensions= array();
$telephone_extensions['John']= 345;
$telephone_extensions['Lisa']= 678;
$telephone_extensions['Terry']= 456;
String Assignment
$Eye_color= array();
$Eye_color['George']= 'Brown';
$Eye_color['Mary']= 'Blue';
$Eye_color['Marie']= 'Green';
As seen in the examples, when assigning a string value to an element in an array, we must enclose the string in single quotes (' '). When assigning an integer value, we use no quotes at all.
Actual PHP Output
John: 345 Lisa: 678 Terry: 456
George: Brown Mary: Blue Marie: Green
Display all of the Elements of an Associative Array
In this article, we show how to display all of the elements of an associate array in PHP.
To display all of the elements of an array in PHP, the foreach function is used.
We use the foreach function with the keyword as and then use the statement $key => $value
as the pair to show each part that makes up each element, the key and the value assigned to the key. This way, when the foreach function goes through each element of the array, we can display either the key of the array, or the value, or both, if we want.
Now, let's create an array and then go over the coding of how to display it:
$Eye_color= array();
$Eye_color['John']= 'Blue';
$Eye_color['Steve']= 'Brown';
$Eye_color['Michelle']= 'Green';
We've now created an associative array. The keys of the array are 'John', 'Steve', and
'Michelle'. The values of the array are 'Blue', 'Brown', and 'Green'.
Displaying the Entire Array
To display all of the elements of an associative array, we use the general format:
foreach ($array_name as $key => $value) {
echo "$key = $value <br>";
}
You can modify the echo statement output anything you want. But if want the output
of all the elements in the form of key = value, the above code is used.
The PHP code, then, to display all of the elements of the above array which we have created
would be:
<?php
foreach ($Eye_color as $key => $value) {
echo "$key = $value ";
?>
PHP Output
John = Blue Steve = Brown Michelle = Green
Sort Numbers of an Array in Ascending Order
In this article, we show how to sort numbers of an array in ascneding order in PHP.
To sort an array of numbers in ascending order in PHP, we use the sort() function.
Let's say we have the array of numbers below:
$numbers= array(48, 93, 4, 6, 21, 11, 32, 17);
And now we want this array to be shown and ordered in ascending order numerically.
We use the sort() function to put it in ascending order.
The general form to put an array of numbers in ascending order:
sort($array_name);
where $array_name is the name of the array we want to sort in ascending order numerically.
For the above array we created, the code to put it in ascending order is:
sort($numbers);
PHP Output
93 48 32 21 17 11 6 4
Sort Numbers of an Array in Descending Order
In this article, we show how to sort numbers of an array in descending order in PHP.
To sort an array of numbers in descending order in PHP, we use the rsort() function.
Let's say we have the array of numbers below:
$numbers= array(48, 93, 4, 6, 21, 11, 32, 17);
And now we want this array to be shown and ordered in descending order numerically.
We use the sort() function to put it in descending order.
The general form to put an array of numbers in descending order:
rsort($array_name);
where $array_name is the name of the array we want to sort in descending order numerically.
For the above array we created, the code to put it in descending order is:
rsort($numbers);
PHP Output
93 48 32 21 17 11 6 4
Sort Strings of an Array in Ascending Order
In this article, we show how to sort strings of an array in ascending order in PHP.
To sort an array of strings in ascending order in PHP, we use the sort() function.
Let's say we have an array of names below:
$class= array('Mike', 'Bob', 'Steve', 'Craig', 'Richard', 'Adam');
And now we want this array to be shown and ordered in ascending order by name.
We use the sort() function to put it in ascending order.
The general form to put an array of strings in ascending order:
sort($array_name);
For the above array we created, the code to put it in ascending order is:
sort($class);
PHP Output
Adam Bob Craig Mike Richard Steve
Sort Strings of an Array in Descending Order
In this article, we show how to sort strings of an array in descending order in PHP.
To sort an array of strings in descending order in PHP, we use the rsort() function.
Let's say we have an array of names below:
$class= array('Mike', 'Bob', 'Steve', 'Craig', 'Richard', 'Adam');
And now we want this array to be shown and ordered in descending order by name.
We use the rsort() function to put it in descending order.
The general form to put an array of strings in descending order is:
rsort($array_name);
For the above array we created, the code to put it in descending order is:
rsort($class);
PHP Output
Steve Richard Mike Craig Bob Adam
Find the Smallest Number in an Array
In this article, we show how to find the smallest number in an array in PHP.
To find the smallest number in an array in PHP, we use the min() function.
Let's say we have the array of numbers below:
$numbers= array(170, 210, 103, 375, 315, 470, 255);
Let's say these numbers represent prices of airline tickets that a user looks up. To find the cheapest price, we need to be able to pick out the smallest number in the array.
We use the min() function to find the smallest number in the array.
The general form to find the smallest number in an array is:
$smallest= max($array_name);
where $array_name is the name of the array and $smallest is the variable which contains the lowest numerical value of the array.
For the above array we created, the code to find the smallest number is:
$smallest= min($numbers);
Actual PHP Output
The smallest value in the array is 103
Finding the smallest value in an array is very crucial for many applications. With finding the smallest value, we can find the cheapest price, meal, airline tickets, hotel, taxi fare, etc.
For a tutorial on finding the largest number in an array, see
How to Find the Largest Number in an Array in PHP.
Find the Largest Number in an Array
In this article, we show how to find the largest number in an array in PHP.
To find the largest number in an array in PHP, we use the max() function.
Let's say we have the array of numbers below:
$numbers= array(103, 170, 210, 375, 315, 470, 255);
Let's say these numbers represent prices of airline tickets that a user looks up. To find the most expensive price, we need to be able to pick out the greatest number in the array.
We use the max() function to find the largest number in the array.
The general form to find the largest number in an array is:
$largest= max($array_name);
where $array_name is the name of the array and $largest is the variable which contains the largest value of the array.
For the above array we created, the code to find the largest number is:
$largest= max($numbers);
PHP Output
The largest value in the array is 470
Find the largest number in an array can be useful in a number of web applications. It can locate the most expensive prices or the greatest amount of anything from a list or a column in a table.
For a tutorial on finding the smallest number in an array, see
How to Find the Smallest Number in an Array in PHP.
Make Each Element of an Array Unique
Make each element of an array unique in PHP.
This means that if the array has multiple elements composed of the same exact item, we want to get rid of all the mulitiple values of the same thing and just have it listed in the array once.
In PHP, this can be done using the PHP array_unique() function.
This is shown in the code below.
$array= array_unique($array);
This PHP array_unique() function gets rid of all multiple elements of the same thing and then just has it listed in the array once.
This makes each element in the array unique.
So if you take an array and pass it through the PHP array_unique() function, it returns an array with only unique elements.
So let's say that we have the array below.
This is the power of the PHP array_unique() function so that we don't return duplicate results of in an array if this is unwanted.
Create a Multidimensional Array
In this article, we show how to create a multidimensional array in PHP.
A multidimensional array is an array that contains arrays.
So what we're really doing is we're creating an array and putting arrays in that array.
A multidimensional array is really just an array composed of arrays.
To create a multidimensional array in PHP, we following the general format below.
array(
array1(), array2(), array3(),
...
);
So let's actually create an array now composed up people, their name, phone number and email address.
We create a multidimensional array of 3 people with their name, email address, city, and state.
<?php
$people= array(
array(
"name" => "Jennifer Kimbers",
"email" => "abc@gmail.com",
"city" => "Seattle",
"state" => "Washington"),
array(
"name" => "Rodney Hutchers", email" => "def@gmail.com",
"city" => "Los Angeles",
"state" => "California"),
array(
"name" => "Robert Smith",
email" => "ghi@gmail.com",
"city" => "Michigan",
"state" => "Missouri")
);
So the above code creates a multidimensional array in PHP.
There are 3 people in this array. We have the name, email, city, and state of each person.
So to create this multidimensional array, we created key-value pairs. The keys are name, email, city, and state. The values
are whatever the name, email, city and state is of each person.
So if we use the print_r function along with the pre tags to make this more readable, we get the following output below.
Actual PHP Output
Array
(
[0] => Array
(
[name] => Jennifer Kimbers
[email] => abc@gmail.com
[city] => Seattle
[state] => Washington
)
[1] => Array
(
[name] => Rodney Hutchers
[email] => def@gmail.com
[city] => Los Angeles
[state] => California
)
[2] => Array
(
[name] => Robert Smith
[email] => ghi@gmail.com
[city] => Michigan
[state] => Missouri
)
)
1
So you can use our array. This is creating a multidimensional array that has key-value pairs.
You can also create the same array above without key-value pairs.
Creating a Multidimensional Array Without Key-Value Pairs
To create the same array without key-value pairs, we use the following PHP code below.
<?php
$people= array(
array(
"Jennifer Kimbers",
"abc@gmail.com",
"Seattle",
"Washington"),
array(
"Rodney Hutchers",
"def@gmail.com",
"Los Angeles",
"California"),
array(
"Robert Smith",
"ghi@gmail.com",
"Michigan",
"Missouri")
);
?>
If we the print_r function along with the pre tags again, we get the following output shown below.
Actual PHP Output
Array
(
[0] => Array
(
[0] => Jennifer Kimbers
[1] => abc@gmail.com
[2] => Seattle
[3] => Washington
)
[1] => Array
(
[0] => Rodney Hutchers
[1] => def@gmail.com
[2] => Los Angeles
[3] => California
)
[2] => Array
(
[0] => Robert Smith
[1] => ghi@gmail.com
[2] => Michigan
[3] => Missouri
)
)
1
The problem with an array without key-value pairs is that it's much harder to have good organization. Since now you have represent columns with a numerical representation rather than a text representation like name, email, city, state, it's a
bit harder. This is why it's better to create key-value pairs. But a programmer may prefer one way over the other. And both types of multidimensional achieve the same thing. It's just that with key-value pairs, you can call a column by name. Without key-value pairs, you have to refer to columns by numbers.
And this is all that is necessary to create multidimensional arrays in PHP.
So, for example, if we have a list of people objects that contains the city and state of the person, we can sort through this JSON data and only return people who live in the state of Florida, for instance.
Related Resources
How to
Access the Elements of a Multidimensional Array in PHPHow to Loop Through a
Multidimensional Array in PHP
Access the Elements of a Multidimensional Array
In this article, we show how to access any individual element or any elements of a multidimensional array in PHP.
A multidimensional array is an array that contains arrays.
So let's say we have created the following multidimensional array below composed of people: their name, email, city, and state. The second block of PHP shows how to access all of the data in the array.
<?php
//we create this array
$people= array(
array("name" => "Jennifer Kimbers", "email" => "abc@gmail.com", "city" => "Seattle", "state" => "Washington"), array("name" => "Rodney Hutchers", email" => "def@gmail.com", "city" => "Los Angeles", "state" => "California"), array("name" => "Robert Smith",email" => "ghi@gmail.com", "city" => "Michigan", "state" => "Missouri")
);
//Accessing the Elements of the Array
//First person
echo $people[0]["name"] . "<br>"; //Jennifer Kimbers
echo $people[0]["email"] . "<br>"; //abc@gmail.com
echo $people[0]["city"] . "<br>"; //Seattle
echo $people[0]["state"]. "<br> "; //Washington
//Second person
echo $people[1]["name"] . "<br>"; //Rodney Hutchers
echo $people[1]["email"] . "<br>"; //def@gmail.com
echo $people[1]["city"] . "<br>"; //Los Angeles
echo $people[1]["state"]. "<br> "; //California
//Third person
echo $people[2]["name"] . "<br>"; //Robert Smith
echo $people[2]["email"] . "<br>"; //ghi@gmail.com
echo $people[2]["city"] . "<br>"; //Michigan
echo $people[2]["state"]. "<br> "; //Missouri
?>
So we've created a multidimensional array composed of individual people, holding their name, email, city and state.
We then access every individual element in the array. We do this using the array name, $people followed by the row number, followed by the name of the column we want to access (name, email, city, or state).
This is how the individual element of a multidimensional array are accessed.
Running the above PHP code, we get the following output below.
Actual PHP Output
Jennifer Kimbers abc@gmail.com Seattle Washington
Rodney Hutchers def@gmail.com Los Angeles California
Robert Smith ghi@gmail.com Michigan Missouri
So this is how the elements of a multidimensional array can be accessed that has key-value pairs.
We will show now below to access the elements of multidimensional array that does not have key-value pairs.
Accessing the Elements of a Multidimensional Array Without Key-Value Pairs
So now we show how to access the elements of a multidimensinal array that does not have key-value pairs.
The PHP code below creates the array and outputs the elements of the array.
<?php
//we create this array
$people= array(
array("Jennifer Kimbers", "abc@gmail.com","Seattle", "Washington"), array("Rodney Hutchers", "def@gmail.com","Los Angeles", "California"), array("Robert Smith","ghi@gmail.com","Michigan", "Missouri")
);
//Accessing the Elements of the Array
//First person
echo $people[0][0] . "<br>"; //Jennifer Kimbers
echo $people[0][1] . "<br>"; //abc@gmail.com
echo $people[0][2] . "<br>"; //Seattle
echo $people[0][3]. "<br> "; //Washington
//Second person
echo $people[1][0] . "<br>"; //Rodney Hutchers
echo $people[1][1] . "<br>"; //def@gmail.com
echo $people[1][2] . "<br>"; //Los Angeles
echo $people[1][3]. "<br> "; //California
//Third person
echo $people[2][0] . "<br>"; //Robert Smith
echo $people[2][1] . "<br>"; //ghi@gmail.com
echo $people[2][2] . "<br>"; //Michigan
echo $people[2][3]. "<br> "; //Missouri
?>
So this is how a multidimensional can be accessed that does not have key-value pairs.
We use the name of the array $people, followed by the row number, followed by the column number.
So $people[0][0] corresponds to the first row of the first column. Since arrays start at 0, 0 begins the array.
This corresponds to the name, Jennifer Kimbers.
You can see the difference of accessing multidimensional arrays with key-value pairs and those without. Usually those with key-value pairs are preferred because the column can be referenced by name instead of by number. But a programmer may have his or her preference.
Running the PHP code above, we get the following output shown below.
Actual PHP Output
Jennifer Kimbers abc@gmail.com Seattle Washington
Rodney Hutchers def@gmail.com Los Angeles California
In this article, we show how to loop completely through a multidimensional array in PHP.
A multidimensional array is an array that contains arrays.
So let's say we have created the following multidimensional array below composed of people: their name, email, city, and state. The second block of PHP shows how to access all of the data in the array.
<?php
//we create this array
$people= array(
array(
"name" => "Jennifer Kimbers",
"email" => "abc@gmail.com",
"city" => "Seattle",
"state" => "Washington"),
array(
"name" => "Rodney Hutchers",
"email" => "def@gmail.com",
"city" => "Los Angeles",
"state" => "California"),
array(
"name" => "Robert Smith",
"email" => "ghi@gmail.com",
"city" => "Michigan",
"state" => "Missouri")
);
$num=0;
foreach ($people as $person)
{
$num++; echo "<br># $num ";
foreach ($person as $key=>$value)
{
echo "$key: $value ";
}
}
?>
So this is how we can loop through a multidimensional array in PHP.
The first foreach() loop obtains each array within the array.
The entire array is called $people. The $person variable represents each array within the $people array.
We then use another foreach() loop. This time we take the individual array within the parent array and we loop through all the key-value pairs of the array.
All the key-value pairs represent the name, email, city, and state values of each person.
We echo out these key-value pairs.
We create a variable called $num and initially it is set equal to 0. However, in the first foreach() loop, it is incremented by 1. This is so we can numerically each track of each new record. We echo out this number for each array that the foreach loop encounters in the multidimensional array.
Because multidimensional arrays are basically arrays nested inside other arrays, all we have to do to loop through them is use nested loops.
Running the above PHP code, we get the following output below.
Actual PHP Output # 1 name: Jennifer Kimbers email: abc@gmail.com city: Seattle state: Washington
# 2 name: Rodney Hutchers email: def@gmail.com city: Los Angeles state: California
In this article, we show how to sort a multidimensional array in PHP.
We sort the multidimensional array using the array_multisort() function.
The array_multisort() function sorts the first column element of an array in order.
For example, if we have a multidimensional array of books and the first column is the titles of the books, it will sort the multidimensional array in order of the titles
alphabetically.
The ar
Below we create a multidimensional array of books, that have title, publication year, and author columns.
We then use the array_multisort() function to sort the elements of the array in order.
Since the first column of the arrays is the title column, this code sorts the titles of the books in alphabetical order.
This is all shown below.
<?php
$books= array(
array(
"title" => "Moving to Worlds Beyond",
"publicationyear" => 2008,
"author" => "Ryan Marks"),
array(
"title" => "Best of Both Seas",
"publicationyear" => 2012,
"author" => "Bill Seagell"),
array(
"title" => "Going Under Siege",
"publicationyear" => 2009,
"author" => "Gregory Mandoe")
);
array_multisort($books);
echo "";
echo print_r($books);
echo "</pre>";
?>
So running the code above gives use the following output below.
Actual PHP Output
Array
(
[0] => Array
(
[title] => Best of Both Seas
[publicationyear] => 2012
[author] => Seagell, Bill
)
[1] => Array
(
[title] => Going Under Siege
[publicationyear] => 2009
[author] => Mandoe, Gregory
)
[2] => Array
(
[title] => Moving to Worlds Beyond
[publicationyear] => 2008
[author] => Marks, Ryan
)
)
1
So you can see above how the titles of the books are shown in alphabetical order.
The array_multisort() functions works very well for this purpose.
But what if you want to sort the books by the publication year or by the author's name.
This can be done but unfortunately not without a bit of work. In order for this to happen with the array_multisort() function, you would have to change the order of the columns. The array_multisort() function only sorts the first column of an array. So however you want to sort an array (by which column), you would have to put that column first.
So if you wanted to sort the books by publication year, for instance, you would have to put that column first in the multidimensional array.
So if I put the publication year column first in each of the arrays within the multidimensional array and ran the code, I get the following output shown below.
Actual PHP Output
Array
(
[0] => Array
(
[publicationyear] => 2008
[title] => Moving to Worlds Beyond
[author] => Marks, Ryan
)
[1] => Array
(
[publicationyear] => 2009
[title] => Going Under Siege
[author] => Mandoe, Gregory
)
[2] => Array
(
[publicationyear] => 2012
[title] => Best of Both Seas
[author] => Seagell, Bill
)
)
1
So now with the publication year data first in the array, the array can now be sorted according to the publication year of the books.
There are other ways of sorting multidimensional arrays in PHP. This, though, is probably the simplest way.
If you only need to sort the multidimensional array according to one set of information (for example, the title of the books), it works very well and is extremely simple code. However, if you are running a very dynamic application, where you need to sort multidimensional ways in multiple ways, then this way probably isn't the
best. This is because you would have to structure the multidimensional array differently each time. You could create multiple multidimensional arrays each structured differently but it's not the most efficient. In that case, you would need to create custom code that sort multidimensional arrays instead of using the built-in array_multisort() function.
But for simplistic purposes, the array_multisort() function works very well to sort multidimensional arrays.
Related Resources
How to Create a Multidimensional Array in PHPHow to
Access the Elements of a Multidimensional Array in PHPHow to Loop Through a
Multidimensional Array in PHP
Difference Between the POST and GET Method
There are two methods which you can use to retrieve information from a web form, the POST and GET
methods.
In this article, we discuss the difference between the POST and GET method, so you can know which one to utilize during information retrieval of form data.
Difference Between POST and GET MethodPOST Method
The POST method retrieves information and can add it directly to a web form. Let's say you have
the following web form below which asks for a user's first name, last name, email address, and telephone number.
<fieldset>
<form action="customerinfo.php" method="POST">
<table>
<tr><td><label>First Name:</label></td><td><input type="text"name="FirstName"/></td></tr>
<tr><td><label>Last Name:</label></td><td><input type="text"name="LastName"/></td></tr>
<tr><td><label>Email Address:</label></td><td><input type="text"name="EmailAddress"/></td></tr>
<tr><td><label>Telephone Number:</label></td><td><input type="text"name="TelephoneNumber"/></td></tr>
</table>
<input name="form" type="submit" value="Submit"/>
</form>
</fieldset>
The POST method can take all these filled-in fields of the form and write them to a web page, such as the confirmation page that this form creates when the submit button is pressed.
The POST method is the most used method when retrieving information from an HTML form using PHP.
GET Method
The GET method retrieves the information from a form and appends it to the URL of the website in use. Unlike the POST method, it cannot output information directly to a web page, but adds the user-added information from the form fields to the URL.
Below is the same exact form above but with the method of the form action attribute changed to "GET".
<fieldset>
<form action="customerinfo2.php" method="GET">
<table>
<tr><td><label>First Name:</label></td><td><input type="text"name="FirstName"/></td></tr>
<tr><td><label>Last Name:</label></td><td><input type="text"name="LastName"/></td></tr>
<tr><td><label>Email Address:</label></td><td><input type="text"name="EmailAddress"/></td></tr>
<tr><td><label>Telephone Number:</label></td><td><input type="text"name="TelephoneNumber"/></td></tr>
</table>
<input name="form" type="submit" value="Submit"/>
</form>
</fieldset>
Once you fill in the form fields and press the submit button, just like before, it takes you to a confirmation page but does not print the data to the web page, like the POST Method.
However if you look at the URL, you can see the information appended to the URL.
So, for example, if you typed in "Peter" as the first name, "Williams" as the last name, "PeterWilliams@yahoo.com"
as the email address, and "800-489-7849" as the telephone number, you will see as output the URL:
http://learningaboutelectronics.com/Articles/Difference-between-the-post-and-get-method-in-PHP?
FirstName=Peter&LastName=Williams&EmailAddress=PeterWilliams@yahoo.com&TelephoneNumber=800-489-7849
&form=Submit+Query
This URL broken down so that you can see better is:
http://learningaboutelectronics.com/Articles/Difference-between-the-post-and-get-method-in-PHP
?FirstName=Peter&LastName=Williams&EmailAddress=PeterWilliams@yahoo.com&TelephoneNumber=800-489-7849&form=Submit+Query
This is how the GET method works.
Because of its functions, it is used much less than the POST method. Also, because it appends
all of the user's information to the URL, it is much less secure and safe to use than the POST method.
Retrieve Data from a Text box
In this article, we will show how you can retrieve data from a text box with PHP.
Text boxes are used all over the web in various types of forms. They are used so that a visitor to a site can enter information into it for all various types of reasons, including signing up for a newsletter, joining to become a member of site, filling out credit card numbers to make a purchase, and so on.
As an example, let's say we're making an HTML form, such as the one shown below, which asks for a person's name: <form action="#nameentered" method="post">
<label>Please enter your Name:</label><input type="text"name="name_of_person" value=''/>
<input name="form" type="submit" value="Submit"/>
</p>
</form>
<fieldset>The name you entered is </fieldset>
We know that users can enter information via text boxes.
But how do we extract the data from the forms
so that we can do whatever we want with it? How do we now take the information that this person entered and do something useful with it, such as create a confirmation page or put it into a database for storage so that we can keep a list of all the people entering into this form? Or any task?
And the answer is, we can do this using PHP.
Using PHP, we can extract the information that is input into a text box and either post it on a web page, such as create a confirmation page with the data that the user has
entered or store it into a database. In this article, we focus on extracting the information and displaying it on a web page.
CodingHTML Code
The HTML code to create the text box you see above, asking for a user's name is:
<form action="" method="post">
<label>Please enter your Name:</label><input type="text" name="Name" value='<?php echo $name; ?>'/>
<input name="form" type="submit" value="Submit"/>
</form>
In this HTML code, we create a form in which we create a text box within the form asking for the visitor's name. To create a form on a web page, we must enclose whatever it is in the form with <form></form>
tags. Within the form tags are attributes. The first attribute, the action attribute, is set equal to an empty string ("") or null. This is because this current page will process the PHP code. If we were sending the PHP code to another page, that PHP page would be specified within the action attribute. The other attribute is the method attribute. This means that the information will be posted to the page instead of appended to the current URL.
For a more in-depth understanding of the method attribute, see
Difference between the POST and GET Method in PHP.
The code which creates the text box is <input type="text" name="name_of_person"/>. This creates a text box
and assigns it to the name attribute of name_of_person.
We then create a submit button.
PHP Code
The PHP code to extract the information which the user enters and display it is:
<?php
$name= $_POST['name_of_person'];
?>
How we retrieve the information using PHP is shown above. To retrieve the information from the text box, we use its name attribute. The name attribute of the text box, in this case, is
name_of_person. Therefore, to extract the information from this name_of_person text box, we use the line $name= $_POST['name_of_person'];. The $_POST is a superglobal array which extracts information from HTML form fields. In this case, it extracts the data from the text box with a name attribute of
name_of_person and assigns and stores it to the $name variable.
<?php
echo "<fieldset>";
echo "The name you entered is $name";
echo "</fieldset>";
?>
Once we've retrieved the data which the user has entered using the superglobal $_POST array, we now use the echo statements to output the data which the user entered wherever you want it on the web page.
Therefore, since we are placing the PHP output below the text box, it goes below the text box after a few <br> tags.
And this is how information can be retrieved from a text box using PHP.
Note: In order for PHP to retrieve information from a text box, the PHP code to retrieve the data must come before the text box. It cannot come after. So in this case, since
we have a text box, the PHP code to retrieve the data from the text box must come before the actual HTML text box.
Related Resources
How to Retrieve Data from a Radio Button with PHP
In this tutorial, we will show you how to retrieve data from a radio button with PHP.
By retrieving data from a radio button, we can know which selection a user selects out of a group of choices.
This can be anything from a quiz to any type of questionnaire where a user has to select one choice out of many.
Below is an example of a questionnaire which uses radio buttons as selection options.
Which Credit Card would you like to use?<form action="#selection" method="post">
<input type="radio" name="credit_card" value="MasterCard" checked="checked">MasterCard
<input type="radio" name="credit_card" value="Visa">Visa
<input type="radio" name="credit_card" value="American Express">American Express
<input type="submit" name="button" value="Submit"/></form>
<fieldset>The credit card you want to use is </fieldset>
Now that we have this above questionnaire that we want a user to answer, we need
a way to extract the data from this form and process it, so that we can know which radio button
(credit card) the user selects.
And we can do this using PHP.
CodingHTML Code
First, the HTML Code to Create the Radio Button Form Above:
<form action="" method="post">
<input type="radio" name="credit_card" value="MasterCard" checked="checked">MasterCard<br>
<input type="radio" name="credit_card" value="Visa">Visa<br>
<input type="radio" name="credit_card" value="American Express">American Express<br>
<input type="submit" name="button" value="Submit"/></form>
When creating a radio button form in HTML, the input tag is used and contains
the type, name, and value attributes.
-The type attribute is set to "Radio" for Radio buttons
-The name attribute is set to the collective or group name of all the radio buttons. All the radio buttons in a certain group will all have the same name attribute, which in the example above is "credit_card".
-The value attribute is set to the name of each indivdual element of the radio buttons. In this case, since we are listing credit cards, the values of the attributes are "MasterCard", "Visa", and
"American Express". When displaying the data from a selected radio button, it is the value
attribute which is shown.
-If you want to select a radio button by default, usually the first one, you add
checked="checked" to the first radio button.
The text you place after the input tag is the text that is shown in the radio button options.
In order for PHP to extract the data from the HTML form, the following line of code
are used.
PHP Code
<?php
$name_of_radio_button= $_POST ['name_of_radio_button'];
?>
Although the name of the PHP variable doesn't have to be the name of the radio button, it is good coding technique to follow this convention. Here, the PHP variable is attracts
the data from the radio button form of the selected button. By default, it selects the defaulted
select box which is the radio button that has the line checked="checked". However, if the user
selects another radio button, this is now the selected button and this will be extracted using the "post" method.
For the form above, the PHP code used was:
<?php
$credit_card= $_POST ['credit_card'];
echo 'The credit card you want to use is' . $credit_card;
?>
If no button is selected by default, meaning you didn't check any radio button with checked="checked", the following line of code is used:
<?php
if(isset($_POST['name_of_radio_button'])){
$name_of_radio_button= $_POST ['name_of_radio_button'];
} else {
$name_of_radio_button= "No Button Selected";
}
?>
Note: Note that even if the line checked="checked" is added to a radio button, it will be checked by default but it still will not be a selected choice until the user clicks the 'Submit' button of the form. This is why when you first load the page, no credit card is chosen. Only until the submit button is clicked with a radio button selected is one selected.
Related Resources
How to Retrieve Data from a Text Box with PHP
In this tutorial, we will show how you can retrieve data from a checkbox using PHP.
Checkboxes are used in questionnaires where a user can select more than one option from a list of choices.
Unlike radio buttons which only allows a user to select a single option, check boxes usually allow multiple options to be selected.
As an example, see the below questionnaire which uses checkboxes as selection options.
Which activities would you like to do?
<form action="#selection" method="post">
<input type="checkbox" name="Snorkeling">Snorkeling
<input type="checkbox" name="Scuba_diving">Scuba Diving
<input type="checkbox" name="Parasailing">Parasailing
<input type="submit" name="button" value="Submit"/></form>
Now that we have this above questionnaire that we want a user to answer, we need
a way to extract the data from this form and process it, so that we can know which checkbox(es) the user selects, which translates into which activities the person wants to do.
And we can do this using PHP.
Select the checkboxes above and click submit. You will see the update below.
<fieldset>
The activities you want to do are<br>No activities chosen yet
</fieldset>
CodingHTML Code
First, the HTML Code to Create the Checkbox Form Above:
<form action="" method="post">
<input type="checkbox" name="Snorkeling">Snorkeling<br>
<input type="checkbox" name="Scuba_diving">Scuba Diving<br>
<input type="checkbox" name="Parasailing">Parasailing<br>
<input type="submit" name="button" value="Submit"/></form>
When creating a checkbox form in HTML, the input tag is used and contains
the type and name attributes.
-The type attribute is set to "Checkbox" for Checkboxes.
-The name attribute is the name of each individual checkbox. This attribute is important because this is the attribute you will use to identify each checkbox and display it if it is checked.
-If you want to select a checkbox by default, you can use the line checked="checked" for the given checkbox. However, in this case, no checkboxes are selected by default.
The text you place after the input tag is the text that is shown in the checkbox options.
In order for PHP to extract the data from the HTML form, the following line of coding is used:
PHP Code
<?php
$name_of_checkbox1= $_POST['name_of_checkbox1'];
$name_of_checkbox2= $_POST['name_of_checkbox2'];
$name_of_checkbox3= $_POST['name_of_checkbox3'];
echo'The activities you want to do are' . ' ';
if(isset($name_of_checkbox1)){
echo 'name_of_checkbox1'. ' ';
}
if(isset($name_of_checkbox2)){
echo 'name_of_checkbox2'. ' ';
}
if(isset($name_of_checkbox3)){
echo 'name_of_checkbox3'. ' ';
}
if((empty($name_of_checkbox1)) && (empty($name_of_checkbox2))
&& (empty($name_of_checkbox3))){
echo 'No checkbox selected';
}
?>
Although the name of the PHP variable doesn't have to be the name of the radio button, it is good coding technique to follow this convention. Here, the PHP variable is extracts
the data from the checkbox form of the selected checkboxes.
For the form above, the PHP code used was:
<?php
$Snorkeling= $_POST['Snorkeling'];
$Scuba_diving= $_POST['Scuba_diving'];
$Parasailing= $_POST['Parasailing'];
echo 'The activities you want to do are' . ' ';
if (isset($Snorkeling)){
echo 'Snorkeling' . ' ';
}
if (isset($Scuba_diving)){
echo 'Scuba diving'. ' ';
}
if (isset($Parasailing)){
echo 'Parasailing' . ' ';
}
if ((empty($Snorkeling)) && (empty($Scuba_diving))
&& (empty($Parasailing))){
echo 'No activities chosen yet';
}
?>
Related Resources
How to Retrieve Data from a Text Box with PHP
In this tutorial, we will show you how to retrieve data from an array of checkboxes with PHP, to determine which check boxes are clicked and which aren't.
Check boxes are used as selection options for users in questionnaires to determine to a user's response.
Below is an array of checkboxes in HTML which is very common in forms on the web, such as when a user needs to select either none, one, or multiple options from a list of choices:
<form action="#selection" method="post">
<label>What Destination Would you Like to Go To?</label>
<input type="checkbox" name="Islands[]" value="Aruba- Aruba is a beautiful desert island">Aruba
<input type="checkbox" name="Islands[]" value="Hawaii- Hawaii is a beautiful strand of islands located in the heart of the Pacific Ocean.">Hawaii
<input type="checkbox" name="Islands[]" value="Jamaica- Jamaica is a beautiful island located in the Caribbean Sea">Jamaica
<input type="submit" name="button" value="Submit"/></form>
<fieldset>You haven't selected any destination</fieldset>
Coding
To create the array of checkboxes shown above, the HTML code is:
<form action="" method="post">
<label>What Destination Would you Like to Go To?</label>
<input type="checkbox" name="Islands[]" value="Aruba- Aruba is a beatiful desert island">Aruba
<input type="checkbox" name="Islands[]" value="Hawaii- Hawaii is a beautiful strand of islands located in the heart of the Pacific Ocean.">Hawaii
<input type="checkbox" name="Islands[]" value="Jamaica- Jamaica is a beautiful island located in the Caribbean Sea">Jamaica
<input type="submit" name="button" value="Submit"/></form>
</form>
Every form element in HTML must be enclosed by the form tag. So in this case, since we are creating an array of checkboxes, this must be closed in a pair of opening and closing form tags.
After this, we now create the actual array of checkboxes.
This is done with a pair of opening and closing option tags for each checkbox. This tag contains the type,
name, and value attributes.
-The type attribute must be set to "checkbox".
-The name attribute is the name of the whole array of checkboxes. It must have a name followed by square brackets [ ], which means that is an array.
Since the choices in this example involve tropical island destinations, the array is called "Islands[]".
-The Value attribute is unique for each of the array elements. In this case, it is set to the names of the islands.
A submit button, as in all forms, was added below this. And then after, the closing form tag was inserted to close the form.
PHP Code
<?php
$destinations= $_POST['Islands'];
if(isset($destinations)) {
echo 'You have chosen:' . ' ' . ' ';
foreach ($destinations as $key => $value)
{
echo $value . ' ';
}
}
else
{
echo "You haven't selected any destination";
}
?>
In the first block of code, we use the $_POST superglobal array to retrieve all data from each of the checkboxes. This is just to retrieve all the data, without knowing which data the user has selected yet.
In the second block of code, we use an if statement with the isset function to determine
if the user has selected any options out of the checkboxes. This checks all of the checkboxes to see if any selections have been made. If no options are selected, the array of checkboxes is not set, and, therefore, the user sees the statement, "You haven't selected any destination."
Then we use the foreach loop to go through each and every individual option. This loop will check every check box to see whether it is selected or not. If the check box option is selected, the value attribute of that option is printed using the echo command. If it is not selected, the value is not output.
Related Resources
How to Retrieve Data from a Text Box with PHP
In this tutorial, we will show how to retrieve data a drop-down list form with PHP, to deterine which selection a user has chosen.
Drop-down lists are used with all types of forms in which a user has to select one option.
As an example, below is a questionnaire which uses a drop-down list as a selection method for a number of options. A user can only select one option.
How would you like to pay?
<form action="#selection" method="post">
<select name="Pay_options">
<option value="No Payment Options Selected">[Choose Option Below]</option>
<option value="Credit Card">Credit Card</option>
<option value="Debit">Debit</option>
<option value="Check">Check</option>
</select>
<input type="submit" name="button" value="Submit"/></form>
Now that we have this above questionnaire that we want a user to answer, we need
a way to extract the data from this form and process it, so that we can know which option the user selected, which translates into which method he will pay by.
And we can do this using PHP.
Select a choice from the drop-down list above and click submit.
You will see the update below.
<fieldset>
<b>The pay method that you have chose to use is:</b>
</b><br></fieldset>
CodingHTML Code
First, the HTML Code to Create the drop-down list above:
<form action="" method="post">
How would you like to pay?<br>
<select name="Pay_options">
<option value="No Payment Options Selected">[Choose Option Below]</option>
<option value="Credit Card">Credit Card</option>
<option value="Debit">Debit</option>
<option value="Check">Check</option>
</select><br>
<input type="submit" name="button" value="Submit"/></form>
When creating a drop-down list in HTML, the select tag is used to enclose all of the options in the drop-down list.
The select tag has an opening and closing tag.
-The option tag is for each of the individual choices in a drop-down list that a user can select. The option tag contains the "value" attribute.
The Value attribute is unique to all of the options. This is the text that is used to differentiate one option from all the rest.
-If you want to select an option from the drop-down list by default, you can use the line checked="checked" for the given drop-down option.
If you don't select any by default, the first option on the list will be selected by default.
The text you place after the option tag is the text that is shown in the drop-down list options.
In order for PHP to extract the data from the HTML form, the following line of coding is used:
PHP Code
<?php
$Select_name=$_POST['Select_name'];
echo $Select_name;
?>
Although the name of the PHP variable doesn't have to be the name of the drop-down list, it is good coding technique to follow this convention. Here, the PHP variable is extracts
the data from the drop-down list of the selected option.
For the form above, the PHP code used was:
<?php
$Pay_options=$_POST['Pay_options'];
echo 'The pay method that you have chose to use is:' .' ' . $Pay_options;
?>
Related Resources
How to Retrieve Data from a Text Box with PHP
In this tutorial, we will show how to retrieve data from a list box with PHP.
There are 2 distinct type of list boxes in which we retrieve data from. The first is a list box that only allows one option to be selected. The second is a list box in which multiple options can be selected.
List boxes are common in web forms in which a webmaster wants to elicit information from a user. A user can either selection one option from a list box or multiple options, depending on the type of list box.
We will deal first with a list box in which only option can be selected.
Below is an example:
<form action="#selection1" method="post">
<label>Which Credit Card Would You Like to Use?</label>
<select name="credit_card" size="3">
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="American Express">American Express</option>
</select>
<input type="submit" name="submit1" value="Submit"/>
</form>
<fieldset>
You have not selected any credit card.
</fieldset>
You can see that the choice that you select gets updated.
HTML Code
<form action="" method="post">
<label>Which Credit Card Would You Like to Use?</label><br>
<select name="credit_card" size="3">
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="American Express">American Express</option>
</select><br>
<input type="submit" name="submit" value="Submit"/>
</form>
PHP Code
The PHP to retrieve data from a list box is:
<?php
$choice= $_POST['credit_card'];
if (isset($choice)) {
echo 'The Credit Card you have selected is '. $choice;
}
else {
echo "You have not selected any credit card.";
}
?>
The $choice variable retrieves the selected option that the user has selected. If the $choice variable is set, meaning has a value, this value will be returned, and we will know which credit card the user selected.
Otherwise, if no options have been selected, the statement is echoed that the user hasn't selected any credit
cards.
List Box Where Multiple Options Can Be Selected
Now below is a list box where multiple options can be selected.
<form action="#selection2" method="post">
<label>What Do You Want In Your Salad?</label>
<select name="foods[]" size="3" multiple="multiple">
<option value="Tomatoes">Tomatoes</option>
<option value="Cucumbers">Cucumbers</option>
<option value="Celery">Celery</option>
</select>
<input type="submit" name="submit2" value="Submit"/>
</form>
You haven't selected any foods to be in your salad.
HTML Code
<form action="" method="post">
<label>What Do You Want In Your Salad?</label><br>
<select name="foods[]" size="3" multiple="multiple">
<option value="Tomatoes">Tomatoes</option>
<option value="Cucumbers">Cucumbers</option>
<option value="Celery">Celery</option>
</select><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</textarea></form>
PHP Code
<?php
$choices= $_POST['foods'];
if(isset($choices)) {
echo 'You have chosen these foods to be in your salad:' . ' ' . ' ';
foreach ($choices as $key => $value)
{
echo $value . ' ';
}
}
else
{
echo "You haven't selected any foods to be in your salad.";
}
?>
In the first block of code, we use the $_POST superglobal array to retrieve all data from each of the options, which in this case is 3, tomatoes, cucumbers, and celery. This block of code is just to retrieve all the data, without knowing yet which data the user has selected.
In the second block of code, we use an if statement with the isset function to determine
if the user has selected any options out of the list box. This checks all of the options of the list box
to see if each is selected or not. Then we use the foreach command to go through each and every individual option. If the list box option is selected, the value attribute of that option is printed using the echo command. If no options are
selected, the user sees a statement, "You haven't selected any foods to be in your salad."
Related Resources
How to Retrieve Data from a Text Box with PHP
In this tutorial, we will go over how to retrieve data from a textarea
using PHP. '
Textareas, also called multi-line text input, are used pretty extensively in forms to extract information from a user. Unlike text boxes, textareas span multiple lines, so that a user can enter into lines of information, rather than just one single line. Therefore, textareas can accomodate more words or sentences.
As an example, below is a textarea in HTML which is very common in forms on the web, such as when a user needs to enter in multiple lines of text:
<form action="#comment" method="post">
<label><b>Additional Comments:</b></label>
<input type="submit" name="button" value="Submit"/></form>
<fieldset>The comment that you entered is:<br><br><br><br></fieldset>
PHP allows us to extract the data from this input text area to do whatever we want to accomplish with the data.
CodingHTML Code
This is the HTML code to create the Additional Comments multi-line text input.
<form action="" method="post">
<label>Additional Comments:</label><br>
<php echo $comments; ?>
</textarea><br>
<input type="submit" name="button" value="Submit"/></form>
PHP Code
This is the PHP code to retrieve the data entered into the textarea.
<?php
$comments= $_POST['comments'];
?>
The code to then output the line beneath the textarea which a user has entered is:
<?php
echo "The comment that you entered is:" . "<br> " . $comments;
?>
The reason these 2 pieces of PHP code have to broken up is because PHP retrieval of an HTML form element must be done before the HTML form element. Therefore, the code to retrieve the data from the textarea, which is $comments= $_POST['comments']; must come before the HTML text area. With the retrieval done before, we can now output the retrieved data after the HTML element.
The superglobal aray $_POST retrieves all which is written in the multi-line text
input form and stores it in the
$comments variable. The echo statement then prints out the comment which is written in this field.
Related Resources
How to Retrieve Data from a Text Box with PHP
In this article, we will go over how to perform number, or numeric, validation of a form field filled in by a user, to make sure that the data entered is, in fact, a numeric value.
This may be necessary for a slew of forms filled out on the web. Examples of these are credit card numbers, zip codes, house numbers, telephone numbers, cash amounts, etc. These are all form fields where we want only numbers entered in to the form field. If any characters in the sequence are non-numeric, then we want to tell the user that the sequence of characters which they entered in are not valid. This is what is referred to as number validation.
Below is an example of a form field which checks for number validation. Only numbers can be entered in to the form field, only numeric values. If non-numeric values are entered, then the form field catches this and tells the user that s/he has made an error.
<form action="#result" method="post">
<label>Enter Number(s) Only:</label><input type="text"name="number_entered" id="ProductName" value=''/>
<input name="form" type="submit" value="Submit"/><br><br></form>
</p>
<fieldset>
<b>Result</b>
</fieldset>
Above is a form which checks for number validation. In this form, it is wanted that users
enter numbers only into the form field. If a user enters a nonnumeric character, an error is thrown and the user is told to enter numbers only into the field.
PHP
So how do we perform number validation in PHP on a form field to make sure only numbers have been entered?
The answer is, we use a function in PHP called the is_numeric function.
The is_numeric function is used to check whether the character(s) which are entered. If all the characters are numeric, it returns a true value. If all the characters are not numeric, it returns a false, or not true, value.
Knowing now how this function works, we can implement it based on an if-else statement. If true, we can make it execute one statement. If false, we can make it execute another statement, such as the form above does.
HTML Code
<form action="" method="POST">
<label>Enter Number(s) Only:</label><input type="text" name="number_entered" id="number"/>
<input name="form" type="submit" value="Submit"/>
</form><br>
This HTML code creates the text field in which a user enters characters.
The important thing we need to know from this HTML Code is the "name" attribute of the text field, which in this case is number. We will need to know this for the PHP code, because the "name" attribute is what we use in PHP of the HTML form field to test the characters that the user enters into this field.
PHP Code
<?php
$number= $_POST['number_entered'];
$form_result= $_POST['form'];
if (isset($form_result)){
if (is_numeric($number)) {
echo 'The number you entered is ' . $number. '. This is a valid number.';
}
else {
echo 'Error: You did not enter numbers only. Please enter only numbers.';
}
}
The is_numeric() function checks to see if the characters entered into a field are numbers or not. If all the characters are numbers, it returns true. If all the characters are not numeric, it returns false.
Here we simply do an if-else statement. If all the characters are numbers, it tells the user which number was entered and that it is valid. If all the characters are not numbers, it tells the user he has made an error and that all characters must be numbers.
The variable $form_result is there for determining if the submit button has been clicked. If it has, it performs the next step.
String Length Validation In a Web Form
In this article, we will show how you can perform string length validation in a web form with PHP.
First, what is string length validation and why is it important?
String length validation is measuring the length of a string entered into a text box and making sure that it
doesn't go under the minimum length or that it doesn't exceed the maximum length. It is important because
let's say, for example, you have
members sign up on your website, you may want to limit the length of the username and password a user can have.
Having a member sign up with a username or password of 1 or 2 or 3 characters is too short, and could present a security issue. More than likely, we want the username and password to be at least 6 characters in length but not more than, say, 20 characters, because we don't want them to be too long.
Look at the example below.
The username and password must be between 6 and 15 characters. Below this, it will tell the user
that the username or password is too short. Above this limit, it will tell you that the username or password is too
long.
<form action="#answer" method="POST">
Please create a username: <input type="text" name="username" value=''/>
Please create a password: <input type="password" name="password" value=''/>
<input type="submit" name="enterbutton" value="Enter"/>
</form>
So how do we create this form above and provide output back if the username is too short or too long?
CodingHTML Code
The HTML code to create the form above, the 2 text boxes and the 'Enter' button, is:
<form action="#answer" method="POST">
Please create a username:
<input type="text" name="username" value='<?php echo $username; ?>'/><?php echo $output; ?><br>
Please create a password:
<input type="password" name="password" value='<?php echo $password; ?>'/><?php echo $output2; ?><br>
<input type="submit" name="enterbutton" value="Enter"/><br>
</form>
This HTML code creates the username and password text boxes, as well as the 'Enter' button.
PHP Code
The PHP code to retrieve the user-entered information, measures the length of the strings, and then outputs the appropriate feedback to the user, so that he can know if he's making any mistakes:
<?php
$username= $_POST['username'];
$password= $_POST['password'];
$enterbutton= $_POST['enterbutton'];
$usernamelength= strlen($username);
$passwordlength= strlen($password);
if (isset($enterbutton)){
if ($usernamelength < 6){
$output= " Invalid username. Username must be at least 6 characters";
}
if ($usernamelength > 15){
$output= " Invalid username. Username cannot be greater than 15 characters";
}
if ($passwordlength < 6){
$output2= " Invalid password. Password must be at least 6 characters";
}
if ($passwordlength > 15){
$output2= " Invalid password. Password cannot be greater than 15 characters";
}
}
?>
The $username and $password variables retrieve and store the values of the information the user has entered into the username textbox and the password textbox.
The $enterbutton retrieves the information from the 'Enter' button. Through this variable, we can determine if the 'Enter' button has been clicked or not.
The $usernamelength variable stores the value of the length of the string of the username and the $passwordlength variable stores the length of the password.
In the first if statement, if (isset($enterbutton)){, we do the following functions only if the 'Enter' button has been clicked. The remaining if statements check to determine if
the length of the username and password are below 6 or above 15 characters. If they are, the appropriate message is output to the user. If the username and password are between 6 and 15 characters, then no message is output to the user, because the user correctly chose a username and password.
This is how most web forms handle validation. They output red text usually to a user, only if a form field has been incorrectly filled out. If not, there are no messages.
Notice that the output statements have <redtext></redtext> around them. In the CSS code, this tag makes the text red, standing out more to alert the user that the form has
been incorrectly filled out.
Check if the Submit Button Is Clicked
In this article, we will go over how you can check to see whether the submit button of a form has been clicked or not using PHP.
This is very useful and can be used often with form data in PHP, because when the web browser first loads a web form, PHP does not know whether the form, initially, has been clicked or not. It doesn't know whether the user has entered data
and submitted or not. This means that if you have a form field and it does an if-else statement, it may run one of the statements initially, which you probably don't want. PHP cannot distinguished
if a form has already been executed or it hasn't, when initially loaded. So checking to see if the submit button has been clicked is important and useful in forms involving PHP.
Below is an typical form field that you would find on the web:
<form action="#answer" method="post">
<label>Enter Your Name Please:</label><input type="text"name="name_entered" id="name" value=''/>
<input name="submitbutton" type="submit" value="Submit"/><br><br></form>
</p>
<fieldset>
<b>Result</b>
</fieldset>
Above is a form which asks a user to enter his or her name into the form field. If the user enters in characters into this field and clicks submit, then the form will tell the user the name which s/he entered. If the user leaves the field blank and clicks 'Submit', then the form will tell the user that s/he did not enter a name and that s/he must do so.
HTML Code
The HTML code of this form field is:
<form action="" method="POST">
<label>Enter Your Name Please:</label>
<input type="text"name=" name_entered" value='<?php echo $name; ?>'/>
<input type="submit" name="submitbutton" value="Submit"/>
</form>
The most important part of this form field in HTML is the "name" of the submit button, which in this case is called "submitbutton". This will be important because
our PHP code needs to extract information from this submit button, which is how it determines whether it has been clicked or not. PHP code knows which submit button to refer to by the "name" attribute of the submit button.
PHP code
The PHP code used to determine whether the submit button has been clicked is:
<?php
$name= $_POST['name_entered'];
$submitbutton= $_POST['submitbutton'];
if ($submitbutton){
if (!empty($name)) {
echo 'The name you entered is ' . $name;
}
else {
echo 'You did not enter a name. Please enter a name into this form field.';
}
}
?>
With the PHP Code, first we have to extract the data from the submit button before we can process it to check whether it is clicked or not. We do this by the line:
$submitbutton= $_POST['submitbutton'];
Here, we created a PHP variable, $submitbutton. Using the superglobal $_POST array, we extract the value of the submit button with the form name 'submitbutton', and assign it to the PHP variable, $submitbutton.
Now that we have the value extracted, we can do an if statement to see whether it is clicked or not. We do this by the following line:
if ($submitbutton){
//This statement to be executed
}
else
{
//This statement to be executed
}
How we check to see if the submit button is clicked is with a simple if statement. If the $submitbutton is clicked, the function will return true.
If the $submitbutton is not clicked, the function will return false. This simple if statement checks the boolean value of the variable.
Based on this, you can make any function or statement be executed.
In our example, if the submit button has been clicked, the form tells the user the name s/he has entered. If it hasn't, then the form tells the user to enter a name.
If we didn't do validation to check whether the submit button was clicked, then initially when the form is first loaded, since the field is empty (not set), the form would automatically tell the user that s/he must enter a name. This is because PHP doesn't know at initial loading whether the user has interacted with the form already or not. The validation to check whether the submit button has been clicked demonstrates this.
Related Resources
How to Upload Images to a Website Using PHPHow to Upload Files to a Website Using PHPHow to Create a Search Engine Using PHPHow to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHPHow to Create a Confirmation Page for an HTML Web Form Using PHPHow to Insert Images into a MySQL Database Using PHP How to Create a Searchable Database Using MySQL and PHP
<form action="" method="POST">
Email Address <input type= "text" name="email_entered" value=''/>
<input type="submit" name="submitbutton" value="submit"/>
</form>

In this article, we show how to validate an email address using PHP.
This is to make sure that the email that a user enters into an email text box is actually a valid email address.
PHP has a built-in function, filter_var() function, to check for email validation.
PHP Code
The PHP code to validate an email is shown below.
<?php
$email= "example@gmail.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
echo("Valid email address");
} else {
echo("Invalid email address");
}
?>
We create a variable named $email. We set to an example email.
We then create an if statement that if the filter_var() function with the $email as one of its parameters is true (not false), then it is a valid email address. Otherwise, it's an invalid email address.
It's really easy to validate an email address in PHP because it has a built-in function that checks for validation.
Related Resources
How to Retrieve Data From a MySQL Database Using AJAX and PHP
Validate an Email Address Using PHP & AJAX
Email Address

In this article, we show how to validate an email address using PHP & AJAX.
This is to make sure that the email that a user enters into an email text box is actually a valid email address.
Using AJAX in conjunction with PHP, enables us to validate an email without the page having to be refreshed.
With AJAX, we can call the function to validate the email address once the user clicks away from the box.
So AJAX along with PHP is a powerful tool that can be used in forms, such as validation which is what we are doing now.
So, as you can see in the above form, an email can be entered in.
I use the Javascript onblur() function to validate the email address once the user clicks away from the text box. So once the user enters in the email and clicks away from the text box, s/he will be able to know if the email address is a valid email.
HTML Code
The HTML code to validate we use to create the above email text box is shown below.
Email Address <input type= "text" id="email_entered" onblur="validateemail();"/><label id="validate"></label>
So the above code is the HTML needed to create the text box where the user enters in his or her email.
Javascript & AJAX Code
Below is the Javascript and AJAX code needed to make this email validation form.
So in this code, we create a function called validateemail(). We create a variable called request. And we create a request object and store in this variable. This request object
allows the browser to communicate with the server to run PHP code in the background.
We then create a variable named url. This stores the PHP file that has the PHP code that does validation processing of the email address. So this is a separate PHP file that you have to create in order for this script to work.
I then create a variable, email address, that stores the email that the user enters.
The next variable that is created in vars. This is a very important variable because it's the variable sent to the PHP file so that PHP can extract the data that the user has entered into the email text box, which represents the user's email.
We then specify in the request.open() function that the method is POST, the url variable represents the file we want the posted data to go to, and the true makes the request asynchronous.
Once the request is ready, we have a creatd variable return_data and we set this equal to request.responseText. This request.responseText represents the output of the PHP file once it has done its processing. So the return_data variable holds the output from the PHP file that has processed the email address.
We then update the element on our page that has an Id tag of "validate" and change the contents of it through the innerHTML method() and set equal to return_data (the output of the PHP file). If you back at the HTML code, to the right of the email address text box is a label tag having an Id of "validate". This label tag will be updated when the PHP returns the output data.
The line, request.send(vars), actually executes the sending of the data.
This concludes the Javascript and AJAX code.
PHP Code
The PHP code that validates an email address is shown below.
<?php
$email= $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
echo("Valid email address");
} else {
echo("Invalid email address");
}
?>
So we retrieve the email from the vars variable.
PHP has a built-in function that can check whether an email is valid or not. So we don't have to use a more sophisticated method such as forming a regular expression for email.
We can simply take advantage of PHP's built-in filter_var() function.
If filter_var is not equal to false, this means the email is valid. We print out "Valid email address".
Else, we print out "Invalid email address."
And this is all that is required to validate an email with PHP and AJAX.
Related Resources
How to Retrieve Data From a MySQL Database Using AJAX and PHP
Validate a Credit Card Number
<form action="" method="POST">
Credit card number:<input type="text" name="number_entered" value='' />
<input type="submit" value="Submit" name="submitbutton"/>
</form>
In this article, we show how to validate a credit card using PHP.
So, as you can see in the above form, a credit card can be entered in.
When you press the Submit button, you see whether or not it is valid.
If the card is valid, this form can detect what type of card it is.
HTML Code
The HTML code to validate a credit card and find out what type of credit card it is is shown below.
<form action="" method="POST">
Credit card number:<input type="text" name="number_entered" value='<?php if ($submitbutton) { echo "$number";} ?>'/>
<?php if ($submitbutton)
{
if (validatecard($number) !== false)
{
echo "<green> $type detected. credit card number is valid</green>";
}
else
{
echo " <red>This credit card number is invalid</red>";
}
}
?>
<input type="submit" value="Submit" name="submitbutton"/>
</form>
So the above code is the HTML needed to create the form to enter a credit card number. You can see that it also has PHP code inside of it.
So the first thing we do is create a form. Since we want to keep the data posted to this page, we set the action attribute equal to "" and the method attribute equal to POST. Therefore, the form posts data to the current page.
We then create a credit card text box. Since we want the text box to retain the value that a user enters, we set the value attribute equal to the $number. You'll see later that this $number holds the credit card number that the user entered. We put PHP code by the right side of this text box. This PHP code checks a function called validatecard to see whether the card is
valid or not. This will update right next to the credit card box when a user presses Submit.
We then code the Submit button and end the form.
PHP Code
The PHP code that validates a credit card is shown below.
<?php
$submitbutton= $_POST['submitbutton'];
$number= $_POST['number_entered'];
function validatecard($number)
{
global $type;
$cardtype = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($cardtype['visa'],$number))
{
$type= "visa";
return 'visa';
}
else if (preg_match($cardtype['mastercard'],$number))
{
$type= "mastercard";
return 'mastercard';
}
else if (preg_match($cardtype['amex'],$number))
{
$type= "amex";
return 'amex';
}
else if (preg_match($cardtype['discover'],$number))
{
$type= "discover";
return 'discover';
}
else
{
return false;
}
}
validatecard($number);
?>
So we retrieve the submit button data, so that we can know whether it has been clicked or not. We store this in the variable $submitbutton.
We retrieve the credit card number that the user has entered into the text box and store it in the variable $number.
We then create a function called validatecard and have it have a $number parameter.
We then create a global variable named $type.
We then create an array named $cardtype. This array holds a series of major credit companies. We use regular expressions to determine which credit card number belongs to which major credit card company based on the beginning numbers of the credit card.
Visa credit card numbers begin with 4. Visa credit cards can either be composed of 13 digits or 16 numbers. Older visa cards contained 13 digits. Newer visa cards now have
16 digits.
Mastercard credit card numbers begin with 5. Mastercards are composed of 16 digits.
American express cards start with either 34 or 37. Amex cards are composed of 15 digits.
Discover cards begin with 6. Discover cards are composed of either 13 or 16 digits.
If you understand regular expressions, these are what are encoded in the PHP code.
Once we have these regular expressions coded in the various credit card types, we'll be able to know whether or not they are valid based on whether the number the user enters matches the regular expressions.
To see if they match, we use the PHP preg_match function, comparing the element in the array (each various credit card type) to the number that the user enters.
The preg_match() function takes 2 parameters. The first is the element in the array we created. And this array represents each card type we specified. The 2nd parameter is the number that the user enters into the text box. If the number is a match, fitting the regular expression, we return the credit card. In each if statement, we had the variable $type and set it equal to the credit card type it is.
Else, if there are no matches, we return false.
We then simply call the function validatecard so that we actually execute it.
If you go back to the HTML code above right next to the text box, where the user enters his or her credit card number, we have PHP code.
We run an if statement to see if what the function returns is not equal to false. If not equal to false (if it is true), we output the card detected and that the credit card number is valid.
If what the function returns is equal to false, then we output that the credit card number is invalid.
And this is all that is required to validate a credit card using PHP.
Of course, there is so much more advanced analytics involved in this. We have taken into account expiration dates and the security code. That requires much more advanced analytics, in which you basically have to contact the credit card vendor to get confirmation. And this is normally what when the actual payment is submitted. You would then have to check the actual vendor.
But what we are doing here is simply checking the format and seeing whether is card value initially just by the numbers that the user enters. If the credit card number isn't valued, then we're going to waste resources, sending this number to the credit card vendor to be processed when it's erroneous to begin with. It first has to be in correct format. This doesn't mean that the actual credit card is correct, but the format is. It's the right number of digits, beginning with the right numbers. Then after that, we can send the information to a credit card to be processed. But before we do that, we first have to make sure the credit card number to begin with. So this is what we're doing.
Related Resources
How to Validate a Credit Card Number Using PHP and AJAX
Validate a Credit Card Using PHP & AJAX
Credit Card Number
Expiration Date (mm/year)
Security Code

In this article, we show how to validate a credit card using PHP & AJAX.
This credit card validation was shown just using PHP in this article found at the following link:
How to Validate a Credit Card Number Using PHP.
However, using AJAX in conjunction with PHP, is much better and creates a much better user experience with the form.
This is because the page doesn't have to be refreshed when using AJAX. With AJAX, we can call the function to validate the credit card without the user even getting to the submit button.
So AJAX along with PHP is a powerful tool that can be used in forms, such as validation which is what we are doing now.
So, as you can see in the above form, a credit card can be entered in.
I used the Javascript onblur() function to validate the credit card number once the user clicks away from the credit card number text box to go to the expiration date text box, to enter in the expiration date. So when a user clicks the expiration date text box, s/he will know whether the credit card number entered is valid or not.
If the card is valid, this form can detect what type of card it is based on the number entered.
HTML Code
The HTML code to validate a credit card and find out what type of credit card it is is shown below.
<table>
<tr><td>Credit Card Number</td><td><input type= "text" id="number_entered" onblur="validatecreditcard();"/><label id="validate"></label></td></tr>
<tr><td>Expiration Date (MM/Year)</td><td><input type= "text" id="expirationdate_entered"/></td></tr>
<tr><td>Security Code</td><td><input type= "text" id="securitycode_entered"/></td></tr>
<tr><td></td><td><input type="submit" value="Submit"/></td></tr>
</table>
<input type="submit" value="Submit" name="submitbutton"/>
</form>
So the above code is the HTML needed to create the form to enter a credit card number, along with other information such as the expiration date and the security code.
We create a credit card text box, a expiration date text box, a security code text box, and a submit button.
It's in tabular form to be neat and orderly.
Javascript & AJAX Code
Below is the Javascript and AJAX code needed to make this credit card validation form.
So in this code, we create a function called validatecreditcard(). We create a variable called request. And we create a request object and store in this variable. This request object
allows the browser to communicate with the server to run PHP code in the background.
We then create a variable named url. This stores the PHP file that has the PHP code that does validation processing of the credit card number. So this is a separate PHP file that you have to create in order for this script to work.
I then create 3 variables, cardnumber, expirationdate, and security code. These hold the data that the user enters into the credit card number, expiration, and security code text boxes,
The next variable that is created in vars. This is a very important variable because it's the variable sent to the PHP file so that PHP can extract the data that the user has entered into the text boxes, which represents the credit card number, expiration date and security code.
We then specify in the request.open() function that the method is POST, the url variable represents the file we want the posted data to go to, and the true makes the request asynchronous.
Once the request is ready, we have a creatd variable return_data and we set this equal to request.responseText. This request.responseText represents the output of the PHP file once it has done its processing. So the return_data variable holds the output from the PHP file that has processed the credit card number.
We then update the element on our page that has an Id tag of "validate" and change the contents of it through the innerHTML method() and set equal to return_data (the output of the PHP file). If you back at the HTML code, to the right of the credit card number text box is a label tag having an Id of "validate". This label tag will be updated when the PHP returns the output data.
The line, request.send(vars), actually executes the sending of the data.
This concludes the Javascript and AJAX code.
PHP Code
The PHP code that validates a credit card is shown below.
<?php
$number= $_POST['creditcardnumber'];
$expirationdate= $_POST['expiration'];
$securitycode= $_POST['security'];
function validatecard($number)
{
global $type;
$cardtype = array(
"visa" => "/^4[0-9]{12}(?:[0-9]{3})?$/",
"mastercard" => "/^5[1-5][0-9]{14}$/",
"amex" => "/^3[47][0-9]{13}$/",
"discover" => "/^6(?:011|5[0-9]{2})[0-9]{12}$/",
);
if (preg_match($cardtype['visa'],$number))
{
$type= "visa";
return 'visa';
}
else if (preg_match($cardtype['mastercard'],$number))
{
$type= "mastercard";
return 'mastercard';
}
else if (preg_match($cardtype['amex'],$number))
{
$type= "amex";
return 'amex';
}
else if (preg_match($cardtype['discover'],$number))
{
$type= "discover";
return 'discover';
}
else
{
return false;
}
}
validatecard($number);
if (validatecard($number) !== false)
{
echo "<green> $type detected. credit card number is valid";
}
else
{
echo " This credit card number is invalid";
}
?>
So we retrieve the credit card number, expiration date, and security code from the text boxes.
We then create a function called validatecard and have it have a $number parameter.
We then create a global variable named $type.
We then create an array named $cardtype. This array holds a series of major credit companies. We use regular expressions to determine which credit card number belongs to which major credit card company based on the beginning numbers of the credit card.
Visa credit card numbers begin with 4. Visa credit cards can either be composed of 13 digits or 16 numbers. Older visa cards contained 13 digits. Newer visa cards now have
16 digits.
Mastercard credit card numbers begin with 5. Mastercards are composed of 16 digits.
American express cards start with either 34 or 37. Amex cards are composed of 15 digits.
Discover cards begin with 6. Discover cards are composed of either 13 or 16 digits.
If you understand regular expressions, these are what are encoded in the PHP code.
Once we have these regular expressions coded in the various credit card types, we'll be able to know whether or not they are valid based on whether the number the user enters matches the regular expressions.
To see if they match, we use the PHP preg_match function, comparing the element in the array (each various credit card type) to the number that the user enters.
The preg_match() function takes 2 parameters. The first is the element in the array we created. And this array represents each card type we specified. The 2nd parameter is the number that the user enters into the text box. If the number is a match, fitting the regular expression, we return the credit card. In each if statement, we had the variable $type and set it equal to the credit card type it is.
Else, if there are no matches, we return false.
We then simply call the function validatecard so that we actually execute it.
We run an if statement to see if what the function returns is not equal to false. If not equal to false (if it is true), we output the card detected and that the credit card number is valid.
If what the function returns is equal to false, then we output that the credit card number is invalid.
And this is all that is required to validate a credit card using PHP.
Of course, there is so much more advanced analytics involved in this. We have taken into account expiration dates and the security code. That requires much more advanced analytics, in which you basically have to contact the credit card vendor to get confirmation. And this is normally what when the actual payment is submitted. You would then have to check the actual vendor.
But what we are doing here is simply checking the format and seeing whether is card value initially just by the numbers that the user enters. If the credit card number isn't valued, then we're going to waste resources, sending this number to the credit card vendor to be processed when it's erroneous to begin with. It first has to be in correct format. This doesn't mean that the actual credit card is correct, but the format is. It's the right number of digits, beginning with the right numbers. Then after that, we can send the information to a credit card to be processed. But before we do that, we first have to make sure the credit card number to begin with. So this is what we're doing.
Related Resources
How to Retrieve Data From a MySQL Database Using AJAX and PHP
Generate a Random Password
In this article, we show how to generate a random password using PHP.
Refresh this page and see the random password change each time.
Random Password: 6Bmqi-cgel
Many sites use random passwords.
For example, say you go to a website. This website needs you to login in to your account. Say you don't remember
your password and can't log into your account. You then click the link "Forgot Password". This page may require you to enter
in some additional information so that it can verify that you are in fact the account owner. Once you've done this and submitted
the information, it may email you a temporary password. You then go back to the login page, type in the temporary password, are granted access into your account, where you can then change the password to any password you want.
This is done for many, many sites on the web.
So maybe you want to implement a system like this on your website.
So now we can go over how this can be done with PHP code.
So, for the random password generator I've decided to create, I made it so that the random password is a 10-character string. You can make it however many characters you want.
Obviously the more characters you have, the harder it is to guess a temporary password. This, in turn, makes the account less vulnerable to being hacked into, in case someone is trying to do so.
However, you also don't want to make it so long that it's like 30 characters. Because it's really unnecessary.
For this password, we'll have a variety of characters in the string including special symbols and numbers.
This makes the password more difficult to guess and, thus, strengthens security.
So the PHP to create this random password generator is shown below.
<?php
$passwordlength= 10;
$symbols= '~!@#$*%`?[]{};<>?.,_-()';
$symbolscount= strlen($symbols);
$randomposition= mt_rand(0, $symbolscount - 1);
$password= substr($symbols, $randomposition, 1);
$password .= chr(mt_rand(48,57));
$password .= chr(mt_rand(65,90));
while (strlen($password) < $passwordlength)
{
$password .= chr(mt_rand(97,122));
}
$password = str_shuffle($password);
echo $password;
?>
So now let's go over all the code required to make this random password generator, in case you want to be able to modify it.
So the first thing that we specify in the code is the password length. In this code, we chose a length of 10 characters for the password generated. You can change it to any amount. I mean, you do want it to be a reasonable amount, though.
You don't want a password that's 50 characters in length long. That's unnecessary. So anywhere from 8 to 12 is reasonable. But of course you're free to do what you want.
After we specify the length of the password, we created a list and special symbols and store it in the
$symbols variable. You can add whatever special symbols you want added. This is totally a free list. You can add any characters
you may want to appear in the random password.
We then create a variable named $symbolscount. This counts the number of special symbols in the $symbols variable we created before.
We then create a variable named $randomposition. We use the mt_rand() function to pick a random position that runs the length of the $symbols variable. The $symbols variable runs from an index of 0 to $symbolscount - 1.
The mt_rand() function is a function that chooses a random value from a list of values.
Since we want it to pick any position in the list of the symbols (with the list starting from 0 and ending at $symbolscount - 1), the full line of code is,
$randomposition= mt_rand(0, $symbolscount - 1);
Next, we actually begin creating the password. We use the substr() function to take a part of the $symbols variable. It takes a single random character from the $symbols variable. We place this single random character in the
$password variable.
We then take a random character from the ASCII values of 48-57 and append it to the $password variable. The ASCII
values of 48-57 pertain to the values of 0-9. A random character is selected from 0 to 9 and appended to the $password variable.
We then take a random character from the ASCII values of 65-90 and append it to the $password variable. The
ASCII values of 65-90 pertain to the values of A-Z (uppercase characters). A random uppercase alphabet character is selected
from A to Z and appended to the $password variable.
We then have a while statement. While the length of the password is less than the length that we want it to be, we append a lowercase alphabet character to the password. The ASCII values of 97 to 122 pertain to a-z, the lowercase alphabet
characters. As long as the password is less than the length we specify and want it to be, lowercase alphabet characters are appended to the password string. Once the length of the password is what we specified, then we come out of the while loop.
After this, we use the PHP str_shuffle() function to shuffle the characters in the string in any type of order.
We then output the password.
Note that there are several variations that can be done. For example, we don't simply have to add one special symbol.
We can add 2 instead. The modification to the code necessary to do so can be found at the following link:
Code to add 2 special symbols to the password of the random password generator.
If you want to add a second number to the random password string, you would just duplicate the exactly the line of code, $password .= chr(mt_rand(48,57)); With 2 of these lines in the code, this adds 2 numbers to the random password string
instead of just one.
So now that you know these modifications, you can generate any random password you want of any length.
Create a Confirmation Page for an HTML Web Form
In this article, we show how to create a confirmation page for an HTML web form using PHP.
Let's say we have the form below. Let's pretend it's a form that a company uses for its customers
to elicit information from them.
<form action="">
<label>First Name:</label><input type="text"id="txtFirstName" value=""/>
<label>Last Name:</label> <input type="text"id="txtLastName" value=""/>
<label>Email Address:</label><input type="text"id="EmailAddress" value=""/>
<label>Telephone Number:<label><input type="text"id="TelephoneNumber" value=""/>
<input name="Form" type="submit"/>
</form>
However, this form doesn't do anything when the submit button is pressed. Therefore, it's useless. We neither post nor retrive the customer's information.
How can we make this form useful so that we can take the information and post a confirmation page to the user so that he/she knows that the information has been successfully received.
To do this, we use PHP.<form action="customerinfo.php" method="post">
<label>First Name:</label><input type="text"name="FirstName" value=""/>
<label>Last Name:</label> <input type="text"name="LastName" value=""/>
<label>Email Address:</label><input type="text"name="EmailAddress" value=""/>
<label>Telephone Number:</label><input type="text"name="TelephoneNumber" value=""/>
<input name="form" type="submit"/>
</form>
To create this form, this is the code used, shown below, to do so:
<form action="customerinfo.php" method="post">
First Name:
<input type="text"name="FirstName"/>
Last Name:
<input type="text"name="LastName"/>
Email Address:
<input type="text"name="EmailAddress"/>
Telephone Number:
<input type="text"name="TelephoneNumber"/>
<input name="form" type="submit"/>
</form>
The first line is of the most importance.
The form tag contains the "action" attribute.
The "action" attribute is set to the PHP file that will contain the script that allows us to create the confirmation page. In this case, the PHP file is customerinfo.php, but you can call your PHP file whatever you want. Just make sure it correlates to the appropriate name of the external
PHP file that it references. The "method" attribute tells the server that we want to retrieve this data and post it to a web page.
All of the data below this first line is just standard HTML to create the text boxes.
Now that we know the HTML to set up for the creation of the confirmation page, let's go over what goes into the PHP file.
PHP File
This is the PHP file:
Confirmation Page of Customer Info
Thank you for submitting this form.
We have successfully received it.
Below is a summary of the information you provided.
<?php
echo 'First Name: ' . $_POST ["FirstName"] . ' ';
echo 'Last Name: ' . $_POST ["LastName"] . ' ';
echo 'Email Address: ' . $_POST ["EmailAddress"] . ' ';
echo 'Telephone Number: ' . $_POST ["TelephoneNumber"];
?>
Everything in this file is standard HTML except for the code in the PHP block, which is highlighted above in red. So the code in red, the PHP code, is the only section we'll focus on.
The echo command prints out statements to the computer screen.
-The echo statement is placed in ' ' (single quotes).
0The first part of the echo statement, 'First Name: ' prints out "First Name: "
-The . (period) is a concatenation operators. It connects together the various parts of a PHP statement.
-The $_POST ["FirstName"] follows next. The "FirstName" is the variable name of the textbox that asks for the customer's first name. The $_Post must be written so that the variable can be fetched from the HTML document
that contains the user-added variable. Otherwise, it would look for the variable on the same page.
-The concatenation operator again to connect the various parts of a statement.
-The br tag now appears within ' ' (single quotes) to give a line break within each of the echo
statements.
-The semicolon (;) ends the statement in PHP.
And this repeats for all the other variables.
And this is how a confirmation page is created for an HTML Web Form using PHP.
Related Resources
How to Create a Search Engine Using PHPHow to Upload Images to a Website Using PHPHow to Upload Files to a Website Using PHPHow to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHPHow to Create a Register and Login Page Using PHP
Redirect to Another URL
In this article, we show how to redirect a user to another URL (page) using PHP.
The way to accomplish this to use the location header () function. Using this function, a URL redirect can be done in PHP. So we fully demonstrate how to do this.
We'll illustrate this using a search text box
where a user types in a term and presses the submit button and then is redirected by the search box to the URL he is looking for. For example, a user may type in the phrase,
'google', and then be redirected to the google homepage.
Executing a redirect in PHP isn't difficult. Only that is needed is a simple header location function. If statements are used
to redirect a user to a certain page, as specified by the search query.
To do this, let's start with the HTML. We create a text box, as is shown below:
<form action="searchpage.php" method="post">
<h2>Search Engine</h2>
Enter Product Name </label><input type="text"name="search" id="txtName"/><br><br>
<input type="submit" name="submit" id="submit" value="Search"/>
</form>
The only terms this search engine contains so far:
Dropbox
Amazon
google
ebay
wikipedia
youtube
hess toy truck
LM7805
HTML Code
The HTML Code to create this text box above is:
<form action="searchpage.php" method="post">
<h2>Product Search</h2>
<label>Enter Product Name </label>
<input type="text"name="search" id="txtName"/><br><br>
<input type="submit" name="submit" id="submit" value="Search"/>
</form>
Now that we've created a text box and a user is able to type in the term he or she is searching for, we now need to redirect the user to the necessary page based on the search query s/he has entered. For example, if the user enters the search query, "amazon", we then need to redirect him to the amazon website.
To do this, we use PHP. PHP will extract the search term that the user has entered and use a series of if statements to see if that term matches a term we have in our list of if statements. If it does, we then direct the user to the necessary URL page on that search term using the PHP header function. This will be explained below.
If no search term matches any that we have on our website, then we redirect the user to a page that states, "No results found for this search".
Example
An example of this is a user looking up the term 'Hess toy trucks'. We need to create the page Hess toy trucks so that when the user enters the term, we have the page to redirect them to, and we need to create an if statement on the PHP page, searchpage.php to check which term is selected.
This is what the PHP page, searchpage.php, will look like:
<?php
$result= $_POST['search'];
$result= strtolower($result);
if ($result=="dropbox")
header ('Location: http://www.dropbox.com');
if ($result=="amazon")
header ('Location: http://www.amazon.com');
if ($result=="google")
header ('Location: http://www.google.com');
if ($result=="ebay")
header ('Location: http://www.ebay.com');
if ($result=="wikipedia")
header ('Location: http://www.wikipedia.org');
if ($result=="youtube")
header ('Location: http://www.youtube.com');
if ($result=="hess toy truck")
header ('Location: https://hesstoytruck.com');
if ($result == "LM7805")
header ('Location: http://www.learningaboutelectronics.com/Articles/What-is-a-LM7805-voltage-regulator');
echo "No results found for this search";
?>
Basically, the PHP page, searchpage.php, retrieves the search term that the user enters using the superglobal array, $_POST, and then compares it against a series of if statements.
If the search term that the user entered matches a search term that is the series of if statements, the user is redirected to that page that the URL specifies in the header function. If none of the search terms match the statement, No results found for this search will be output to the screen.
one trick that we use to simplify this process is when we retrieve the search term the user entered, we lowercase the string using the strtolower() function. This why no matter what string the user enters, it becomes lowercase. Therefore, when we are comparing strings, we can just compare it only with the string with lower case alphabetical characters. An example is different users typing in "Hess Truck", "HESS TRUCK",
"Hess truck", and "HESS truck". If we didn't convert these to lowercase, we would have to have comparisons to each capitalized of each letter in each word. These would be tedious. By converting the string to all lowercase, all we must do is compare the string to its all lowercase equivalent. Therefore, all we must do is compare it with the line if ($result=="hess truck").
You can put as many terms as you want in the searchpage.php and redirect users to the desired page using the header function.
So these redirects work well. The search box redirects a user to a certain page if the user types in the exact phrase
desired. If you want to add more flexibility, instead of using the direct if statement, for example, if ($result == "amazon"), you can use
if (strpos($result, "amazon") == "true"), this way the search query doesn't need to be a direct match in order to redirect to the amazon page. Instead if the user types in a phrase that contains the word 'amazon' such as 'amazon website' or 'amazon homepage',
s/he will be redirected to the amazon site. If the direct (==) if statement, the user is only directed to the amazon website if the search query is directly 'amazon'. For more details on this, see
How to Create a Search Engine Using PHP. This shows in-detail how to create an advanced search box that can return increasingly relevant results.
Now we have a search box that does redirects that doesn't require a direct character-for-character match.
If the user types in 'youtube homepage' or 'youtube videos', s/he will still be redirected
to the youtube homepage, because the search query contains the word 'youtube'.
A few points to make about this creating the searchpage.php page. When you do so, make sure there is absolutely no space before the <?php tag. Putting space in between the PHP tag may send output to the browser and the code will not work.
Before PHP can execute this redirect function, no output can be written to the browser. No nothing at all can go before the <?php tag, not even white space.
Otherwise, you will get an error that says something to the effect of,
Warning: Cannot modify header information - headers already sent by (output started at /home/content/.../searchpage.php:1).
This means that before PHP performed the redirect, output was already written to the browser. With the PHP header location redirect, this is forbidden. Also, for the same reason, when you save the searchpage.php file, save it in ANSI encoding. Do not save it in unicode, unicode big endian, or UTF-8 encoding. These encoding may encrypt and add characters before the PHP code
even when there is no white space there. ANSI is the purest encoding that doesn't add any characters before the <?php tag and this will produce the best results. To see a more in-depth article on this PHP header function error, see PHP Header Location Error- Warning: Cannot Modify Header Information- Headers Already Sent.
This is how URL redirects can be achieved easily with PHP.
Related Resources
How to Create a Confirmation Page for an HTML Web Form Using PHPHow to Insert Images into a MySQL Database Using PHP How to Create a Searchable Database Using MySQL and PHP
You can easily create your own search engine in PHP.
This is a text box where a user types in a term and presses the submit button and then is redirected by the search engine to the page he is looking for. For example, a user may type in the phrase,
'youtube', and then be redirected to the youtube homepage.
This type of search engine isn't google. It doesn't search through dozens of sites and then sends the most relevant results based on the query. It isn't that advanced. What it does is, according to the search query that you enter, if there is a matching if statement for that query, it will redirect a person to the page most relevant according to that query. So it isn't a search engine that returns many relevant results, but a search engine that redirects a user to a page. It's a much more simpler search engine, but still very effective for basic purposes and something you may desire for your website.
Building this type of search engine is actually not hard at all. It's actually very simple code.
To do this, let's start with the HTML. We create a text box, as is shown below:
<form action="searchpage.php" method="post">
<h2>Search Engine</h2>
Search </label><input type="text"name="search" id="txtName"/><br><br>
<input type="submit" name="submit" id="submit" value="Search"/>
</form>
The only terms this search engine contains so far:
Dropbox
Amazon
google
ebay
wikipedia
youtube
hess toy truck
LM7805
HTML Code
The HTML Code to create this text box above is:
<form action="searchpage.php" method="post">
<h2>Product Search</h2>
<label>Enter Product Name </label>
<input type="text"name="search" id="txtName"/><br><br>
<input type="submit" name="submit" id="submit" value="Search"/>
</form>
Now that we've created a text box and a user is able to type in the term he or she is searching for, we now need to redirect the user to the necessary page based on the search query s/he has entered. For example, if the user enters the search query, "wikipedia", we then need to redirect him to the wikipedia website. To do this, we use PHP. PHP will extract the search term that the user has entered and use a series of if statements to see if that term matches a term we have in our website. If it does, we then direct the user to the necessary page on that search term using the PHP header function. This will be explained below. If no search term matches any that we have on our website, then we redirect the user to a page that states, "No Searches Matched".
Example
An example of this is a user looking up the term 'Hess toy trucks'. We need to create the page Hess toy trucks so that when the user enters the term, we have the page to redirect them to, and we need to create an if statement on the PHP page, searchpage.php to check which term is selected.
This is what the PHP page, searchpage.php, will look like:
<?php
$result= $_POST['search'];
$result= strtolower($result);
if ($result=="dropbox")
header ('Location: http://www.dropbox.com');
if ($result=="amazon")
header ('Location: http://www.amazon.com');
if ($result=="google")
header ('Location: http://www.google.com');
if ($result=="ebay")
header ('Location: http://www.ebay.com');
if ($result=="wikipedia")
header ('Location: http://www.wikipedia.org');
if ($result=="youtube")
header ('Location: http://www.youtube.com');
if ($result=="hess toy truck")
header ('Location: https://hesstoytruck.com');
if ($result == "LM7805")
header ('Location: http://www.learningaboutelectronics.com/Articles/What-is-a-LM7805-voltage-regulator');
echo "No results found for this search";
?>
Basically, the PHP page, searchpage.php, retrieves the search term that the user enters using the superglobal array, $_POST, and then compares it against a series of if statements.
If the search term that the user entered matches a search term that is the series of if statements, the user is redirected to that page that the URL specifies in the header function. If none of the search terms match, the statement, No Searches Matched will be output to the screen.
one trick that we use to simplify this process is when we retrieve the search term the user entered, we lowercase the string using the strtolower() function. This why no matter what string the user enters, it becomes lowercase. Therefore, when we are comparing strings, we can just compare it only with the string with lower case alphabetical characters. An example is different users typing in "Hess Truck", "HESS TRUCK",
"Hess truck", and "HESS truck". If we didn't convert these to lowercase, we would have to have comparisons to each capitalized of each letter in each word. These would be tedious. By converting the string to all lowercase, all we must do is compare the string to its all lowercase equivalent. Therefore, all we must do is compare it with the line if ($result=="hess truck").
You can put as many terms as you want in the searchpage.php and redirect users to the desired page using the header function.
This search engine works great, but there's one problem. It only returns a result if the user enters the exact phrase you are looking for. For example, if a user is trying to go find information about the LM7805 voltage regulator and types in 'LM7805 voltage regulator' instead of just 'LM7805', the search won't redirect to the page on LM7805 voltage regulators. This is because
according to the code the if statement looks for the exact equal of the phrase (==). Thus, it must be a perfect match. Same thing for another search query. If a user types in 'google homepage' and not 'google', the person won't be brought to the google website. This is because again the if statement looks for a direct equal (==). So to counter, if the phrase contains the word google, such as 'google homepage' or 'google search engine', then the user will still be redirected to the google homepage, because his/her search contains the word 'google'. The same thing if the user types
in 'LM7805 voltage regulator'. Because the search query contains the phrase 'LM7805', the search engine recognizes this and reroutes the person to the LM7805 voltage regulator page.
So how is this done? It's simple. Instead of the php if statement being a direct equal (==), as in,
if ($result=="google"), which must be directly equal, we change the statement to, if (strpos($result, "google") == "true")
What this statement does is it looks for the phrase, 'google', in the search query. If the position of that phrase is present in the string, the if statement is true; if it is true, we can redirect them to the google homepage. This is because as long as 'google' is present in the search query, the if statement is true. And then underneath we put the header location redirect
function.
So we create a new searchpage named searchpage2.php and change the if statements, as shown above, we'll get this file, which is shown below.
<?php
$result= $_POST['search'];
$result= strtolower($result);
if (strpos($result, "dropbox") == "true")
header ('Location: http://www.dropbox.com');
if (strpos($result, "amazon") == "true")
header ('Location: http://www.amazon.com');
if (strpos($result, "google") == "true")
header ('Location: http://www.google.com');
if (strpos($result, "ebay") == "true")
header ('Location: http://www.ebay.com');
if (strpos($result, "wikipedia") == "true")
header ('Location: http://www.wikipedia.org');
if (strpos($result, "youtube") == "true")
header ('Location: http://www.youtube.com');
if (strpos($result, "hess toy truck") == "true")
header ('Location: https://hesstoytruck.com');
if (strpos($result, "lm7805") == "true")
header ('Location: http://www.learningaboutelectronics.com/Articles/What-is-a-LM7805-voltage-regulator');
echo "No results found for this search";
?>
Now we have a search engine that doesn't require a direct character-for-character match. If the user types in 'youtube homepage' or 'youtube videos', s/he will still be redirected
to the youtube homepage, because the search query contains the word 'youtube'.
And you can keep refining this search engine. For example, if a user types in 'google maps' instead of just rerouting them to the google hompage, you can create another if statement
that if the result contains 'google' and 'maps' to redirect the user to google maps instead of simply the google homepage. If you do this where you're using the same root phrase 'google' but for different categories within google, it is best to use if else statements instead of just if statements. But it isn't absolutely necessary if you're using and statements. This if statement would look like this, if ((strpos($result, "google") == "true") && (strpos($result, "maps") == "true"))
Then underneath you would put the header location redirect function to, header ('Location: https://maps.google.com/');
And this is how you can build a search engine that can become more and more advanced, or more and more intelligent. You keep making more divisions and if statements. So if a user
types in 'google' and 'finance' within the same search, you can bring them to the google finance page. If a user types in 'google' and 'images' in the same search, you can bring them to the
'google images' page. And so on and so forth.
A few points to make about this creating the searchpage.php page. When you do so, make sure there is absolutely no space before the <?php tag. Putting space in between the PHP tag may send output to the browser and the code will not work.
Before PHP can execute this redirect function, no output can be written to the browser. No nothing at all can go before the <?php tag, not even white space.
Otherwise, you will get an error that says something to the effect of,
Warning: Cannot modify header information - headers already sent by (output started at /home/content/.../searchpage.php:1).
This means that before PHP performed the redirect, output was already written to the browser. With the PHP header location redirect, this is forbidden. Also, for the same reason, when you save the searchpage.php file, save it in ANSI encoding. Do not save it in unicode, unicode big endian, or UTF-8 encoding. These encoding may encrypt and add characters before the PHP code
even when there is no white space there. ANSI is the purest encoding that doesn't add any characters before the <?php tag and this will produce the best results. To see a more in-depth article on this PHP header function error, see PHP Header Location Error- Warning: Cannot Modify Header Information- Headers Already Sent.
This is how you create a search engine in PHP.
Related Resources
How to Create Your Own Search Engine For Your Website Using PHPHow to Create a Custom Search Engine For Your Website Using PHPHow to Create an Image Search Engine For Your Website Using PHPHow to Create a video Search Engine For Your Website Using PHPHow to Create an Audio File Search Engine For Your Website Using PHPHow to Upload Images to a Website Using PHPHow to Upload Files to a Website Using PHPHow to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHPHow to Create a Confirmation Page for an HTML Web Form Using PHPHow to Insert Images into a MySQL Database Using PHP How to Create a Searchable Database Using MySQL and PHP
Create Your Own Search Engine For Your Website Using
In this article, we show how to build your own search engine for your website using just PHP.
This search engine we are going to build doesn't require MySQL in conjunction with PHP. It just requires PHP alone.
You can see the search engine shown above.
This search engine shown above searches this whole site.
This website has a pretty good, extensive list of articles on electronics. So if you type in 'transistor', 'resistor',
'capacitor', 'power', 'circuit', you'll get back a ton of results.
This search engine simply gives the URL of the pages that are found based on the search.
It lists every page on my website that matches all of the words in the search query.
If you try it out above, you'll see this.
Building this search engine literally took me about an hour or 2 to code.
It's very simple and it doesn't require any vast enormous databases such as using MySQL database and having multiple tables to search. Its' just PHP.
So how does this work?
So, as you probably know if you run a website, you upload files to your website through a file transfer protocol (FTP).
These files can place in a directory on your website. This can be the home directory (/), the Articles directory (Articles/), the images
directory (images/), or whatever else directory you created and named. You're probably familiar with this if you run a website.
Files are uploaded to directories (or folders) on your website.
So you have files in either one directory or various directories.
Using PHP, you can access any directory on your website.
Being that PHP is a server side language, it can access back-end things such as a website's directories.
So once we gain to a directory on your website with PHP, we can search it. We create a search text box such as what you see above and then we extract the query entered and see if any files in that directory match the query. If it does, we output it in the form of a hyperlink.
And that's as simple as it is.
We either can search one directory or multiple directories on your website.
A user enters a search query.
If the search query matches anything in the files of the directory (or directories) being searched, we can output the hyperlink. As many pages that match the query get outputted.
So it's very simple.
The only thing is that your files must have appropriate names. For example, if you have a file on dandelion flowers. It will have that in the file name, for example, how-to-feed-dandelion-flowers.html or how-to-grow-dandelion-flowers.php or just dandelion-flowers.html. It has to have the name in the filename. If you have an article on dandelion flowers and it's named 123wxp.html, this search engine won't work. It's based on the fact that it looks at the file name. The file name should have the keywords that the user is searching for.
So now that you get an idea of how it works, we're now going over all the code needed to get
this up and running on your website.
If you just want the code, the full code of this image search engine is at the following link:
Code to create your own search engine for your website using PHP.
Remember that you have to change the directory to the directory you want to search. Also you have to change the website name to your website name when outputting the link to the search engine result returned.
Also when you copy this code to your web page, make sure it's saved as a PHP file.
HTML Code
So now we'll first go over the HTML code needed for this search engine.
The HTML code is needed just to create the search text box.
Everything else is PHP.
<form action="" method="POST">
Enter Search Query:
<input type="text" name="search_entered" value=''/>
<input type="submit" name="submit" value="Search"/>
</form>
So the above code creates the search box.
First, we create an HTML form. We set the action equal to "" because we want the information to this page. If we wanted the information sent to another page, we want specify this file within this action attribute. We set the method equal to POST.
As almost all forms require, we add a submit and give it the value, "Search". Thus, Search is displayed on the button.
We also add PHP code so that if the submit button is clicked and the search text box is empty, the statement "A search query must be entered" is output.
We then close the form.
This concludes the HTML code needed to make this search engine.
PHP CodeFirst Block of PHP Code
We now go on to the PHP code necessary to make this search engine work.
We separate the PHP code into 2 blocks of code.
The first block of PHP code is shown below.
<?php
$search= $_POST['search_entered'];
$searchoriginal= $search;
$search= strtolower($search);
$search= trim($search);
$search= explode(" ", $search);
$countsearchterms= count($search);
$submitbutton= $_POST['submit'];
?>
This PHP extracts the search query that the user enters into the search text box.
We then a $searchoriginal variable so that the search term that the user has entered is kept intact. We later will be doing many modifications to the search query that the user has entered.
We then make all the characters of the search query that the user has entered lowercase. This is because case matters in PHP. By making all the characters lowercase, we don't have to worry about case sensitivity.
We then use the PHP $trim function to cut off any space in front of the search query or the back of the search query (or left of the query or right of the query).
Next, we explode the $search variable. The explode() function in PHP separates a string based on a certain parameter. Here, we want the $search variable explosed based on any space characters (" "). The reason we want to do this is because the user may type in more than one word into the search engine. For example, the user may type in
"transistor circuit". If we forget about exploding the term and we just accept the search query directly, only terms that have the direct phrase, "transistor circuit" will be returned. If a
page is named, How-to-connect-a-transistor-to-a-circuit, this page will not be returned because the term "transistor circuit" isn't consecutive to the string. The terms in the name are separated.
So we'll miss this search. Only a term that has "transistor circuit" with the terms exactly "transistor circuit" will be returned.If these 2 terms are separated in the name, this search will be skipped. To avoid this, we explode the term and then look at each term separately. If the name of the file has both terms, it will be returned in the search results. Another example of this is a user typing in, "pepperoni pizza". Without exploding the term, only results that have the phrase "pepperoni beef pizza" in that exact order will returned. A page that is named, "Adding pepperoni
and beef to pizza" will not be returned because the phrase "pepperoni beef pizza" isn't in it, even though all the terms are in it. So you can see why we wouldn't want to just use the phrase exactly that the user inputs.
So after we explode the search query based on spaces, we then count the number of terms in the $search variable. Again, the explode() function separates the string into separate entities based on the parameter entered, in this case a space (" "). We now count the number terms in the $search variable. This is how we know how many terms the user has entered in.
Lastly, we make sure that we obtain the value of the submit button to see if it has been clicked. If it has been clicked, it returns true. If not, it returns false.
Second Block of PHP Code
This is now the second and last block of PHP code shown below.
<?php
$directory = "Articles/";
if ($submitbutton){
if (!empty($searchoriginal))
{
if (is_dir($directory)){
if ($open = opendir($directory)){
if ($countsearchterms == 1)
{
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if (strpos("$file", "$search[0]") !== false)
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 2) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 3) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 4) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 5) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)
&& (strpos("$file", "$search[4]") !== false))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 6) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)
&& (strpos("$file", "$search[4]") !== false) && (strpos("$file", "$search[5]") !== false))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 7) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$position= strpos("$file", ".");
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)
&& (strpos("$file", "$search[4]") !== false) && (strpos("$file", "$search[5]") !== false) && (strpos("$file", "$search[6]") !== false))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
closedir($open);
}
}//while loop
$arraycount= count($array);
if ($arraycount == 0)
{
echo "No results for this search entered";
}
}
}
?>
So this, you can see, is the longer block of PHP code. Still, it isnt' hard.
First, we specify which directory we want to search that is on our website.
Practically, all of my website's pages are in the Articles directory. So I set the directory equal to "Articles/"
Change this to the directory you want searched.
If you want to add multiple directories, copy and paste all of this code and change the directory information. That way, you can add all the directories you want searched on your
website.
So once we've specified the directory, we then go to the heart of code. We first check to see if the submit button has been clicked. If it has, the code advances to the next line.
We have a second if that that checks to see if a search query has been entered. If it has and the search query isn't empty (a null string), the code advances to the next line. The next line is a third if statement. The line checks to see if the directory is actually a directory. If it is, the code advances to the line. The line opens up that directory.
We then have another if statement. If the number of terms in the search query is just one single word, the while loop is executed. The while loop loops through the files in that directory.
Because we're going to modify the file name, we created a $fileoriginal variable that holds the file intact. This is important because we'll need when we're outputting the link to the file.
We then make the $file lowercase. By making the search query lowercase in previous and making the $file lowercase now, we have equal cases. Therefore, we don't have to worry about cases matching. All are lowercase, so they're at equal plane.
Since most files are separated by "-" or "_", we use the PHP str_replace() function to replace these symbols with spaces. This make the link more human readable than if it had all these symbols.
Next, we have to eliminate the ending of the filename, such .html, .php, etc. This is not needed when we want to view the results returned from the search. Again, this makes the results returned more human readable. We don't care whether the results returned are html or PHP pages.
So we go about doing this by finding the position of the ".". Once we know its position, we know that what's after the "." is the file extension (.html or .php, etc).
So we then use the PHP substr() function to just take the portion of the file that isn't the extension.
So now we just have the file name without the file extension.
Next, we have if an if statement. We use the strpos() function in PHP that if the search term is in the file name, that result is going to be returned. If the search query is in the file name, this if statement returns true. If so, it advances.
We then use the PHP ucwords() function to capitalize each word in the string. It again is done to make the results returned more human readable and better visually.
Now we create an array that stores if any files are returned that match that query. The reason we do this is because later on, if no results are returned from the search query entered, we then count this array. If it is equal to 0, no files have been returned that match the search query, which means we can output a statement, "No results found for this search query".
We then use the PHP echo () function to output the links to the pages found that match the search query. Whether it's 1 result or 50 results, all are returned that match the search query.
Next we have an if statement if the search query has 2 terms, meaning the user has entered 2 words into the search box. All the code is the same except for the last if statement
in that block of code. Now since there are 2 search words, the if statement is composed of 2 strpos() functions. If the file name has both terms in it, then it is returned in the results.
This search engine covers the user entering up to 7 words in the search box. For search, that usually is sufficient. However, if you want to make it more just copy and paste
more blocks of code and just change the value of $countsearchterms and up to $search[number] value. I would say the maximum would be 10. I don't think a user is going to type in 30 words into a search engine.
After that, we close the directory.
We then count the $array.
If the $array is equal to 0, then no search results have been returned. So we output the statement, "No results have been found for this search".
And this concludes all the code needed to create a search engine for your website.
Again, no database involvement. No MySQL. Just straight PHP code directly to directories on your website.
Related Resources How to Create a Search Engine Using PHPHow to Create a Custom Search Engine For Your Website Using PHPHow to Create an Image Search Engine For Your Website Using PHPHow to Create a Video Search Engine For Your Website Using PHPHow to Create an Audio File Search Engine For Your Website Using PHP
Create a Custom Search Engine For Your Website
In this article, we show how to build a custom search engine for your website using PHP.
This search engine we are going to build doesn't require MySQL in conjunction with PHP. It just requires PHP alone.
You can see the search engine shown above.
This search engine shown above searches a specific directory for the website and only returns documents that are PDF documents.
I've made it so that this search engine searches the Datasheets directory of this website. This way, a user can find the datasheets of various electronic components (datasheets are usually almost always on PDF documents). So I've created a datasheet search engine for my website just with a few lines of PHP code.
Being that this is a custom search engine we're building that can cater directly to your needs at any moment, you can make it search any directory on your website
for any type of document, whether it's an image file (such as .jpg, .png, or .bmp), a document (such as .txt or .pdf), or a video file (such as .mov or .mp4).
I mean you can make a real custom search engine.
That's the great thing about knowing how to build a custom search engine. You can program it to search for anything. Not only can we search for specific type of documents, you can also get the size of files so that you can customize which size files should be returned. What if you are looking large files on your site to empty space on it. You can set up a search engine so that
only files greater than 100MB are returned in the search results. Then you can happily delete it if you don't need it.
It's very dynamic.
As previously stated, the above search engine searches the Datasheets directory returns only PDF documents from this documentary, making it a search engine for electronic component datasheets.
If you type 'BC547' or 'transistor datasheet' or '555 timer datasheet', you'll get back results.
.
It's very simple and it doesn't require any vast enormous databases such as using MySQL database and having multiple tables to search. Its' just PHP.
So how does this work?
So, as you probably know if you run a website, you upload files to your website through a file transfer protocol (FTP).
These files can place in a directory on your website. This can be the home directory (/), the Articles directory (Articles/), the images
directory (images/), or whatever else directory you created and named. You're probably familiar with this if you run a website.
Files are uploaded to directories (or folders) on your website.
So you have files in either one directory or various directories.
Using PHP, you can access any directory on your website.
Being that PHP is a server side language, it can access back-end things such as a website's directories.
So once we gain to a directory on your website with PHP, we can search it. We create a search text box such as what you see above and then we extract the query entered and see if any files in that directory match the query. If it does, we output it in the form of a hyperlink.
And that's as simple as it is.
We either can search one directory or multiple directories on your website.
A user enters a search query.
If the search query matches anything in the files of the directory (or directories) being searched, we can output the hyperlink. As many pages that match the query get outputted.
So it's very simple.
The only thing is that your files must have appropriate names. For example, if you have a file on dandelion flowers. It will have that in the file name, for example, how-to-feed-dandelion-flowers.html or how-to-grow-dandelion-flowers.php or just dandelion-flowers.html. It has to have the name in the filename. If you have an article on dandelion flowers and it's named 123wxp.html, this search engine won't work. It's based on the fact that it looks at the file name. The file name should have the keywords that the user is searching for.
So now that you get an idea of how it works, we're now going over all the code needed to get
this up and running on your website.
If you just want the code, the full code of this image search engine is at the following link:
Code to create a custom search engine for your website using PHP.
Remember that you have to change the directory to the directory you want to search.
Also you have to change the website name to your website name when outputting the link to the search engine result returned.
Also when you copy this code to your web page, make sure it's saved as a PHP file.
HTML Code
So now we'll first go over the HTML code needed for this search engine.
The HTML code is needed just to create the search text box.
Everything else is PHP.
<form action="" method="POST">
Enter Search Query:
<input type="text" name="search_entered" value=''/>
<input type="submit" name="submit" value="Search"/>
</form>
So the above code creates the search box.
First, we create an HTML form. We set the action equal to "" because we want the information to this page. If we wanted the information sent to another page, we want specify this file within this action attribute. We set the method equal to POST.
As almost all forms require, we add a submit and give it the value, "Search". Thus, Search is displayed on the button.
We also add PHP code so that if the submit button is clicked and the search text box is empty, the statement "A search query must be entered" is output.
We then close the form.
This concludes the HTML code needed to make this search engine.
PHP CodeFirst Block of PHP Code
We now go on to the PHP code necessary to make this search engine work.
We separate the PHP code into 2 blocks of code.
The first block of PHP code is shown below.
<?php
$search= $_POST['search_entered'];
$searchoriginal= $search;
$search= strtolower($search);
$search= trim($search);
$search= explode(" ", $search);
$countsearchterms= count($search);
$submitbutton= $_POST['submit'];
?>
This PHP extracts the search query that the user enters into the search text box.
We then a $searchoriginal variable so that the search term that the user has entered is kept intact. We later will be doing many modifications to the search query that the user has entered.
We then make all the characters of the search query that the user has entered lowercase. This is because case matters in PHP. By making all the characters lowercase, we don't have to worry about case sensitivity.
We then use the PHP $trim function to cut off any space in front of the search query or the back of the search query (or left of the query or right of the query).
Next, we explode the $search variable. The explode() function in PHP separates a string based on a certain parameter. Here, we want the $search variable explosed based on any space characters (" "). The reason we want to do this is because the user may type in more than one word into the search engine. For example, the user may type in
"transistor circuit". If we forget about exploding the term and we just accept the search query directly, only terms that have the direct phrase, "transistor circuit" will be returned. If a
page is named, How-to-connect-a-transistor-to-a-circuit, this page will not be returned because the term "transistor circuit" isn't consecutive to the string. The terms in the name are separated.
So we'll miss this search. Only a term that has "transistor circuit" with the terms exactly "transistor circuit" will be returned.If these 2 terms are separated in the name, this search will be skipped. To avoid this, we explode the term and then look at each term separately. If the name of the file has both terms, it will be returned in the search results. Another example of this is a user typing in, "pepperoni pizza". Without exploding the term, only results that have the phrase "pepperoni beef pizza" in that exact order will returned. A page that is named, "Adding pepperoni
and beef to pizza" will not be returned because the phrase "pepperoni beef pizza" isn't in it, even though all the terms are in it. So you can see why we wouldn't want to just use the phrase exactly that the user inputs.
So after we explode the search query based on spaces, we then count the number of terms in the $search variable. Again, the explode() function separates the string into separate entities based on the parameter entered, in this case a space (" "). We now count the number terms in the $search variable. This is how we know how many terms the user has entered in.
Lastly, we make sure that we obtain the value of the submit button to see if it has been clicked. If it has been clicked, it returns true. If not, it returns false.
Second Block of PHP Code
This is now the second and last block of PHP code shown below.
<?php
$directory = "Datasheets/";
if ($submitbutton){
if (!empty($searchoriginal))
{
if (is_dir($directory)){
if ($open = opendir($directory)){
if ($countsearchterms == 1)
{
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos($file, ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 2) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if (((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false)) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 3) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if (((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 4) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if (((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&&
(strpos("$file", "$search[3]") !== false)) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 5) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if (((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)
&& (strpos("$file", "$search[4]") !== false)) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 6) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if (((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)
&& (strpos("$file", "$search[4]") !== false) && (strpos("$file", "$search[5]") !== false)) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
else if ($countsearchterms == 7) {
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$file= str_replace("-", " ", $file);
$file= str_replace("_", " ", $file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if (((strpos("$file", "$search[0]") !== false) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)
&& (strpos("$file", "$search[4]") !== false) && (strpos("$file", "$search[5]") !== false) && (strpos("$file", "$search[6]") !== false)) && ($fileextension == "pdf"))
{
$file= ucwords($file);
$array[] += "$file";
echo "<a href='http://www.learningaboutelectronics.com/$directory" . "$fileoriginal'>$file"."<br>";
}
}
}
closedir($open);
}
}//while loop
$arraycount= count($array);
if ($arraycount == 0)
{
echo "No results for this search entered";
}
}
}
?>
So this, you can see, is the longer block of PHP code. Still, it isn't hard.
First, we specify which directory we want to search that is on our website.
I've searching the Datasheets directory, so I set the $directory variable equal to 'Datasheets/'
If you want to add multiple directories, copy and paste all of this code and change the directory information. That way, you can add all the directories you want searched on your
website.
So once we've specified the directory, we then go to the heart of code. We first check to see if the submit button has been clicked. If it has, the code advances to the next line.
We have a second if that that checks to see if a search query has been entered. If it has and the search query isn't empty (a null string), the code advances to the next line. The next line is a third if statement. The line checks to see if the directory is actually a directory. If it is, the code advances to the line. The line opens up that directory.
We then have another if statement. If the number of terms in the search query is just one single word, the while loop is executed. The while loop loops through the files in that directory.
Because we're going to modify the file name, we created a $fileoriginal variable that holds the file intact. This is important because we'll need when we're outputting the link to the file.
We then make the $file lowercase. By making the search query lowercase in previous and making the $file lowercase now, we have equal cases. Therefore, we don't have to worry about cases matching. All are lowercase, so they're at equal plane.
Since most files are separated by "-" or "_", we use the PHP str_replace() function to replace these symbols with spaces. This make the link more human readable than if it had all these symbols.
Next, we have to eliminate the ending of the filename, such .html, .php, etc. This is not needed when we want to view the results returned from the search. Again, this makes the results returned more human readable. We don't care whether the results returned are html or PHP pages.
So we go about doing this by finding the position of the ".". Once we know its position, we know that what's after the "." is the file extension (.html or .php, etc).
So first we create a variable named $fileextension. We use the PHP substr() function to obtain the file extension of the file.
We then use the PHP substr() function to take the portion of the file that isn't the extension. We store this in the $file variable.
So now we just have the file name without the file extension.
Next, we have if an if statement. We use the strpos() function in PHP that if the search term is in the file name and the file extension is a pdf document, that result is going to be returned. If the search query is in the file name and the file extension is pdf, this if statement returns true. If so, it advances.
We then use the PHP ucwords() function to capitalize each word in the string. It again is done to make the results returned more human readable and better visually.
Now we create an array that stores if any files are returned that match that query. The reason we do this is because later on, if no results are returned from the search query entered, we then count this array. If it is equal to 0, no files have been returned that match the search query, which means we can output a statement, "No results found for this search query".
We then use the PHP echo () function to output the links to the pages found that match the search query. Whether it's 1 result or 50 results, all are returned that match the search query.
Next we have an if statement if the search query has 2 terms, meaning the user has entered 2 words into the search box. All the code is the same except for the last if statement
in that block of code. Now since there are 2 search words, the if statement is composed of 2 strpos() functions. If the file name has both terms in it, then it is returned in the results.
This search engine covers the user entering up to 7 words in the search box. For search, that usually is sufficient. However, if you want to make it more just copy and paste
more blocks of code and just change the value of $countsearchterms and up to $search[number] value. I would say the maximum would be 10. I don't think a user is going to type in 30 words into a search engine.
After that, we close the directory.
We then count the $array.
If the $array is equal to 0, then no search results have been returned. So we output the statement, "No results have been found for this search".
And this concludes all the code needed to create a search engine for your website.
Again, no database involvement. No MySQL. Just straight PHP code directly to directories on your website.
Related Resources How to Create a Search Engine Using PHPHow to Create Your Own Search Engine For Your Website Using PHPHow to Create an Image Search Engine For Your Website Using PHPHow to Create a Video Search Engine For Your Website Using PHPHow to Create an Audio File Search Engine For Your Website Using PHP
Create an Image Search Engine For Your Website
In this article, we show how to build your own search engine for your website using just PHP that exclusively returns only images. So it's a search engine that only returns images back in its search results.
This search engine we are going to build doesn't require MySQL in conjunction with PHP. It just requires PHP alone.
You can see the search engine shown above.
This search engine shown above searches this whole site.
This website has a pretty good, extensive list of articles on electronics. So if you type in 'transistor', 'resistor',
'capacitor', 'power', 'circuit', you'll get back a ton of results.
This search engine outputs the images that are found based on the search.
It lists every image on my website that matches all of the words in the search query.
If you try it out above, you'll see this.
It's very simple and it doesn't require any vast enormous databases such as using a MySQL database and having multiple tables to search. It's just PHP.
So how does this work?
So, as you probably know if you run a website, you upload files to your website through a file transfer protocol (FTP).
These files can be placed in any directory on your website. This can be the home directory (/), the Articles directory (Articles/), the images
directory (images/), or whatever else directory you created and named. You're more than likely familiar with this if you run a website.
Files are uploaded to directories (or folders) on your website.
So you have files in either one directory or various directories.
Using PHP, you can access any directory on your website.
Being that PHP is a server side language, it can access backend things such as a website's directories.
So once we gain to a directory on your website with PHP, we can search the entire directory. We create a search text box such as what you see above and then we extract the query entered and see if any files in that directory match the query. If it does, we output the image itself using the HTML <image> tag.
And that's as simple as it is.
We either can search one directory or multiple directories on your website.
A user enters a search query.
If the search query matches anything in the files of the directory (or directories) being searched, we can output the image. As many images that match the query get outputted.
So it's very simple.
The only thing is that your files must have appropriate names. For example, if you have a file on dandelion flowers. It will have that in the file name, for example, how-to-feed-dandelion-flowers.html or how-to-grow-dandelion-flowers.php or just dandelion-flowers.html. It has to have the name in the filename. If you have an article on dandelion flowers and it's named 123wxp.html, this search engine won't work. It's based on the fact that it looks at the file name. The file name should have the keywords that the user is searching for.
So now that you get an idea of how it works, we're now going over all the code needed to get
this up and running on your website.
If you just want the code, the full code of this image search engine is at the following link:
Code to create an image search engine.
Remember that you have to change the directory to the directory you have images on your site. Usually this will be the same directory.
Also when you copy this code to your web page, make sure it's saved as a PHP file.
HTML Code
So now we'll first go over the HTML code needed for this search engine.
The HTML code is needed just to create the search text box.
Everything else is PHP.
<form action="" method="POST">
Enter Search Query:
<input type="text" name="search_entered" value=''/>
<input type="submit" name="submit" value="Search"/>
</form>
So the above code creates the search box.
First, we create an HTML form. We set the action equal to "" because we want the information to this page. If we wanted the information sent to another page, we want specify this file within this action attribute. We set the method equal to POST.
As almost all forms require, we add a submit and give it the value, "Search". Thus, Search is displayed on the button.
We also add PHP code so that if the submit button is clicked and the search text box is empty, the statement "A search query must be entered" is output.
We then close the form.
This concludes the HTML code needed to make this search engine.
PHP CodeFirst Block of PHP Code
We now go on to the PHP code necessary to make this search engine work.
We separate the PHP code into 2 blocks of code.
The first block of PHP code is shown below.
<?php
$search= $_POST['search_entered'];
$searchoriginal= $search;
$search= strtolower($search);
$search= trim($search);
$search= explode(" ", $search);
$countsearchterms= count($search);
$submitbutton= $_POST['submit'];
?>
This PHP extracts the search query that the user enters into the search text box.
We then a $searchoriginal variable so that the search term that the user has entered is kept intact. We later will be doing many modifications to the search query that the user has entered.
We then make all the characters of the search query that the user has entered lowercase. This is because case matters in PHP. By making all the characters lowercase, we don't have to worry about case sensitivity.
We then use the PHP $trim function to cut off any space in front of the search query or the back of the search query (or left of the query or right of the query).
Next, we explode the $search variable. The explode() function in PHP separates a string based on a certain parameter. Here, we want the $search variable explosed based on any space characters (" "). The reason we want to do this is because the user may type in more than one word into the search engine. For example, the user may type in
"transistor circuit". If we forget about exploding the term and we just accept the search query directly, only terms that have the direct phrase, "transistor circuit" will be returned. If a
image is named, How-to-connect-a-transistor-to-a-circuit, this image will not be returned because the term "transistor circuit" isn't consecutive to the string. The terms in the name are separated.
So we'll miss this search. Only a term that has "transistor circuit" with the terms exactly "transistor circuit" will be returned.If these 2 terms are separated in the name, this search will be skipped. To avoid this, we explode the term and then look at each term separately. If the name of the file has both terms, it will be returned in the search results. Another example of this is a user typing in, "pepperoni pizza". Without exploding the term, only results that have the phrase "pepperoni beef pizza" in that exact order will returned. An image that is named, "Adding pepperoni
and beef to pizza" will not be returned because the phrase "pepperoni beef pizza" isn't in it, even though all the terms are in it. So you can see why we wouldn't want to just use the phrase exactly that the user inputs.
So after we explode the search query based on spaces, we then count the number of terms in the $search variable. Again, the explode() function separates the string into separate entities based on the parameter entered, in this case a space (" "). We now count the number terms in the $search variable. This is how we know how many terms the user has entered in.
Lastly, we make sure that we obtain the value of the submit button to see if it has been clicked. If it has been clicked, it returns true. If not, it returns false.
Second Block of PHP Code
This is now the second and last block of PHP code shown below.
<?php
$directory = "images/";
if ($submitbutton){
if (!empty($searchoriginal))
{
if (is_dir($directory)){
if ($open = opendir($directory)){
if ($countsearchterms == 1)
{
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
if ((strpos("$file", "$search[0]") !== false) && (($fileextension == "jpg") || ($fileextension == "jpeg") || ($fileextension == "png") || ($fileextension == "bmp")))
{
$array[] += "$file";
echo "<img style='width: 200px;' src='/images/$fileoriginal'>". "
";
}
}
}
closedir($open);
}
}//while loop
$arraycount= count($array);
if ($arraycount == 0)
{
echo "No results for this search entered";
}
}
}
?>
So this, you can see, is the longer block of PHP code. Still, it isn't hard.
First, we specify which directory we want to search that is on our website.
Since we are creating an images search engine, the directory we are searching through is the images directory.
Still, if you want to add multiple directories, copy and paste all of this code and change the directory information.
That way, you can add all the directories you want searched on your
website.
So once we've specified the directory, we then go to the heart of code. We first check to see if the submit button has been clicked. If it has, the code advances to the next line.
We have a second if statement that checks to see if a search query has been entered. If it has and the search query isn't empty (a null string), the code advances to the next line. The next line is a third if statement. The line checks to see if the directory is actually a directory. If it is, the code advances to the line. The line opens up that directory.
We then have another if statement. If the number of terms in the search query is just one single word, the while loop is executed. The while loop loops through the files in that directory.
We then create a variable named $fileorignal and we assign it to the value of $file. We do this because we're going to manipulate the $file string. It needs to be intact in order for us to output. Therefore, we need the original before manipulation, in order for the file name to be correct when using the image tag.
We then make the $file lowercase. By making the search query lowercase in previous and making the $file lowercase now, we have equal cases. Therefore, we don't have to worry about cases matching. All are lowercase, so they're at equal plane.
So we go about doing this by finding the position of the ".". Once we know its position, we know that what's after the "." is the file extension.
So we then use the PHP substr() function to take the portion of the string after the ".". This is the file extension. We save this in the variable $fileextension
Next, we have if an if statement. We use the strpos() function that if the search term is in the file name and if the file is a .jpg, .jpeg, .png., or .bmp, that result is going to be returned. If the search query is in the file name and the file is an jpg, jpeg, png, or bmp, this if statement returns true. If so, it advances.
Now we create an array that stores any files are returned that match that query. The reason we do this is because later on, if no results are returned from the search query entered, we then count this array. If it is equal to 0, no files have been returned that match the search query, which means we can output a statement, "No results found for this search query".
We then use the PHP echo () function to output the images found that match the search query. Whether it's 1 result or 50 results, all are returned that match the search query. We set the image tag to a decent width of 200px. The reason we do this because some of the images are huge. They can take up a whole page. To prevent, we set the image to a width of 200. We don't set the height because if you set and width of an image, you may get distortion. You can only set one of them, or else you'll get distorted images. After the image set we create 2 spaces and a horizontal line to separate each image from each other. And it just looks better presentation wise.
Next we have an if statement if the search query has 2 terms, meaning the user has entered 2 words into the search box. All the code is the same except for the last if statement
in that block of code. Now since there are 2 search words, the if statement is composed of 2 strpos() functions. If the file name has both terms in it, then it is returned in the results.
This search engine covers the user entering up to 7 words in the search box. For search, that usually is sufficient. However, if you want to make it more just copy and paste
more blocks of code and just change the value of $countsearchterms and up to $search[number] value. I would say the maximum would be 10. I don't think a user is going to type in 30 words into a search engine.
After that, we close the directory.
We then count the $array.
If the $array is equal to 0, then no search results have been returned. So we output the statement, "No results have been found for this search".
And this concludes all the code needed to create an image search engine for your website.
Again, no database involvement. No MySQL. Just straight PHP code directly to directories on your website.
Related Resources How to Create a Search Engine Using PHPHow to Create Your Own Search Engine For Your Website Using PHPHow to Create a Custom Search Engine For Your Website Using PHPHow to Create a Video Search Engine For Your Website Using PHPHow to Create an Audio File Search Engine For Your Website Using PHP
Create a Video Search Engine For Your Website
In this article, we show how to build your own search engine for your website using just PHP that returns exclusively videos. So it's a video search engine.
This search engine we are going to build doesn't require MySQL in conjunction with PHP. It just requires PHP alone.
You can see the search engine shown above.
This search engine shown above searches this whole site.
This website has a pretty good, extensive list of videos on electronics. So if you type in 'transistor', 'op amp',
'circuit', 'power', 'circuit', you'll get back results.
This search engine outputs videos that are found based on the search.
It lists every video on this website that matches all of the words in the search query.
If you try it out above, you'll see this.
It's very simple and it doesn't require any vast enormous databases such as using a MySQL database and having multiple tables to search. It's just PHP.
So how does this work?
So, as you probably know if you run a website, you upload files to your website through a file transfer protocol (FTP).
These files can be placed in any directory on your website. This can be the home directory (/), the Articles directory (Articles/), the images
directory (images/), or whatever else directory you created and named. You're more than likely familiar with this if you run a website.
Files are uploaded to directories (or folders) on your website.
So you have files in either one directory or various directories.
Using PHP, you can access any directory on your website.
Being that PHP is a server side language, it can access backend things such as a website's directories.
So once we gain to a directory on your website with PHP, we can search the entire dirctory. We create a search text box such as what you see above and then we extract the query entered and see if any files in that directory match the query. If it does, we output the image itself using the HTML <image> tag.
And that's as simple as it is.
We either can search one directory or multiple directories on your website.
A user enters a search query.
If the search query matches anything in the files of the directory (or directories) being searched, we can output the image. As many images that match the query get outputted.
So it's very simple.
The only thing is that your files must have appropriate names. For example, if you have a file on dandelion flowers. It will have that in the file name, for example, how-to-feed-dandelion-flowers.html or how-to-grow-dandelion-flowers.php or just dandelion-flowers.html. It has to have the name in the filename. If you have an article on dandelion flowers and it's named 123wxp.html, this search engine won't work. It's based on the fact that it looks at the file name. The file name should have the keywords that the user is searching for.
So now that you get an idea of how it works, we're now going over all the code needed to get
this up and running on your website.
If you just want the code, the full code of this video search engine is at the following link:
Code to create a video search engine.
Remember that you have to change the directory to the directory you have videos on your site.Usually this will be the same directory.
Also when you copy this code to your web page, make sure it's saved as a PHP file. Also if your videos directory is located in the root or home directory, this page should be uploaded
to the home directory.
HTML Code
So now we'll first go over the HTML code needed for this search engine.
The HTML code is needed just to create the search text box.
Everything else is PHP.
<form action="" method="POST">
Enter Search Query:
<input type="text" name="search_entered" value=''/>
<input type="submit" name="submit" value="Search"/>
</form>
So the above code creates the search box.
First, we create an HTML form. We set the action equal to "" because we want the information to this page. If we wanted the information sent to another page, we want specify this file within this action attribute. We set the method equal to POST.
As almost all forms require, we add a submit and give it the value, "Search". Thus, Search is displayed on the button.
We also add PHP code so that if the submit button is clicked and the search text box is empty, the statement "A search query must be entered" is output.
We then close the form.
This concludes the HTML code needed to make this search engine.
PHP CodeFirst Block of PHP Code
We now go on to the PHP code necessary to make this search engine work.
We separate the PHP code into 2 blocks of code.
The first block of PHP code is shown below.
<?php
$search= $_POST['search_entered'];
$searchoriginal= $search;
$search= strtolower($search);
$search= trim($search);
$search= explode(" ", $search);
$countsearchterms= count($search);
$submitbutton= $_POST['submit'];
?>
This PHP extracts the search query that the user enters into the search text box.
We then a $searchoriginal variable so that the search term that the user has entered is kept intact. We later will be doing many modifications to the search query that the user has entered.
We then make all the characters of the search query that the user has entered lowercase. This is because case matters in PHP. By making all the characters lowercase, we don't have to worry about case sensitivity.
We then use the PHP $trim function to cut off any space in front of the search query or the back of the search query (or left of the query or right of the query).
Next, we explode the $search variable. The explode() function in PHP separates a string based on a certain parameter. Here, we want the $search variable explosed based on any space characters (" "). The reason we want to do this is because the user may type in more than one word into the search engine. For example, the user may type in
"transistor circuit". If we forget about exploding the term and we just accept the search query directly, only terms that have the direct phrase, "transistor circuit" will be returned. If a
video is named, How-to-connect-a-transistor-to-a-circuit, this video will not be returned because the term "transistor circuit" isn't consecutive to the string. The terms in the name are separated.
So we'll miss this search. Only a term that has "transistor circuit" with the terms exactly "transistor circuit" will be returned.If these 2 terms are separated in the name, this search will be skipped. To avoid this, we explode the term and then look at each term separately. If the name of the file has both terms, it will be returned in the search results. Another example of this is a user typing in, "pepperoni pizza". Without exploding the term, only results that have the phrase "pepperoni beef pizza" in that exact order will returned. A video that is named, "Adding pepperoni
and beef to pizza" will not be returned because the phrase "pepperoni beef pizza" isn't in it, even though all the terms are in it. So you can see why we wouldn't want to just use the phrase exactly that the user inputs.
So after we explode the search query based on spaces, we then count the number of terms in the $search variable. Again, the explode() function separates the string into separate entities based on the parameter entered, in this case a space (" "). We now count the number terms in the $search variable. This is how we know how many terms the user has entered in.
Lastly, we make sure that we obtain the value of the submit button to see if it has been clicked. If it has been clicked, it returns true. If not, it returns false.
Second Block of PHP Code
This is now the second and last block of PHP code shown below.
<?php
$directory = "Videos/";
if ($submitbutton){
if (!empty($searchoriginal))
{
if (is_dir($directory)){
if ($open = opendir($directory)){
if ($countsearchterms == 1)
{
while (($file = readdir($open)) !== false){
$fileoriginal= $file;
$file= strtolower($file);
$position= strpos("$file", ".");
$fileextension= substr($file, $position + 1);
$fileextension= strtolower($fileextension);
$file= substr($file, 0, $position);
if ((strpos("$file", "$search[0]") !== false) && (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm")))
{
$file= ucwords($file);
$array[] += "$file";
echo "$file";
echo "<video style='width: 320px;' controls>