php examples

Must Watch!



MustWatch



Create a Global Variable

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

How to Retrieve Data from a Check box with PHP How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a List Box with PHP How to Retrieve Data from a Textarea with PHP How to Create a Confirmation Page for an HTML Web Form Using PHP How to Redirect to Another URL with PHP How to Create a Search Engine Using PHP How to Upload Images to a Website Using PHP How to Upload Files to a Website Using PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using 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 Method POST 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:
CharacterDescription
YA four-digit year such as 2012
yA two-digit year such as 12
mDisplays the month with leading zeroes (01)(for january)
dDispalys the day with leading zeroes (09)(for the 9th of the month)
Formatting the Date Year-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 PHP How to Upload Files to a Website Using PHP How 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 PHP Difference between the POST and GET Method in PHP How to Create a Line Break in PHP How to Format and Display the Date in PHP How to Generate a Random Number in PHP How to Find and Replace Text in PHP How to Remove Whitespace from a String in PHP How to Capitalize the First Word of a String in PHP How to Capitalize Each Word of a String in PHP PHP print_r() function PHP foreach loop How to Check if a Variable is Empty In PHP How 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, 10 PHP 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'); Examples Integer 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; Examples Integer 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 PHP How 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

Robert Smith
ghi@gmail.com
Michigan
Missouri And this is all that is required to access elements of a multidimensional array. Related Resources How to Loop Through a Multidimensional Array in PHP

Loop Through a Multidimensional Array

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

# 3
name: Robert Smith
email: ghi@gmail.com
city: Michigan
state: Missouri Related Resources How to Access the Elements of a Multidimensional Array in PHP

Sort a Multidimensional Array

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 PHP How to Access the Elements of a Multidimensional Array in PHP How 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 Method POST 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. Coding HTML 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

How to Retrieve Data from a Check box with PHP How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a List Box with PHP How to Retrieve Data from a Textarea with PHP

Retrieve Data from a Radio Button

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. Coding HTML 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

How to Retrieve Data from a Check box with PHP How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a List Box with PHP How to Retrieve Data from a Textarea with PHP

Retrieve Data from a Check box

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> Coding HTML 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

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a List Box with PHP How to Retrieve Data from a Textarea with PHP

Retrieve Data from an Array of Checkboxes

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

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from a Check box with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a List Box with PHP How to Retrieve Data from a Textarea with PHP How to Create a Confirmation Page for an HTML Web Form Using PHP

How to Redirect to Another URL with PHP

How to Create a Search Engine Using PHP

How to Upload Images to a Website Using PHP

How to Upload Files to a Website Using PHP

How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP

Retrieve Data from a Drop-down List

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> Coding HTML 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

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from a Check box with PHP How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a List Box with PHP How to Retrieve Data from a Textarea with PHP

Retrieve Data from a List Box

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

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from a Check box with PHP How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a Textarea with PHP

Retrieve Data From a Textarea

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. Coding HTML 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

How to Retrieve Data from a Radio Button with PHP

How to Retrieve Data from a Check box with PHP How to Retrieve Data from an Array of Checkboxes with PHP How to Retrieve Data from a Drop-down List with PHP How to Retrieve Data from a List Box with PHP

Perform Number Validation

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? Coding HTML 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 PHP How to Upload Files to a Website Using PHP How to Create a Search Engine Using PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Confirmation Page for an HTML Web Form Using PHP How to Insert Images into a MySQL Database Using PHP
How to Create a Searchable Database Using MySQL and PHP

How to Create a Register and Login Page Using PHP

Validate an Email Address

<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 PHP How to Upload Images to a Website Using PHP How to Upload Files to a Website Using PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How 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 PHP How to Insert Images into a MySQL Database Using PHP
How to Create a Searchable Database Using MySQL and PHP

How to Search a MySQL Table For Any Word or Phrase Using PHP

Create a Search Engine

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 PHP How to Create a Custom Search Engine For Your Website Using PHP How to Create an Image Search Engine For Your Website Using PHP How to Create a video Search Engine For Your Website Using PHP How to Create an Audio File Search Engine For Your Website Using PHP How to Upload Images to a Website Using PHP How to Upload Files to a Website Using PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Confirmation Page for an HTML Web Form Using PHP How to Insert Images into a MySQL Database Using PHP
How to Create a Searchable Database Using MySQL and PHP

How to Search a MySQL Table For Any Word or Phrase Using PHP

How to Create a Register and Login Page Using 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 Code First 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 PHP How to Create a Custom Search Engine For Your Website Using PHP How to Create an Image Search Engine For Your Website Using PHP How to Create a Video Search Engine For Your Website Using PHP How 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 Code First 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 PHP How to Create Your Own Search Engine For Your Website Using PHP How to Create an Image Search Engine For Your Website Using PHP How to Create a Video Search Engine For Your Website Using PHP How 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 Code First 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'>". "


"; } } } else if ($countsearchterms == 2) { 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) && (strpos("$file", "$search[1]") !== false)) && (($fileextension == "jpg") || ($fileextension == "jpeg") || ($fileextension == "png") || ($fileextension == "bmp"))) { $array[] += "$file"; echo "<img style='width: 200px;' src='/images/$fileoriginal'>". "


"; } } } else if ($countsearchterms == 3) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)) && (($fileextension == "jpg") || ($fileextension == "jpeg") || ($fileextension == "png") || ($fileextension == "bmp"))) { $array[] += "$file"; echo "<img style='width: 200px;' src='/images/$fileoriginal'>". "


"; } } } else if ($countsearchterms == 4) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false)) && (($fileextension == "jpg") || ($fileextension == "jpeg") || ($fileextension == "png") || ($fileextension == "bmp"))) { $array[] += "$file"; echo "<img style='width: 200px;' src='/images/$fileoriginal'>". "


"; } } } else if ($countsearchterms == 5) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)&& (strpos("$file", "$search[3]") !== false) && (strpos("$file", "$search[4]") !== false)) && (($fileextension == "jpg") || ($fileextension == "jpeg") || ($fileextension == "png") || ($fileextension == "bmp"))) { $array[] += "$file"; echo "<img style='width: 200px;' src='/images/$fileoriginal'>". "


"; } } } else if ($countsearchterms == 6) { 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) && (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 == "jpg") || ($fileextension == "jpeg") || ($fileextension == "png") || ($fileextension == "bmp"))) { $array[] += "$file"; echo "<img style='width: 200px;' src='/images/$fileoriginal'>". "


"; } } } else if ($countsearchterms == 7) { 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) && (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 == "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 PHP How to Create Your Own Search Engine For Your Website Using PHP How to Create a Custom Search Engine For Your Website Using PHP How to Create a Video Search Engine For Your Website Using PHP How 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 Code First 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> Your browser does not support the video tag.


"; } } } else if ($countsearchterms == 2) { 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) && (strpos("$file", "$search[1]") !== false)) && (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<video style='width: 320px;' controls> Your browser does not support the video tag.


"; } } } else if ($countsearchterms == 3) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)) && (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<video style='width: 320px;' controls> Your browser does not support the video tag.


"; } } } else if ($countsearchterms == 4) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false) && (strpos("$file", "$search[3]") !== false)) && (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<video style='width: 320px;' controls> Your browser does not support the video tag.


"; } } } else if ($countsearchterms == 5) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false) && (strpos("$file", "$search[3]") !== false) && (strpos("$file", "$search[4]") !== false)) && (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<video style='width: 320px;' controls> Your browser does not support the video tag.


"; } } } else if ($countsearchterms == 6) { 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) && (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 == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<video style='width: 320px;' controls> Your browser does not support the video tag.


"; } } } else if ($countsearchterms == 7) { 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) && (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[5]") !== false)) && (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<video style='width: 320px;' controls> Your browser does not support the video tag.


"; } } } 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 a videos search engine, the directory we are searching through is the Videos directory. That's the directory I created for this website that stores the videos on the website. 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 video 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 .mp4, .ogg, or .webm, that result is going to be returned. If the search query is in the file name and the file is an mp4, ogg, or webm file, this if statement returns true. If so, it advances. The reasons these 3 files are chosen is because these are the only 3 file formats that are supported by the HTML <video> tag. We later use the HTML video tag to display and play the video. So the file formats of the videos we upload must be compatible with the HTML video tag, or else the videos won't work. 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 videos 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 video tag to a width of 320px. The reason we do this because in this day in age, different devices are used to access the internet. Mobile phones can have screen sizes with widths as small as 320px. To be able to fit into the smallest mobile screen, the width should be set to accommodate the smallest screen and, thus, all devices. We specify 'controls' in the video tag to give the video control buttons. With controls, the user can have access to a play/pause button. The user can adjust the volume of the video, whether it be full screen for the device the user is using, etc. Controls is normally used, because you want the user options for navigating through videos. Without controls, the user can't adjust anything. Next, we specify the video file through the source src attribute. If the video directory is placed in the home directory, the path specified in the code will work. Next, we specify the type attribute, which is the file format of the video. We obtained the file format or extension of the video in previous code and placed in the $fileextension variable. We now use that $fileextension variable to specify the type of video it is within the HTML video tag. We output in between the video tags, "Your browswer does not support the video tag". This will output only if the browser being used by the user doesn't support the HTML video tag. Otherwise, this statement won't be shown. It's done for convenience for the user. In case, the user's browser can't play, it's good for the user to know that it's because of the browser being used. So now the user knows why the video isn't being displayed. We then close the video tag. After the video, we create 2 spaces and a horizontal line to separate each video from each other. 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 a video 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 PHP How to Create Your Own Search Engine For Your Website Using PHP How to Create a Custom Search Engine For Your Website Using PHP How to Create an Image Search Engine For Your Website Using PHP How to Create an Audio File Search Engine For Your Website Using PHP How to Insert Videos Into a MySQL Database Using PHP How to Upload Videos to a Website Using PHP

Create an Audio File 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 audio files. So it's an audio file 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. So far this website has very few audio files. As of right now, it only has files, 'Hello-hola' and 'January-enero'. So only if you type in one of these terms will you get a search result returned. This search engine outputs audio (sound) files that are found based on the search. It lists every audio file 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 sound file itself using the HTML <audio> 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 output the audio file. 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.mp3 or just dandelion-flowers.mp3. It has to have the name in the filename. If you have a sound file on dandelion flowers and it's named 123wxp.mp3, 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 audio file search engine is at the following link: Code to create an audio file search engine. Remember that you have to change the directory to the directory you have audio files on your site. Also when you copy this code to your web page, make sure it's saved as a PHP file. Also if your sound files 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 Code First 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 an audio file is named, How-to-connect-a-transistor-to-a-circuit, this audio file will not be returned because the term "transistor circuit" isn't in consecutive order in 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 audio file 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 = "Audio/"; 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 == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } else if ($countsearchterms == 2) { 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) && (strpos("$file", "$search[1]") !== false)) && ($fileextension == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } else if ($countsearchterms == 3) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false)) && ($fileextension == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } else if ($countsearchterms == 4) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false) && (strpos("$file", "$search[3]") !== false)) && ($fileextension == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } else if ($countsearchterms == 5) { 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) && (strpos("$file", "$search[1]") !== false) && (strpos("$file", "$search[2]") !== false) && (strpos("$file", "$search[3]") !== false) && (strpos("$file", "$search[4]") !== false)) && ($fileextension == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } else if ($countsearchterms == 6) { 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) && (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 == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } else if ($countsearchterms == 7) { 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) && (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[5]") !== false)) && ($fileextension == "mp3")) { $file= ucwords($file); $array[] += "$file"; echo "$file

"; echo "<audio controls> Your browser does not support the audio tag.


"; } } } 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 audio files search engine, the directory we are searching through is the Audio directory. That's the directory I created for this website that stores the audio files on the website. 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 HTML audio 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 .mp3, that result is going to be returned. If the search query is in the file name and the file is an mp3 file, this if statement returns true. If so, it advances. The reasons this mp3 file is chosen is because it is the only file format that is supported by the HTML <audio> tag that works with all the major browsers. To have the audio file display across all the major browsers, we make sure the file format uploaded is an mp3 file. We later use the HTML audio tag to display and play the sound file. So the file format of the audio files we upload must be compatible with the HTML audio tag, or else the sound files won't play. Next we create an array that stores any files are returned that match the query entered. 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 sound files found that match the search query. Whether it's 1 result or 50 results, all are returned that match the search query. We specify 'controls' in the audio tag to give the sound file control buttons. With controls, the user can have access to a play/pause button. The user can also adjust the volume of the sound file, Controls is normally used, because you want to give the user options when working with the sound files. Without controls, the user can't adjust anything. Next, we specify the audio file through the source src attribute. If this file is placed in the home directory and the Audio directory is in the home directory, the path specified in the code will work. Next, we specify the type attribute, which is the file format of the audio file. We obtained the file format or extension of the sound file in previous code and placed in the $fileextension variable. We now use that $fileextension variable to specify the type of audio file it is within the HTML audio tag. We output in between the audio tags, "Your browswer does not support the audio tag". This will output only if the browser being used by the user doesn't support the HTML audio tag. Otherwise, this statement won't be shown. It's done for convenience for the user. In case, the user's browser can't play, it's good for the user to know that it's because of the browser being used. So now the user knows why the sound file isn't being displayed. We then close the audio tag. After the audio tag, we create 2 spaces and a horizontal line to separate each sound file from each other. 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 audio file 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 PHP How to Create Your Own Search Engine For Your Website Using PHP How to Create a Custom Search Engine For Your Website Using PHP How to Create an Image Search Engine For Your Website Using PHP How to Create a Video Search Engine For Your Website Using PHP

Create a Register and Login Page

In this article, we show how to build a register and login page using PHP. A register page or form can be used for your website to register users in the event that your website takes in users. Maybe your website uses members and you want to sign up members. Or maybe your site doesn't have members. You want to just take down information from users, for maybe like an email list so that you can send them email. However, most of the time, it's probably for members. It may not be for any type of social platform. Maybe you just want people on your site to have accounts, so that maybe they could upload documents or projects they've done. For, example, this site doesn't have members (forum doesn't count). It doesn't sign up members so that a member has his/her own account. But if it did, it could be used for something like a member trying to share his/her own electronic product or possibly code. So a register and login system can be used for something like that. Register Page So before we have a login page, we need to first register users. We need to first get users in the database so that they are officially registered. How we do this is we create a database through MySQL. And then once we have this database, we use a register form where a user can type in information, such as his/her first name, last name, username and password. Once the user clicks the form submit button, this information is then sent and stored in the MySQL database. So what's the code to go about the create a register form? Code for Register Page We will show and explain the code needed to create the register page below. You can also see it in the following text file at the following link: Code for Register Page. PHP Code The first block of code needed to make this form work is the PHP code. <?php $user = "user"; //Enter the user name $password = "password"; //Enter the password $host = "host"; //Enter the host $dbase = "database"; //Enter the database $table = "table"; //Enter the table name $submitbutton= $_POST['submit']; $firstname= $_POST['firstname_entered']; $lastname= $_POST['lastname_entered']; $username= $_POST['username_entered']; $password1= $_POST['password_entered']; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $username_table= mysql_query( "SELECT username FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error()); $count= mysql_num_rows($username_table); if ((!empty($firstname)) && (!empty($lastname)) && (!empty($username)) && (!empty($password1))) { if ($count == 0) { mysql_query("INSERT INTO $table (firstname, lastname, username, password) VALUES ('$firstname', '$lastname', '$username', '$password1')"); $check= 1; } } mysql_close($connection); ?> So with this PHP code shown above, we create a connection to the MySQL database that will hold the user data from the register form. This MySQL table has 5 fields: ID, first name, last name, username, and password. To connect to the database, we need a host name, user name, password, database name, and the name of the table which will hold the user data. I created this table using phpMyAdmin. The ID column is of type "int" and is set to auto-increment. The first name column is of type "varchar" and is given a value of 50. The last name column is of type "varchar" and is given a value of 50. The username column is of type "varchar" and is given a value of 50. The password column is of type "varchar" and is given a value of 50. An image of the structure of this table can be seen at the following link: Table for User Registration and Login. Once we have all of this set up, we retrieve data from the HTML form whose code is shown below. This is done through the superglobal $_POST array. From the HTML form, we obtain the first name, last name, username, and password entered in by the user. We also obtain data from the submit button see whether it has been clicked or not. We then connect to the database using the mysql_select_db function. We then query the database to find out whether the username that the user has entered. We store this in the variable $username_table. We then create a variable named $count and count how many rows exist based on this query. The reason we do this is if the $count variable is equal to 0, this means that the username has not been taken, so this user can use that user. If the $count variable is not equal to 0, this means that it is taken and this user cannot take it (since it's already been taken). The next block of code has an if statement. If any of the variables, $firstname, $lastname, $username, and $password1 are empty, then nothing that the user entered into the register form will be transferred to the MySQL table. If the fields are not empty (the user has entered into all of them), then there is one more if statement. If the $count is equal to 0, then we insert the data that the user has entered into the form into the MySQL database table. Remember the $count variable holds whether the username is taken or not. If it is 0, this means the username that the user has entered is not taken and thus can be used. If it is not 0, the username is taken; thus we cannot add it to the table (this would create duplicate usernames which of course is forbidden). The last line simply closes the database connection. Since we've already inserted the data from the HTML form into the MySQL table (if the username wasn't taken and the form fields were all entered), we can close the connection to the database and its table. This is all the PHP code needed to create the register form. HTML Code The HTML code for the register form is shown below. <form action="" method="POST"> First name: <input type="text" name="firstname_entered" value=''/> Last name: <input type="text" name="lastname_entered" value=''/> Select a Username: <input type="text" name="username_entered" value=''/> Choose a Password: <input type="password" name="password_entered" value=''/> <input type="submit" name="submit" value="Register"/> </form> So the above code creates the form needed in which the user will input data. In this form, we create 4 text boxes. The text boxes asks for the user's first name, last name, username, and password. All the text boxes are of type "text" except the password textbox. The password text box takes on the type "password", so that the characters entered into it are encrypted. Otherwise, it is just like the other text boxes. For each of the text boxes, the text box cannot be left blank; else, the form will output, "This field cannot be left empty". How we do this is through 2 if statements for each text box. The first if statement checks the variable $submitbutton. This variable holds whether the submit button of the form has been clicked. If the submit button has been clicked, it will be true. If the submit button has not been clicked, it's false. If the submit button has been clicked and the field is empty, then the statement, "This field cannot be left empty" will be output. For the username text box, there is an additional if statement. If the submit button has been clicked and the $count variable is not equal to 0, this means this username has already been taken (since it's already present in the database. Lastly, we have the submit button. We name this button "submit". This completes the form. This completes all of the code needed to create the register page. Login Page Next we need the login page. Code for Login Page So now we go over the code for the login page. This code is shown below. We also show this code in the following text file at the following link: Code for Login Page. <form action="login-confirmation-page.php" method="POST"> Username: <input type="text" name="username_entered"/> Password:<input type="password" name="password_entered"/> <input type="submit" name="submit" value="Log in"/> </form> The code for the login page is very simple. It is simply an HTML form. The form contains the fields, Username and Passworld. These are the only fields required for a user to log in. The form, as only forms require, needs a submit button. Once clicked, the form redirects the user to the PHP page, login-confirmation-page.php using the POST method. Again, this is all that is required for the login page. Login Confirmation Page The last page is the login confirmation page. This is the page the user gets brought to after s/he has logged in. Once you use the login page, you'll be brought to the confirmation page. Code for the Login Confirmation Page The code needed for the login confirmation page, which is entirely PHP code, is shown below. We also show it here in the following text file at the following link: Code for Login Confirmation Page. <?php $user = "user"; //Enter the user name $password = "password"; //Enter the password $host = "host"; //Enter the host $dbase = "database"; //Enter the database $table = "table"; //Enter the table name $username= $_POST['username_entered']; $password1= $_POST['password_entered']; $submitbutton= $_POST['submit']; // Connection to DBase mysql_connect($host,$user,$password); @mysql_select_db($dbase) or die("Unable to select database"); //stores username $username_table= mysql_query( "SELECT username FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error()); //ATTENTION-Code ends here $firstname_table= mysql_query( "SELECT firstname FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error()); //ATTENTION-Code ends here $lastname_table= mysql_query( "SELECT lastname FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error()); //ATTENTION-Code ends here //stores password to username $password_table= mysql_query( "SELECT password FROM $table WHERE username= '$username'" ) or die("SELECT Error: ".mysql_error()); while ($row = mysql_fetch_array($username_table)){ $username1= $row['username']; } while ($row = mysql_fetch_array($password_table)){ $password2= $row['password']; } while ($row = mysql_fetch_array($firstname_table)){ $firstname= $row['firstname']; } while ($row = mysql_fetch_array($lastname_table)){ $lastname= $row['lastname']; } $count= mysql_num_rows($username_table); if ($count == 0) { echo "Sorry, login was not successful. The username entered does not exist. Please go back to the login page to try again."; } else if (($count == 1) && ($password1 !== $password2)) { echo "Sorry, login was not successful. The password entered was incorrect. Please go back to the login page to try again."; } else if (($count == 1) && ($password1 == $password2)) { echo ucwords("<h2>Hi $firstname
"); echo ucwords("$firstname $lastname"); echo ", you have been successfully logged into your account"; } ?> So, again, we create our connection to the MySQL database table. We then take the login information from the login form that the user entered in through the superglobal $_POST array. These are the $username, $password1, and $submitbutton variables. We make the connection to the database. We then query the table of the database to see whether the username that the user has entered exists or not. We also store the values of the first name, last name, and password of that username (assuming it exists). We then use an if statement. If the $count variable is 0, this means that the username that the user entered does not exist. So we echo the statement, "Sorry, login was not successful. The username entered does not exist" We then redirect the user back to the login page to retry. If the $count variable is equal to 1 and the password entered doesn't match the password in the database, we echo the statement, "Sorry, login was not successful. The password entered was incorrect." We, again, redirect the user back to the login page to retry. If the $count variable is equal to 1 and the password entered matches the password in the database, we echo "Hi" and the user's name. The ucwords() function capitalizes the user's name in the event that the user entered his/her name in lowercase. We also echo to the user, "you have been successfully logged into your account". And this is all that is required to make a simple register and login page using PHP. Of course, there are many variations that can be done to this register and login page. For example, in the register form, we can new form fields such as get the user's gender, date of birth, any other information, etc. However, the more simple and invasive a form field, the more a user will trust it. However, you can add how many information fields you want. It's also based on what type of site you're running. Depending on what site you run determines what information you may need a user to reveal. Besides the form fields, we can make it so that the user can have a password reset option in the login form. We will reveal the modifications needed to create a password reset option, so that if the user forgets his password, he can reset it. This isn't hard. We simply have to create another page where the user types in his username. We then create a connection to the table of the MySQL database and rewrite the current password in the password field. There are many variations. However, this form can be used as a fundamental root of what is necessary to create a register and login page using PHP. Using only PHP, we can create a pretty decent register and login form using PHP. It's decent but it isn't as good as if you had jquery code involved. This is because we must submit the form in order to find out whether a username is taken. Modern up-to-date companies allow you to tell whether a username is taken without a user having to click the submit button of a form. This is more efficient. However, again, for a basic register and login page for your site, the code above runs very well. Also, this page shows just how to create a register and login page. One more element that needs to be added and considered is the session_start() function in PHP. For example, once a user logs on into his account, once he will switches to another page on the site, you still want him to be logged on. Therefore, once a user logs on, we have to start a session, so that he remains logged on while maneuvering through the site. To see a full tutorial on session, see How to Use Sessions to Track User Data Using PHP. This will show you how once a user has registered in, how we can keep the user logged in even while the user visits different pages on the site. You don't want the user's session to end after the register page. You want to user to remain logged in until the user logs off. To do this, you need to start a session once the user has logged in. This keeps the user's log in session lasting even while the user visits other pages on the site. Related Resources How to Upload Images to a Website Using PHP How to Upload Files to a Website Using PHP How to Create a Search Engine Using PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Confirmation Page for an HTML Web Form Using PHP How to Insert Images into a MySQL Database Using PHP
How to Create a Searchable Database Using MySQL and PHP
How to Search a MySQL Table For Any Word or Phrase Using PHP
How to Create a Send Email Form Using PHP and MySQL How to Create a Newsletter from Scratch using PHP and MySQL

Use Sessions to Track User Data

In this article, we show how to use sessions to track user data using PHP. This is actually a powerful concept because sessions data can stored on the web server. Therefore, if a user clicks and goes to another page, the server still has the information about the user. Many sites use this concept of sessions. Pretty much any site that has a login system where a user logs in will use sessions. Once a user is logged in, a session is begun. If the user goes to another page or even gets off the site to another and comes back, their data is still available, so they can pick up right where they left off. Shopping sites use this all the time. You log into your account and no matter what page you go to on the site, you're still logged into your account and the website knows who you are. So how do sessions work and how can we implement them on a website with PHP? Form To Track You Through Sessions <form action="userpage.php" method="POST"> Enter Your First Name <input type="text" name="name_entered"/> <input type="submit" name="submit" value="Submit"/> </form> Before we go get into the code for this tutorial, enter your first name into the text box above. This form will illustrate sessions for you. You will see how you go from page to page, yet each page knows your first name. This is done through sessions. We will now go over how to do this below in code. HTML Code So let's say just like above we have an HTML form that gets data from a user, such as above with a text box asking for the user's first name. The HTML code for this is shown below. <form action="userpage.php" method="POST"> Enter Your First Name <input type="text" name="name_entered"/> <input type="submit" name="submit" value="Submit"/> </form> The <form></form> tags create an HTML form. We set the action attribute of the form to userpage.php. This is because this is the PHP page we want to transfer the user to when the user clicks on the Submit button. The method is set to POST because we're posting it to the actual page, not the URL, which is what the GET method does. We then have a standard HTML text box that asks for the user's name. This is followed by a submit button, which allows a form to be submitted. PHP Code So now we go to the first PHP code that is used once the user submits the form. The contents of the PHP file, userpage.php, is shown below. <?php session_start(); $name= $_POST['name_entered']; $_SESSION['name']= $name; echo "Hi " . $_SESSION['name']; ?> So the first thing that we do is call the function, session_start(). Session_start() is one of the crucial of sessions. Without it, sessions could not work. In order for you to start a session that is able to track a user or user data, you must start a session. This is what the session_start() function does. This code must exist before any other code on a page, or else it will not work. Therefore, when you use the session_start() function, do not include any other code before this of any kind, including HTML code. You will get the error, "Headers already sent". You must put this first in your code. If you still get the error, "Headers already sent" and you are not including any white space or code of any kind before the session_start() function, then save your PHP file with the ANSI encoding. More than likely, your PHP file is saved either with Unicode, Unicode Big Endian, or UTF-8 encoding. These type of encodings add invisible characters before that causes PHP to throw errors. So after this session_start function, we retrieve the data that the user entered into the form. Since the name of the HTML text box was name_entered, we use the superglobal array $_POST to retrieve the data entered into the this text box; we assign the value of this data to the variable $name. The next line of code is very important. We create a sessions variable called name that is set equal to what the user has entered into the text box. This way, $_SESSION['name'], is equal to the name that the user has entered. This is how we will track the user or the user's data from page to page. Because session variables are saved on the server, even if a user goes to another page, this sessions variable is still stored. Therefore, we can track users from page to page to page. This, again, is how many sites that have users logged in allow a user to see they are still logged in even when going from different page to different page. So on this userpage.php file, we transfer the user to another page to show that we can track the user (the user's data) through session variables. This page is anotheruserpage.php, which we show the contents of below. <?php session_start(); echo "I still know you are ". $_SESSION['name']. " even though this is another completely separate page"; ?> The biggest thing to note about this page is it has another session_start() function. In fact, every page that tracks a user through sessions must have the session_start() function at the top of the PHP code. The session_start() function is used for when a session is first begun and to continue a current session for a user. It might seem a little weird to have a session called session_start when you're continuing an already started session, but look at it like this, it starts a session for each page, so that the session is continued on other pages. That's the way I see it, at least. So, again, for each page that tracks user data through sessions, there must be a session_start() function on that page. So if you have a very interactive site where you want a user to be logged in no matter what page they are visiting on your website, that means you will have a session_start function on every page on your website. So after this session_start() function, we output a statement that we still know who the user is even though this is another completely separate page. And we know this because of the session variable, $_SESSION['name'], that we created. Once a session variable is created, which we did on the userpage.php file, and we use the session_start() function on each page after that, the server still has the value stored in this session variable. So if we call it, it still has the value. So whatever you entered into the HTML form is still contained even after now 2 PHP files. After this page, we demonstrate one last page tracking the user data through sessions. Why not? The page we transfer the user to now is lastuserpage.php. The contents of the lastuserpage.php file is shown below. <?php session_start(); echo $_SESSION['name']. ", this is just one last page to show you the session data transfers over."; ?> So, again, as explained, we must include the session_start() function. This is needed on every PHP page that you want to track session data, either to create a session or maintain a current session. We output the user's name (stored in the $_SESSION['name'] variable) and say this is just one last page to show you the session data transfers over. And this is really all that is required of the basics of working with sessions. If you want to end a session, a session normally ends when a user closes the browser or even sometimes when a user goes to a website. But if you want to definitively end a session with PHP, then you can use the session_destroy() function. This terminates a user's session so that the user is no longer being tracked. In this article, we just showed one example of a session variable but you can store as many session variables as you want. In our form, we just tracked the user's first name. However, we can track one of hundreds of variables if we want, including last name, email address, phone number, etc. We can track anything. This can be data that is entered into an HTML form, such as you did. Or you can have a user log in on a site and have data from past history such as the long form that have to complete when they're initial registering on the site or their shopping history based on past purchases. You may have this data stored in a database and then pull it from the database and store it in session variables for the duration of the session. So there's many dynamic ways of doing it but sessions is a powerful programming concept to learn and many sites use it to track users from page to page. Related Resources How to Create a New Directory Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

Check if Cookies are Enabled

In this article, we show how to check if cookies are enabled or disabled using PHP. Cookies are data that is stored by a user's web browser. This can be data such as the information that a user enters into a form such as the user's name, email, telephone number, etc. PHP has the functionality to work with cookies. For example, you can write code that could send a cookie that contains the user's name. The cookie could then be stored on the user's computer and the next time he visits the site, teh cookie would be sent to your program, which could then result in a personalized greeting. The first step, however, is to find out whether cookies are enabled and you can do this using PHP. How do we do this? The simplest way is probably to just create a cookie with PHP and check to see whether the cookie gets created. If it does and we're able to read it, then cookies are enabled with the broswer. If not, then cookies are disabled. The PHP code below checks to see whether or not cookies are enabled. <?php setcookie('testcookie', "hello"); if (isset($_COOKIE['testcookie'])) { echo "Cookies are enabled"; } else { echo "Cookies are not enabled"; } ?> So we use the PHP setcookie() function to create a cookie called testcookie and we give it the value of Peter. This is simply for testing. We then check to see if the testcookie cookie has been set. If it has, cookies are enabled. If it hasn't, cookies are disabled. Even PHP has good functionality for cookies, cookies are can present with bad data. Cookies need to be sanitized first before you can turst it. For instance, once your program sends a cookie to a visitor's browser, the visitor can edit or change that cookie to be anything he wants. This is why cookies aren't that secure. Sessions are more secure in that they are stored over the server and aren't accessible like cookies. However, cookies still have their uses and if you aren't worried about security can work similarly to sessions. So this is just real quick code to check whether or not cookies are enabled. Related Resources How to Create a New Directory Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

List All the Directories of a Website

In this article, we show how to list all directories of a website using PHP. How this is done is not that simple. It depends on the amount of subdirectories you have. For example, every directory has a home or root directory. This directory almost always contains other directories, which are subdirectories of this home directory. If you just want to show all of the directories in this home directory, the PHP code to do is. <?php $directory = "."; if ($opendirectory = opendir($directory)){ while (($file = readdir($opendirectory)) !== false){ if (is_dir($file)) { echo "$file" . "<br>"; } } } ?> This PHP code above shows all the directories that are in the root directory (the subdirectories of the root directory). We'll now break down the code. So we set the $directory variable equal to ".". This makes the directory selected the home (or root directory) which is the first and chief directory of any website. We then use the PHP opendir() function to open up this home directory so that we have access to it. We then use a while loop to loop through all the files in the directory. If any files are directories, we then echo out this directory. How we know if any files are directories is through the PHP is_dir() function. This function checks to see if any files in the root directory are directories. So all is good with this code if you only have 1 set of subdirectories on your website. This may be an Articles (Articles/) directory, Documents (Documents/) directory, images (images/) directory. But now what if you have another set of subdirectories in these directories. For example, in the Articles directory, you may have an images directory. In the Documents directory, you may have a PDFs directory. And so on and so forth. So now we're dealing with 2 levels of subdirectories. How can use PHP code to now get every directory on the website? It's a little more complicated but the code to do this is shown below. <?php $dir = "."; // Sort in ascending order - this is default $a = scandir($dir); if ($opendirectory = opendir($dir)){ while (($file = readdir($opendirectory)) !== false){ if (is_dir($file)) { if ($opendirectory2 = opendir($file)){ while (($file3 = readdir($opendirectory2)) !== false){ if (is_dir($file3)){ if ($file !== ".") { echo "$file" . "/" ."$file3" . "<br>"; } } } } } } } ?> This code now shows all directories of the home directory, all the directories on the home directory, and all of the first set of subdirectories in the directories of the home directory. So now the code will show subdirectories in the directories on the home directory. For example, now it will show the images directory in the Articles directory (Articles/images/). It will show the PDFs directory in the Documents directory (Documents/PDFs/). This code goes another layer deep into the directories on a website. But if your website has even more subdirectories inside of directories, you just have to amend the code so it can keep showing more and more subdirectories that matches deep your site goes into it. Being that PHP has no explicit function to find all directories on your website, you have to build the code necessary to show these directories. So based on your site, you custom build the code based on the layers of subdirectories that you have. But unless your site is very complex, either one of these scripts should suffice.

List All Files of the Root Directory and its Subdirectories

In this article, we show how to list all files the root directory and all the directories on the root directory (its subdirectories) using PHP. Every website has a home or root directory. This directory almost always contains other directories, which are subdirectories of this root directory. What we want to do is be able to show all files in the root directory and all files in the subdirectories of the root directory. So this includes all files in the root directory as well as all subdirectories of the home directory. This may includes the Articles (Articles/) directory, Documents (Documents/) directory, images (images/) directory, and so on and so forth. It shows all files in all directories in the root directory. The code to show all files in the root directory and all files in the subdirectories using PHP is shown below. <?php $dir = "."; if ($opendirectory = opendir($dir)){ while (($file = readdir($opendirectory)) !== false){ if (is_dir($file)) //all files in root directory { if ($opendirectory2 = opendir($file)){ //opens up all files in subdirectories in root directory while (($file3 = readdir($opendirectory2)) !== false){ if(!(is_dir($file3))) { echo "$file3" . "<br>"; } } } } } } ?> So this PHP code above shows all the files in the root directory as well as all files in all directories in the root directory. We'll now break down the code. So we set the $directory variable equal to ".". This makes the directory selected the home (or root directory) which is the first and chief directory of any website. We then use the PHP opendir() function to open up this root directory so that we have access to it. We then use a while loop to loop through all the files in the directory. If any files are directories, the code advances. We then open up these directories again using the opendir() function. We loop all all files in each of these directories. If the files aren't directories, we echo out the file. And this is all that is required. This, again, returns all files in the root directory as well as all files in the every directory on the root directory. If you have subdirectories inside of subdirectories inside of subdirectories, this is a lot more complicated and difficult to achieve. It's obviously definitely achieveable. But this code that I wrote about covers the case of returning all files in the root directory and each subdirectory of the root directory.

Read Contents of a File

In this article, we show how to read contents of an existing file that you have in a directory on a server. Say, you have an existing file already in a directory on your server and you want to read the contents of that file. Well, with PHP, you can read the contents of a file without having to go that file and open it up and read it. Since PHP is a server side language, it can access any file in a directory on your server and read the contents of it without you having to directly go to that file. Before I go over to the PHP code, look at the file below. This is the contents of the file, samplepage.txt. This website gives tutorials on electronics and programming. This website is written in HTML, PHP, and Javascript So you can see the contents of the file above. The statement "This website gives tutorials on electronics and programming. This website is written in HTML, PHP, and Javascript" is output. So you've read the contents of a file using PHP without having to manually go to the file and write it. So how is this done in PHP code? This is shown below. PHP Code The code to read the contents of a file using PHP is shown below. <?php $fileread= file_get_contents('file_name.txt'); echo "$fileread"; ?> So the code is extremely simply. All you have to do to read the contents of a file is to use the PHP file_get_contents() function. The only parameter that this function needs is the pathway and the filename. Since we are writing the contents of our file to the current directory (right now this article is published in the Articles directory of this website), this file named samplepage.txt is saved in the samplepage.txt file in the Articles directory. However, if we were writing to the subdirectory named 'files', for instance, inside the Articles directory, the first parameter would be 'files/samplepage.txt'. Then to be able to read the contents of the file, you have to output it. We do this through the well-known PHP echo() function. So this just shows you briefly how to read the contents of a file using the PHP file_get_contents() function. Related Resources How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP How to List All Files in a Directory using PHP

Write Contents to a File

In this article, we show how to write contents to an existing file that you have in a directory on a server. Say, you have an existing file already in a directory on your server and you want to write something to that file, such as a few lines. Well, with PHP, you can write contents to a file without having to go that file and open it up and write the content. Since PHP is a server side language, it can access any file in a directory on your server and write contents to it without you having to directly go to that file. Before I go over to the PHP code, look at the file below. This is the contents of the file, sample.txt. <fieldset> ththththth</fieldset> So you can see the contents of the file above. Write something to this Textarea to Write to the File Shown Above So above is an area where you can write contents. When you click the submit button, the contents that you wrote will be written to the file, sample.txt. If you wrote something and submitted it by clicking the submit button, you should see the contents above that show the file change to include this. You will have to refresh the page though after you submit the form to see the changes to the content of the file. So you've now written contents to a file using PHP without having to manually go to the file and write it. So how is this done in PHP code? This is shown below. PHP Code The code to write contents to a file using PHP is shown below. <?php $contents="Content that you want to write to file"; file_put_contents('file_name.txt', $contents); ?> Or if you just wanted to use a single line to write contents to a file, you could use the line shown below. <?php file_put_contents('file_name.txt', "Content that you want to write to file"); ?> So the code is very straightforward and simple. All you have to do to write contents to a file is to use the file_put_contents() function. The first parameter in this function specifies the pathway and the filename. And the second parameter specifies the string that you want to write to the file. Since we are writing the contents of our file to the current directory (right now this article is published in the Articles directory of this website), this file named sample.txt is saved in the sample.txt file in the Articles directory. However, if we were writing to the subdirectory named 'files', for instance, inside the Articles directory, the first parameter would be 'files/sample.txt'. The second parameter is simply the string that you want to write. Be aware, though, that the file_put_contents() function in PHP erases everything currently in the file and overwrites it with the content that you specify. Therefore, be careful. If you don't want to erase all the contents that you have in a file, this is not the function to use. It totally erases everything and replaces just with the text that you write to it. Therefore, make sure this is what you want when using this PHP function. You can see this above when using the textarea form. Anyways, this just shows you briefly how to write contents to a file using the PHP file_put_contents() function. Related Resources How to Read the Contents of a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP How to List All Files in a Directory using PHP

Copy a File

In this article, we show how to copy a file using PHP. Copying files may be necessary for many reasons. Copying a file means that you take a complete file and make a copy of it. The new file is then called a different name. All the contents that are in the original file are copied to the copy of the original file. The names of the files must be different, however, the only thing that is different, because files cannot have the same exact name. So how is this done with PHP? PHP has a copy() function that allows us to make a copy a file. So the PHP code to make a copy of a file is shown below.

So the code above is very simple. It's a single line. The PHP copy() function takes in 2 parameters. The first parameter is the original file that we want to copy. In this parameter, we must specify the file name along with its file extension. Do not leave off the file extension, or else the function will not work. The second parameter represents the new copied file. Again, we must specify the file name along with its file extension. In the second parameter, you specify what you want the new copied file to be named. This new file contains all the contents in it that the original file has; the only difference is the file name is different.  So this is all that is needed to copy a file. Even though the code is above is very effective and does the job of copying a file, many times we would want to add more to it, so that we can get more information. For example, does the file we want to copy exist? If the file does exist, was it successfully copied? The PHP code below copies a file and gives us more information. <?php if (file_exists('originalfile.txt')) { $copied= copy('originalfile.txt', 'copiedfile.txt'); if ($copied) { echo "The file has been successfully copied"; } else { echo "The file has not been successfully copied"; } } else { echo "The original file that you want to copy doesn't exist"; } ?> This code now is more forthwise. It tells us more. We first see whether the file exists. If the file exists, the code advances to the next line. In this line, we create a variable named $copied. This variable holds the result of the PHP copy function. If the file has been copied successfully, the $copied variable will hold a 1 or TRUE value. If it hasn't, the $copied variable will hold a 0 or FALSE value. If the file has been copied successfully, the line "The file has been successfully copied" is output. If not, the line "The file has not been successfully copied" is output. If the file doesn't exist, the line "The original file that you want to copy doesn't exist" is output. So this code above tells us everything. It tells us whether the file we want to copy exists. And it tells us whether the file copy was successful or not. And this is all that is required to copy a file using PHP. s

Rename a File

In this article, we show how to rename a file using PHP. Renaming files may be necessary for many reasons. Files may require a name change. There may have been spelling errors in an existing file or files that you want to change. Your website may have changed; and, thus, this may require renaming files. Renaming a file means that you take an exisitng file and change the name to something other than it is. For example, you may change the file NY.txt to newyork.txt. So how is this done with PHP? PHP has a rename() function that allows us to make a rename a file. So the PHP code to rename a file is shown below.

So the code above is very simple. It's a single line. The PHP rename() function takes in 2 parameters. The first parameter is the original file that we want to rename. In this parameter, we must specify the file name along with its file extension. Do not leave off the file extension, or else the function will not work. The second parameter represents the new renamed file. Again, we must specify the file name along with its file extension. In the second parameter, you specify what you want the name of the renamed file. This renamed file contains all the contents in it that the original file has; the only difference is the file name is different. So this is all that is required to rename a file. Even though the code is above is very effective and does the job of renaming a file, many times we would want to add more to it, so that we can get more information. For example, does the file we want to rename exist? If the file does exist, was it successfully renamed? The PHP code below renames a file and gives us more information. <?php if (file_exists('originalfile.txt')) { $renamed= rename('originalfile.txt', 'copiedfile.txt'); if ($renamed) { echo "The file has been successfully renamed"; } else { echo "The file has not been successfully renamed"; } } else { echo "The original file that you want to rename doesn't exist"; } ?> This code now is more forthwise. It tells us more. We first see whether the file exists. If the file exists, the code advances to the next line. In this line, we create a variable named $renamed. This variable holds the result of the PHP rename function. If the file has been renamed successfully, the $renamed variable will hold a 1 or TRUE value. If it hasn't, the $renamed variable will hold a 0 or FALSE value. If the file has been renamed successfully, the line "The file has been successfully renamed" is output. If not, the line "The file has not been successfully renamed" is output. If the file doesn't exist, the line "The original file that you want to rename doesn't exist" is output. So this code above tells us everything. It tells us whether the file we want to rename exists. And it tells us whether the file rename was successful or not. And this is all that is required to rename a file using PHP. How to Rename All Files in a Directory with a Certain Criterion or Criteria The above code is great and works well. But the true beauty of this PHP rename() function, if you want to tap into the true beauty of it, is that it can rename all files in a directory matching a certain criterion. Say, you have a list of files that have the word, "MD" standing for Maryland, such as "flowers-in-MD", "gifts-to-buy-in-MD", "places-to-go-in-MD" and you've decided that you don't want to use the state abbreviation; instead you want to use the full state name, "Maryland". Imagine if you have 70 of these files. Imagine if you have hundreds. You would have to go through each of these files and manually rename them. This is the beauty of the PHP rename() function. With a single block of code, we can rename all of those files in less than a minute, instead of it taking hours or days with us manually doing it. So how do you loop through all the files in a directory and rename the files we want to? <?php $directory = "Articles/"; // Open a directory, and read its contents if (is_dir($directory)){ if ($opendirectory = opendir($directory)){ while (($file = readdir($opendirectory)) !== false){ if (strpos($file, "MD") !== false) { $file2= str_replace("MD", "Maryland", $file); rename($directory.$file, $directory.$file2); echo "$file has been renamed to $file2" . "<br>"; } } closedir($opendirectory); } } ?> So this code above searches the Articles directory. Of course you can set this to any direcory you want on your website. The PHP code checks to see if this is a directory. If so, it opens the directory. The while loop loops through all the files in the directory. We then write an if statement to see whether each file contains the phrase "MD". If it does, we then create another variable, $file2, which is the same string as the original file, except that 'MD' is replaced with 'Maryland' through the PHP str_replace() function. We then use the PHP rename() function to rename the original file to the now renamed filed. Lastly, we echo that the original file has now been renamed to the renamed file. This is the beauty of programming and the PHP rename() function. Related Resources How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Delete a File Using PHP How to List All Files in a Directory using PHP

Delete a File

In this article, we show how to delete a file using PHP. Deleting files may be necessary for many reasons. Deleting a file means that you completely erase it from a directory, so that the file no longer exists. So how is this done with PHP? PHP has a unlink() function that allows us to delete a file. So the PHP code to delete a file is shown below.

So the code above is very simple. It's a single line. The PHP delete() function takes in a single parameter. The parameter is the file that we want to delete. In this parameter, we must specify the file name along with its file extension. Do not leave off the file extension, or else the function will not work. So this is all that is required to delete a file. Even though the code is above is very effective and does the job of deleting a file, many times we would want to add more to it, so that we can get more information. For example, does the file we want to delete exist? If the file does exist, was it successfully deleted? The PHP code below deletes a file and gives us more information. <?php if (file_exists('file.txt')) { $deleted= unlink('file.txt'); if ($deleted) { echo "The file has been successfully deleted"; } else { echo "The file has not been successfully deleted"; } } else { echo "The original file that you want to delete doesn't exist"; } ?> This code now is more forthwise. It tells us more. We first see whether the file exists. If the file exists, the code advances to the next line. In this line, we create a variable named $deleted. This variable holds the result of the PHP unlink function. If the file has been deleted successfully, the $deleted variable will hold a 1 or TRUE value. If it hasn't, the $deleted variable will hold a 0 or FALSE value. If the file has been deleted successfully, the line "The file has been successfully deleted" is output. If not, the line "The file has not been successfully deleted" is output. If the file doesn't exist, the line "The original file that you want to delete doesn't exist" is output. So this code above tells us everything. It tells us whether the file we want to delete exists. And it tells us whether the file delete was successful or not. And this is all that is required to delete a file using PHP. How to Delete All Files in a Directory with a Certain Criterion or Criteria The above code is great and works well. But the true beauty of this PHP delete() function, if you want to tap into the true beauty of it, is that it can delete all files in a directory matching a certain criterion or certain criteria. Say, you have a list of files that have the word, "HTML4", such as "How-to-create-a-horizontal-line-using-HTML4", "How-to-create-a-paragraph-using-HTML4", and "How-to-create-an-anchor-tag-using-HTML4" and you've updated yourself to all HTML5 and you've decided you want to delete all files with HTML4. Imagine if you have 70 of these files. Imagine if you have hundreds. You would have to go through each of these files and manually delete them. This is the beauty of the PHP unlink() function. With a single block of code, we can delete all of those files in less than a minute, instead of it taking hours or days with us manually doing it. So how do you loop through all the files in a directory and delete the files we want to? <?php $directory = "Articles/"; // Open a directory, and read its contents if (is_dir($directory)){ if ($opendirectory = opendir($directory)){ while (($file = readdir($opendirectory)) !== false){ if (strpos($file, "HTML4") !== false) { unlink($directory.$file); } } closedir($opendirectory); } } ?> So this code above searches the Articles directory. Of course you can set this to any direcory you want on your website. The PHP code checks to see if this is a directory. If so, it opens the directory. The while loop loops through all the files in the directory. We then write an if statement to see whether each file contains the phrase "HTML4". If it does, we delete the file through the PHP unlink() function. This is the beauty of programming and the PHP delete() function. Related Resources How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to List All Files in a Directory using PHP

Create a New File

In this article, we will show how to create a new file on your website using PHP. This means you can create new pages on the fly, dynamically, with PHP. This can be a new text file, HTML file, PHP file, etc. This means you don't have to manually go to a FTP and upload a new file. You can use the PHP language to create a new file. PHP is a powerful server-side scripting language. It can do many powerful things, one of them being creating new files on a website, backend work. Creating new files using PHP can be very important. For example, say if you want to create a new page based on some input that a user has entered. Or say you're creating a website that acts as a notepad on the cloud where users can save files. This can be accomplished with PHP> So how do we go about creating new files with PHP? And we create new files with PHP through the fopen() function. This is the same PHP function that is used to open an existing file. However, if the file does not exist, PHP will create the file. So this is how PHP can be used to create a new file. So below we show the code. Code The code to create a new file called newfile.php is shown below. <?php fopen("newfile.php", "w") or die("Unable to open file!"); ?> This fopen() function is very simple. It takes 2 parameters. The first parameter is the name of the file that you want to create And the second parameter is the accessibility you want to provide to this file. If we want to be able to write to this file, then we have to give it write permissions ("w"). If we simply want to read from this file, then we give it read permissions ("r"). So the following code above create a file named newfile.php and the file is completely blank, because we haven't written anything to it. Below, though, we'll show how to write to files. <?php $myfile = fopen("newfile.php", "w") or die("Unable to open file!"); $txt = "I love PHP."; fwrite($myfile, $txt); fclose($myfile); ?> So this code above creates a new file called newfile.php and writes the text, "I love PHP", in the file. We can write text to a file using the fwrite() function. So this demonstrates how to write text to a new file you create with PHP. However, be careful, because rememmber the same PHP function fopen() that opens an existing file creates a new file if an existing file does not exist. Say if you use the fopen() function to create a new file. However, the file already exists, an important file. If you use the fwrite() function, you will erase all data in that existing file, unintentionally. To avoid this, you can use an if statement to find out if the file already exists. If it does, you probably don't want to overwrite it. So you can use the following code that if the file already exists that you are trying to create, the code will inform you of this. <?php if (!is_file($filename)) { $myfile = fopen("newfile.php", "w"); $txt = "New text goes here."; fwrite($myfile, $txt); fclose($myfile); } else { "This file name already exists"; } ?> Now with this code, we'll only create a new file if there is no existing file with that name. Therefore, we won't run the risk of overwriting potentially important data that we have. The last thing is the fopen() can specify not only a file name, such as what is shown above, but also a pathway. Say if we want to create a file in a directory other than the current directory. We can specify the pathway in the fopen() function. The example below will store the file in the Articles directory. <?php fopen("Articles/newfile.php", "w"); ?> So the new file we create, newfile.php, will be stored in the Articles directory if we upload it to the webroot directory. So this is how we specify relative paths to create new files in other directories other than the current directory. So if you upload this PHP file to the root directory, it creates the file, newfile.php, in the Articles directory. So the fopen() function takes either the filename (if creating in the directory this PHP file is uploaded to) or the pathway and the filename (if creating in another directory other than the current directory). And this is how to create a new file using PHP. Related Resources How to Create a New Directory Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

Create a New Directory

In this article, we will show how to create a new directory on your website using PHP. This means you don't have to manually go to a FTP and create the directory. You can use the PHP language to create the new directory for you. PHP is a powerful server-side scripting language. It can do many powerful things, one of them being creating directories on a website, backend work. Creating directories using PHP can be very important. For example, say if you have a website that has users. Say, users store photos and documents on the website. Many times you probably want all of the user's documents, including photos, in the user's own directory. So, for example, when a user initially signs up for your website, you may just PHP dynamically to create a directory for that user. Then when the user decides to upload photos, documents, etc., you can store all in that directory that was created. More than likely, that directory name will be the same as the username, being that the username always has to be unique. So this could be one of the ways how PHP can be used and why would it would be used to create directories. So how do we do this? How do we create a directory? And we create a directory through the PHP mkdir() function. This function is very simple. All you need to know is that it takes one parameter, which is the name of the directory that you want to create. So below we show the code. Code The code to create a directory called Pocahontas is shown below. <?php mkdir("Pocahontas"); ?> So the following code above creates a directory called Pocahontas. You can also specify relative directories. So if I upload PHP file above to the root directory, it creates the directory, Pocahontas, in the root directory. So this website is http://www.learningaboutelectronics.com/. So this directory will be created at http://www.learningaboutelectronics.com/Pocahontas Now you can also specify relative pathways. So if I wanted to create a directory Pocahontas in the Articles directory, I would specify the pathway. This is shown in the code below. <?php mkdir("Articles/Pocahontas"); ?> Now if you upload this PHP file to the root directory, it creates the directory, Pocahontas, in the Articles directory. So the mkdir() function takes either the filename (if creating the directory in the directory this PHP file is uploaded to) or the pathway and the filename (if creating the directory in another directory other than the current directory). The mkdir() function is pretty safe to use. What I mean by this is that, it will not create a new directory to a directory that already exists. So this function doesn't run the risk of overwriting an existing directory that you may have that contains important files. If you attempt to use the mkdir() function to create a directory that already exists, PHP will throw a warning error, stating the following, Warning: mkdir() [function.mkdir]: File exists. So there's one way of overwriting an important directory if a mistake or made or anything. However, if you want to create a PHP code that shows if a directory has been successfully created or if it hasn't been, you can use the following code shown below. if (!is_dir("MyNewDirectory")) { mkdir("MyNewDirectory")) } else { echo "This directory already exists"; } So this PHP code will output to you whether the directory has been successfully created or not, based on the fact if it's already taken. So PHP is very dynamic. It can create new directories on the fly. You don't have to do it manually. It can be important for a wide variety of reasons, when doing it manually is painful and unnecessary, like the example I gave. If you have a website that has users and they can upload files, you probably want to create a directory for each user at the time they become users or at least at the time they upload files. Then you can just store all their files in that one folder. So the mkdir() function is a great function, and this is how you can use it to create a new directory using PHP. Related Resources How to Create a File Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

Create a Web Crawler



In this article, we show how to create a very basic web crawler (also called web spider or spider bot) using PHP. A web crawler is a script that can crawl sites, looking for and indexing the hyperlinks of a website. It goes from page to page, indexing the pages of the hyperlinks of that site. Why are web crawlers important? Because they are able to find new hyperlinks and, thus, new pages of a website. They index the pages found and can store in a database. This is how search engines work. Google has web crawler, a spider bot, that is able to search the whole world wide web, find new pages, and index them, so that the pages can be found on the search engine. Google is constantly crawling the web, so that new pages, which are published to the world wide web constantly, can be found and listed. And it's not only search engines. There are plenty of other services that crawl the web for hyperlinks. Another example is a script that checks for broken links found on a website. One of the most prominent examples, and one I use myself, is http://brokenlinkcheck.com. This program crawls a website, looking for broken links, so that a website owner can fix the broken links, improving his/her site. So web crawlers are in full use on the internet and is a very valuable tool. So how do we go about creating one with PHP? This will be shown below. PHP Code All we need to create this spider web crawler is a single block of PHP code. This code is shown below. <<?php $website_to_crawl= "http://www.learningaboutelectronics.com"; $all_links= array(); function get_links($url) { global $all_links; $contents= @file_get_contents($url); $regexp= "]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; preg_match_all("/$regexp/siU", $contents, $matches); $path_of_url= parse_url($url, PHP_URL_HOST); if (strpos($website_to_crawl, "https://") == true) { $type= "https://"; } else { $type= "http://"; } $links_in_array= $matches[2]; foreach ($links_in_array as $link) { if (strpos($link, "#") !== false) { $link= substr($link,0, strpos($link, "#")); } if (substr($link, 0, 1) == ".") { $link= substr($link,1); } if (substr($link, 0, 7) == "http://") { $link= $link; } else if (substr($link, 0, 8) == "https://") { $link= $link; } else if (substr($link, 0, 2) == "//") { $link= substr($link,2); } else if (substr($link, 0, 1) == "#") { $link= $url; } else if (substr($link, 0, 7) == "mailto:") { $link= "[" . $link . "]"; } else if (substr($link, 0, 1) != "/") { $link= "$type" .$path_of_url. "/" . $link; } else { $link= "$type" .$path_of_url.$link; } if (!in_array($link,$all_links)) { array_push($all_links, $link); } }//ends foreach }//ends function get_links get_links($website_to_crawl); foreach ($all_links as $currentlink) { get_links($currentlink); } foreach ($all_links as $currentlink) { get_links($currentlink); } foreach ($all_links as $currentlink) { if ((strpos($currentlink, "www.learningaboutelectronics.com") !== FALSE) && (strpos($currentlink, "http", 4) == FALSE)) { echo $currentlink . "<br>"; $linkscount[] += $currentlink; } } $count= count($linkscount); echo "<br>
There are $count links found by the crawler"; ?> So above is the PHP code that we need to create our web crawler. This block of code is the only code needed to do so. So the first thing we put in our code is the website we want to crawl. This is placed in the $website_to_crawl variable. You would change the value of this variable to any website that you want to crawl. We then create an array called all_links. This array will store all the links that our crawler finds later in the code. We then create a function called get_links() that has the $url parameter. This function will get the links from each page that the website crawls. Each link that the crawler goes through gets assigned to the $url variable. Inside this get_links() function, we make the all_links array global. This is so that later in the code we can continue to use this all_links array even outside of this get_links() function. Outside of the function, we can continue to use the all_links array, so it's important to make it a global variable. We then create a variable named $contents. This variable gets the contents of each page (each link) that the crawler finds. This is very important because this is how we open up the links found to get the links that are in each link. That way, we can keep getting links from all the pages that are found. This line of code is critical. Without this line of code, this code would only be able to get links only on the page you specify in the website URL and not any other pages on the site. The next expression looks for hyperlinks on a page. In this code we look for hyperlinks based on the regular expression for a hyperlink. Without going into all that makes up this expression, this line is able to find all hyperlinks on a page based on how a hyperlink is marked up in HTML. The next link, using the preg_match_all() function looks to see if the regular expression we are looking for matches any on the page. If there is a match on any of the pages, this hyperlink is stored in the $matches array. We then create a variable called $path_of_url. We parse the URL to give us the path to the page on the website. We will use this for only specific instances in the code shown below. Next, we have a few if statements to find out whether the URL is an http or an https. If it is an http, we set the $type variable to "http". If it is an https, we set the $type variable is set to "https". We then create a variable, $links_in_array, which stores all the hyperlinks stored in the second portion matches array. The matches array holds much more than just the URLs we want to find. Only in the $matches[2] portion is just the hyperlinks. So we just create another variable and store just the $matches[2] portion, which is just the hyperlinks. We then loop through all the links, first, on the URL that we specified using the foreach loop. We go through each link of the specified URL. We use a series of if statements to correct links so that we either don't duplicate links in the final array of all the hyperlinks we find or to make sure we have the full name of the hyperlink. So the first if statement checks for hashtags ("#") found on a page. If a hyperlink contains a hashtag, we don't want to have the link with the hashtag. If you know HTML pretty well, you would know that if a link hashtag, it means that it is specifying a certain part of a webpage. So, for example, say we have the following links: http://earningaboutelectronics.com/Transistor#BJT and http://earningaboutelectronics.com/Transistor#FET. These 2 links both are referring to the same page. They are just referring to different parts of the page. Therefore, we don't want to index both of these pages, because they're the same page. We don't want duplicate entries in our final list of arrays. Therefore, if a link contains a hashtag we simply retain the portion that precedes the hashtag. We strip away all parts after the hashtag. Next we check if the hyperlink begins with a period or dot ("."). If it does, we want to take away this dot. In HTML, this means that the link is a relative link from the home directory of the website. For example, a website owner may specify the path of a link to be "./Articles/Transistors". What this means is that the website owner created a relative link from the home directory. We don't want relative links so we simply remove the period. Later on we'll append the http:// and the URL to this link, so that we obtain the full complete pathway to the hyperlink. Next we check if the link begins with "http://". If it does, the link remains the same. We then check if the link begins with "https://". If it does, the link remains the same. If the link begins with "//", we remove the "//". Later in the code, we'll append the "http://" and the URL to make a full absolute pathway to the link. If the link begins with "#", this means that it is referring a certain part of the current page, which is the URL you specified. Therefore, we just make the link equal to the $url variable. If the link is an email link (contains "mailto:"), we append a "[" and a "]" to the link. This is our signal so that later on, we can create an absolute pathway to this email function. If the link begins with "/", we specify the pathway by adding in the $path_of_url variable, which we created from the PHP parse_url() function. In all other cases, the $link variable is equal to the $path_of_url with the $link variable appended to it. We then have an if statement that if the hyperlink is not found in the $all_links array, we want to add it to all the all_links array. The all_links array is our array to store all the links that the web crawler finds. This get_links() function is going to run over and over and over all throughout the website. Websites typically have hyperlinks to the same page all over the website. We only want to index a certain page once in the all_links array. Thus, we want to check if the link is currently in the array. If it is, we don't want to index it again. If it isn't, we put in the array via the array_push() function. This ends the get_links() function. Right below this, we call (or invoke) the get_links () function. Remember, we created a function above. But to have the function run, you must call the function. This is what we do in the in this line. After this, we have a foreach loop. This loops through all links on the current page that the crawler is on. For each of these links, we run the get_links() function. So this means we get the links from each of the hyperlinks. This way, we can scan the whole site. We then have another foreach loop that goes through each of the links. We then echo out these links. I added an optional 2 lines of code so that I could see how many hyperlinks the web crawler indexed. And this concludes all the code needed to build our spider web crawler using PHP. I placed the above PHP code on my website. See the following link to see this PHP spider web crawler script crawl my website: Web Crawler on Learning about Electronics. You can see all the hyperlinks indexed and at the bottom it tells you the total count of hyperlinks indexed. If you want to make all the links hyperlinks, then instead of the line, echo $currentlink . "<br>";, you would instead put the line, echo "<a href=" . "\"" . "$currentlink" . "\"" . ">$currentlink</a>" . "<br>"; Related Resources How to Create a Confirmation Page for an HTML Web Form Using PHP How to Insert Images into a MySQL Database Using PHP
How to Create a Searchable Database Using MySQL and PHP

How to Search a MySQL Table For Any Word or Phrase Using PHP

How to Create a Send Email Form Using PHP and MySQL

Retrieve and Get the Contents of a Web Page

In this article, we show ways of how to retrieve a web page using PHP to get the contents of the web page. Being that PHP is a dynamic, server-side language, it can access other remote pages on the web at your request. It can fetch any URL so that you can get the contents of the page of that URL. This can be done in a few ways. file_get_contents() function The first way we can retrieve and get the contents of a page is through the file_get_contents() function. This takes the contents of the page specified in the parameter and gets the contents of it on the current page. The PHP code to do this is shown below. <?php $page= file_get_contents('http://www.ebay.com'); echo $page; ?> So this PHP code above retrieves the ebay.com home page and puts the full contents on the page. So it's almost as if your site has ebay's full page. This function is only supposed to do used to get the contents of a page so that you can see what's on the page and maybe scrape some of the information on the page, such as web scraping. Even though it appears like your site has actually transformed into ebay, it hasn't. You simply have the contents of ebay's home page on your site, not the functionality. If you try to use the search text box to look for an item on ebay, it won't work. Your site hasn't become ebay. It's simply loaded the contents of ebay's page onto your website. The file_get_content(), as the name implies, is simply to get the contents of a web page, mostly the text. The actual images, themselves will be missing the majority of the time, because that information is in the folder of any website, not on yours. However, you can still get the contents of an image, such as the image source and the alt tags, if you scrape for it. If you simply want to redirect to another site, you would use the PHP Location header redirect function. CURL Another way of retrieving and getting the contents of a page is through the CURL function. This achieves the same effect as above, with the file_get_contents() function. The PHP code to do this with CURL is shown below. <?php $c= curl_init('http://www.ebay.com'); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); $page= curl_exec($c); echo $page; curl_close($c); ?> This code achieves the same effect. It retrieves the URL inserted into it and gets the contents of that page. So these are 2 ways we can retrieve and get the contents of a URL using PHP. Related Resources How to Insert Images into a MySQL Database Using PHP How to Insert Files into a MySQL Database Using PHP How to Create a Confirmation Page for an HTML Web Form Using PHP

How to Redirect to Another URL with PHP

How to Create a Search Engine Using PHP

How to Upload Images to a Website Using PHP

How to Upload Files to a Website Using PHP

How to Create a Searchable Database Using MySQL and PHP

How to Search a MySQL Table For Any Word or Phrase Using PHP

How to Create a Send Email Form Using PHP and MySQL

How to Create a Newsletter from Scratch using PHP and MySQL

How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP

Connecting to and Using an FTP

In this article, we show how to connect to and use a file transfer protocol (FTP) with PHP. Being a server side language, PHP can connect to remote servers such as FTP servers to allow for transferring of files. PHP has an ftp_connect function which allows for connection to an FTP server. In order for the connection to be successful, the address that you put in the parameter of the ftp_connect() function has to be an FTP server. You can't just put in your website hosting name or IP address and expect it to work. This PHP function only works if the address is an FTP server. That's the first thing. The next PHP function ftp_login allows you to log into the FTP server (assuming it was able to connect to the server). You need a username and password to get access into the FTP server. Otherwise, you won't be able to transfer files or do anything. So, again, you need to connect to an actual FTP server and you connect to it via the ftp_connect() function. Next, you need a username and password to gain access into the FTP server and this is done via the PHP ftp_login function. We show how to do these in the code below. PHP Code The PHP code to connect to an FTP server and log into the FTP server is shown below. <?php $connect= ftp_connect("ftp.godaddy.com") or die ("Connection to server unsuccessful"); $user= "username"; $password= "password"; $login= ftp_login($connect, $user, $password) or die ("Login was unsuccessful"); ?> So now we'll go over the code. So, first, we create a variable named $connect and make it equal ftp_connect("ftp.godaddy.com") or die("Connection to server unsuccessful"); If the statement executes, this variable holds the value of true. If not, the statement, "Connnection to server unsuccessful" is shown. If unsuccessful, the die() function terminates the script and what it has in it will print. The ftp_connect function, besides, having the hosting name of the website as its parameter can store the IP address of the website instead. So, for example, the line can be, ftp_connect(" If it has been successful, the script will continue on. We have 2 variables, $username and $password. They store the username and password to log in to the FTP server. We then create a variable $login that is set equal to ftp_login() function which has 3 parameters. $connect is the past parameter which gave connected to the server. $user is the username. $password is the password. If nothing prints in this script and you get a blank page, you have successfully logged in. If the login is unsuccessful, the die() function is called and the statement, "Login was unsuccessful" is output. So this is all that is required to connect to and log into an FTP server. PHP then has a number of function so that we can interact and do useful things with the FTP servers such as create, delete, rename, copy, get a listing of, and transfer files, as an FTP does. Getting a Directory Listing One way to get a directory listing with PHP is through the ftp_nlist() function. The ftp_nlist() function gets a directory listing from the remote computer and stores it in an array. The ftp_nlist() function takes 2 parameters. The first parameter establishes connection, via the $connection variable we previously used. And the second parameter is where we specify the name of the directory we want to get the listing of. the full PHP code is shown below. $filesdirectory= ftp_nlist($connect, "directory_name"); foreach ($filesdirectory as $file) { echo "$file "; } So this code prints all the files in the directory you specified. Downloading Files with an FTP Files can be downloaded with an FTP from the remote computer with the ftp_get() function. The following code can be used below to download a file from the computer once you've logged into the FTP server. ftp_get($connection, "file_name.txt", "file_downloaded.txt", FTP_ASCII); So the ftp_get() function takes 4 parameters. The first parameter uses the previously used $connection variable to establish connection. The second parameter, "file_name.txt", is the name of the file that you will have on your computer once the file is downloaded. This is what you want to name the file. the third parameter, "file_downloaded.txt", is the name of the file on the server that you want to download. The FTP_ASCII parameter tells the FTP what kind of file is being downloaded. It can either be text files (FTP_ASCII) or machine language files (FTP_BINARY), which is basically anything that isn't plain text. You can determine which one you need by the contents of the file.If the contents are regular characters that are human readable, that you can read and understand, it is an ASCII file. IF the contents are all machine code, ones and zeros, the file is binary. Graphic files, for example, are binary. Uploading Files with an FTP Files can be uploaded with an FTP to the remote computer with the ftp_put() function. The following code can be used below to upload a file to the computer once you've logged into the FTP server. ftp_put ($connect, "file_name.txt", "file_uploaded.txt", FTP_ASCII); So the ftp_put() function takes 4 parameters. The first parameter uses the previously used $connection variable to establish connection. The second parameter, "file_name.txt", is the name of the file that you have on your computer that you want to upload. the third parameter, "file_downloaded.txt", is the name that you want the file to be once it is uploaded to the server. The FTP_ASCII parameter, again, specifies the file is an ASCII file. Once you've finished transferring files over your FTP connection, you can close the connection with the following statement shown belo. ftp_close($connection); This closes the FTP connection. Below is a table of more PHP FTP functions that are commonly used.
Function What It Does
ftp_cdup($connection) Changes to the directory directly above the current directory
ftp_chdir($connection, "directoryname") Changes directories on the remote computer
ftp_delete($connection, "path/filename") Deletes a file on the remote computer
ftp_exec($connection, "command") Executes a system command on the remote computer.
ftp_mdtm($connection, "filename.txt") Gets hte time when the file was last modified.
ftp_mkdir($connection, "directoryname") Creates a new directory on the remote computer.
ftp_pwd($connection) Gets the name of the current directory on the remote computer.
ftp_rename($connection, "oldname", "newname") Reames a file on the remote computer
ftp_rmdir($connection, "directoryname") Deletes a directory on the remote computer.
ftp_size($connection, "filename.txt") Returns the size of the file on the remote computer.
ftp_systype($connection) Returns the system type of the remote file server (for example, Unix)
Related Resources How to Create a New Directory Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

Find Out if a Page is Secure

In this article, we go over how to find out if a page is secure using PHP. PHP has a $_SERVER['HTTPS'] call that you can use to find out whether a given page is secure or not. The full PHP code to find out if a page is secure or not is shown below. <?php if (isset($_SERVER['HTTPS'])) { echo "This page is secure."; } else { echo "This page is not secure."; } ?> If the $_SERVER['HTTPS'] superglobal variable is set, then the page is secure. If it not set, then the page is not secure. This could be a very important variable, because many websites need have to secure connections for their vistors or customers. Many websites deal with customer-sensitive information such as passwords, credit cards, debit cards, social security numbers, and other important information. Insecure pages, or regular pages, are easier for hackers to intercept on the web to retrieve information. Thus, sites that deal with customer-sensitive information are better dealt with over a secure connection. Secure websites are websites that have pages that begin with https://. https means that the page is secure; it's being handled over a secure connection. Insecure pages, or regular pages, begin with http://. http means that the page is not being handled over a secure connection. This PHP superglobal variable can be used to find out if a page is secure. And based on that, you can do anything, such as decide to take in customer-sensitive information or redirect a user to a secure page on the website (rather than the insecure page). So many things can be dealt with based on this superglobal variable. Once you know whether a page is secure or not, you can write code that takes any actions based on what you feel is appropriate for your website. Even if all the links on your website are coded so that they give the absolute pathway and they all contain https, even this doesn't make your website secure. This is because the user can still go to the URL bar on the web browser and type in http:// and the full pathway to a page and get the regular page. To prevent this, you can have a script on each page that will redirect a user from a regular page to a secure page, so that a user can never submit information over a regular page. A user, without advanced web knowledge, may simply not know that http is insecure and accidently type http instead of the intended https where you would like him or her to be. So, either way, this can all be prevented by placing a PHP script to redirect a user from a regular page to a secure page. To see how to redirect a user from a regular page to a secure page, see How to Redirect a User to a Secure Connection Using PHP. Actual PHP Output This page is not secure. Related Resources How to Create a New Directory Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

Redirect a User to a Secure Connection

In this article, we go over how to redirect a user to a secure connection using PHP. If you have a secure website, your website exists as regular pages (http) and secure pages (https). Regular pages begin with http. So, for example, a regular page may be http://www.example.com/hello.html. This page is not secure, and provides no encryption of user data such as of passwords or credit cards or other sensitive user information. Secure pages begin with https. So, for example, a secure page may be https://www.example.hello.html. This page is secure, and provides encryption of sensitive user data. If your site inherently exists as https and you've coded all of your links with absolute links that include https, this does not guarantee that your site is secure at all pages. This is because if a user goes to the URL bar and types in the absolute URL containing http instead of https, he or she can be guided to a regular page instead of a secure page. To prevent this from happening, you can include a PHP script at the top of every page that automatically performs a redirect from a regular page (http) to a secure page (https). The PHP code to perform an automatic redirect from a regular page (http) to a secure page (https) is shown below. &?php if (!isset($_SERVER['HTTPS'])) { $url= 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; header("Location: $url"); } ?> So the code above checks to see if the current page is a secure page by checking the URL of the page. If the page begins with https, then it is secure. If not, it is not secure. And if it is not secure, the $_SERVER['HTTPS'] has not been set and the if statement executes the lines in between the brackets. In the if statement, we create a variable named $url. This variable $url will contain the absolute path to the secure connection to the current page. The variable $url first begins with 'https://'. After this, we append the $_SERVER['HTTP_HOST'] global variable, which retrieves the domain name of the URL. We then append the $_SERVER['REQUEST_URI'] superglobal variable, which is the pathway to the file. Thus, we get the full absolute URL, now beginning with https (a secure connection). We then call the header location function to bring us to this URL. This way, we can transferred to the secure page. This way, we ensure that a page is always on a secure connection. This code protects the users of your site, because the user won't be able to be on any regular pages, which is much more prone to interception from hackers. Therefore, the user won't transmit sensitive information on regular pages. If the user types in the URL of a regular page, he or she will automatically be redirect to a secure connection. This can prevent cyberattacks on user information. Know, though, that the above code may not always work with every server. Since the data that is stored in the $_SERVER array is set by the web server, there's no guarantee that every web server will set this dat athe same. This code does work for most versions of the Apache web server but not all. And it may not work on web servers like IIS. If it does not work, then it needs modification to work correctly for the web server in use. Related Resources How to Find Out if a Page is Secure Using PHP

Create a Comma-Separated Values (CSV) File

In this article, we show how to create a comma-separated values (CSV) file using PHP. A CSV file, also called a comma-delimited file, is a common file or format used to transfer information between various databases. It can kind of be looked at as a platform-independent file that stores rows and columns of a table. This file, in turn, can be read by various databases such as Microsoft Excel, MySQL, and Microsoft Access. Thus, one file written, a CSV file, can interact with many different databases, with no need to modify the code at all. So it's like, write once, run everywhere. This is why CSV files are a popular format for working with data that goes into tables of databases. If working with many databases, it serves as a platform-neutral choice to minimize or completely get rid of the need to modify code. You can write a CSV file by hand or you can use PHP to create a CSV file. We can then later load this file into a MySQL table so that this data can be added to the table. PHP Code The PHP code to create a CSV file is shown below. <?php $user[]= "John williams,52,Custodian"; $user[]= "Michelle Smith,35,Secretary"; $user[]= "Daniel Ryans,27,Engineer"; $user[]= "Steve Adams,28,Marketer"; $arraycount= count($user); $fh= fopen("users.txt", "a"); for ($i=0; $i<$arraycount;$i++) { fwrite($fh,$users[$i]. "\n"); } fclose($fh); ?> The code above creates a CSV based on arrays, which is probably the easiest way to code rows in PHP. The code creates a CSV file for users. The data entered in is the user's name, age, and occupation. There are 4 rows entered in, representing 4 users. For each user, there are 3 columns of information entered, the name, age, and occupation of the user. We take this data and create a file named "users.txt". If the file already exists, then the file is opened and we append this data to it. A CSV file can be of many formats. You can make it be a plain text file or you can create a CSV file built by commercial companies such as Excel by Microsoft. PHP can work with a variety of file formats, formatted properly in CSV. Thus, if you change the file above to "users.csv", it creates a special csv file extension that can be used and opened by Microsoft Excel. Thus, PHP is very dynamic. It can read or create several different CSV formatted files. We create a variable named $arraycount that counts the number of array elements created. The reason we do this is so that you don't have to manually count the elements yourself. If you are creating a lot, you probably won't want to count it. You'll need to know the amount because in the for loop we create which goes through all the array elements you created, we need to loop through all the elements and the only way we can do this is by knowing how many elements exist in the array. For each element in the array, we write the array element using the PHP fwrite() function. We add in "\n" to create a line break between each array. Line breaks are very important when coding CSVs. With them, it allows us to know each distinctive row of data. Without line breaks, the code will not be in proper CSV format and will not work. After we have looped through all elements in the array and have written them all out into our file we have specified and created, we then close the file (since we're finished writing to it). Running the example, a file is created named users.txt, which is shown at the following link: users.txt. If you run the example above and change users.txt to users.csv, the following file is created: users.csv. You can now use this CSV file and load it directly into a MySQL database so that new rows of data can be inserted into a MySQL table. To see how to do this, see How to Load a CSV File into a MySQL Table Using PHP. Related Resources How to Load a CSV File into a MySQL Table Using PHP

Access the Parent Directory of a Directory

In this article, we show how to access the parent directory of a current directory you are in using PHP. So let's say you are in the Articles directory of your website located in the website's root directory, as this website is. So suppose you want to write code so that you can access the root directory of the website. In order to go up one directory from the current directory, which is to reach the parent directory of the current directory, you can use the following PHP code shown below. $directory = ".."; if (is_dir($directory)){ if ($open = opendir($directory)) { while (($file = readdir($open)) !== false){ echo $file; } Using "..", we go a directory up from the current directory. Since the Articles directory is located on the root directory, this brings us to the root directory. Using ".." allows you to go the parent of the current directory. The code outputs all the files in the parent directory of the current directory. Going Multiple Directories Up From the Current Directory So the following code above goes up one directory from the current directory. You can go how many directories up that you want. Suppose you are in the Articles/Uploads directory of your website and you want to get to the root directory. You can go up 2 directories by using the following PHP code shown below. $directory = "../.."; if (is_dir($directory)){ if ($open = opendir($directory)) { while (($file = readdir($open)) !== false){ echo $file; } We simply use ".." twice to go up 2 directories from the current directory. How to Go to Another Directory in the Same Parent Directory Now we will show how to go to a directory on the same level as the current directory. Let's say we are in the Articles directory, which is on the root directory. And we want to go to another directory on the root directory, let's say, images. We first have to go up one directory, getting out of the current directory to the root directory. We then have the specify the directory on the root directory we want to access. So the code accesses another directory on within the same root directory. Specifically, it goes from the Articles directory on the root directory to the images directory located on the same root directory. $directory = "../images"; if (is_dir($directory)){ if ($open = opendir($directory)) { while (($file = readdir($open)) !== false){ echo $file; } So this code goes to another directory on the root directory, from the Articles directory to the images directory. And this is all you really need to know about accessing parent directories using PHP. Related Resources How to Create a New Directory Using PHP How to Upload Files to Your Server Using Your Own Website How to Restrict the Size of a File Upload with PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP How to List All Files in a Directory using PHP How to List All the Directories of a Website Using PHP How to List All Files of the Home Directory and Its Subdirectories of a Website Using PHP How to Read the Contents of a File Using PHP How to Write Contents to a File Using PHP How to Copy a File Using PHP How to Rename a File Using PHP How to Delete a File Using PHP

Get and Send HTTP Headers

In this article, we show how to get and send HTTP headers using PHP. HTTP headers hold all sorts of information, such as the type of file that the document requested is, as well as the type of request that is made by the client. How to Get HTTP Headers From the Server So the first thing we'll show how to do is get headers from the server. The following PHP code below shows how to get the accept and verb from the headers from the server. <?php echo "Accept: " . $_SERVER['HTTP_ACCEPT']; echo "<br>"; echo "Verb: " . $_SERVER['REQUEST_METHOD']; ?> For this page, running the above PHP yields the following result shown below. Actual PHP Output Accept:
Verb: GET So you can see a lot of information from the above code. $_SERVER is a superglobal array in PHP which allows us to be able to get a lot of information from the server. This includes HTTP headers information. The $_SERVER['HTTP_ACCEPT'] array gets information such as the type of file the document requested is. The */* shows that the Accepter header indicates support for every possible content type. The verb is obtained through the array $_SERVER['REQUEST_METHOD']. There are several methods that can do used when communicating through HTTP. The GET method simply retrieves a page. The PUT method adds content to the requested page. The DELETE method deletes a resource from the requested page. If you look at the above verb, it will be the GET method, because you clicked on the link to get to this page, which is a GET request. Any time you're simply retrieving a web page, such as clicking on a hyperlink, it is always a GET request made to the server by the browser. How to Send HTTP Headers Now we will show how to send HTTP headers, so that it can be sent from the server to the client. The following PHP code below sends HTTP headers to a client. //send headers to the client header('Content-Type: text/html; charset=utf8'); header('HTTP/1.1 404 Not Found'); So this code above uses the PHP header() function to send header information to the client. This can be anything such as what is shown above. In the first exaple, we send the type of file it is and we set the character set. In the second example, we send the information that the page has not been found (if no page has in fact not been found). Know that if you are sending out headers, such as shown in the code above, headers must be the first thing sent to a client. So it must be at the very top of a web page. It cannot, for instance, be in the body of the page. If it is, the code will be an error. It must be the very first thing of the web document. So this is just a brief overview of how to get and send HTTP headers using PHP. Related Resources How to Create an XML Document with PHP How to Parse an XML Document Using PHP

Prevent Cross Site Scripting

In this article, we show how to prevent cross site scripting with PHP. Cross site scripting is when a user is able to insert the elements of a language onto a web page such as HTML or Javascript. For example, if you have a text box on your page where a user can enter input into the text box, the user can insert direct HTML tags onto the page or write Javascript to the page. To prevent this cross site scripting from happening, PHP has a built-in function, htmlentities(), that prevents a user from being able to enter direct HTML tags or Javascript onto the page. To visualize this and actually see it, use the text box shown below. Enter in a regular string such as "hello" and then enter in an HTML tag such as <h2>hello</h2>. You'll see that direct, without the htmlentities() function, you get the transcribed HTML code, so you see a heading with the content of hello. With the htmlentities() function, you get the literal value printed out. So what's printed out is <h2>hello</h2>. With the htmlentities() function, the language, whether HTML or Javascript will not be executed, so you get the literal value just as entered. So to do this in PHP, we use the following code below. <?php $string= "This is the string"; $string= htmlentities($string); ?> So we create a string and we pass this string through the htmlentities() function. This htmlentities() function prevents any other languages such as HTML and Javascript from being actually rendered in the language. This helps to protect a site that may not want users to be able to directly add any HTML or Javascript to be added to a page. Related Resources How to Create an XML Document with PHP How to Parse an XML Document Using PHP

Serialize an Object or Array

In this article, we show how to serialize an object or array in PHP. By serializing data, an object or an array, we mean we convert the data to a plain text format. So the an object gets converted into a plain text string. And an array gets converted into a plain text string. Serializing data is useful for many reasons. It is useful mostly for when you are passing data outside of PHP. This is especially true for complex data structures, such as arrays and objects. Other types of simple data structures such as integers or strings can work fluidly with other languages and applications as is. But other languages can't understand native PHP code when it comes to complex data structures, so serializing the data (converting the data to a plain text string) allows the data to be able to be used in other applications outside of PHP. So if you are putting data into a MySQL database, for instance, you may serialize the data before transmitting it to the database. For example, you can't just put a PHP object in a MySQL database. It's pure PHP code. It won't understand it. Thus, you serialize the object and then you can transmit to the database. The same is true for an array. Even though there are other ways of doing it, serializing the data is one of the options so that the PHP code can be transmitted to other languages and applications. In this way, you can view serializing data as making the data platform or language neutral. Practically every language can understand a plain text string, so this data can work with other applications. Serializing an Object So we'll now show how to serialize an object in PHP. This converts the object to a plain text string. Below is PHP code that serializes an object in PHP and outputs the serialized data so that you can see its form. <?php class cars { } $car1= new cars(); $cars_serialized= serialize($car1); echo "This is the serialized object: '$cars_serialized'"; ?> The PHP output of this code is shown below. Actual PHP Output This is the serialized object: 'O:4:"cars":0:{}' So you can see the output above. We'll explain the code of it now below. So we create a class called cars. Right underneath this class we instantiate an object of the class, $car1. This is an object of the cars class. We then serialize this $car1 object. After this, we then echo out the value of the serialized car object. Now having undergone serialization, the $car1 object is now a string and can be used easily outside of PHP. If you ever want to convert it back to an object, its native PHP code, then you would use the PHP unserialize() function. This converts it back to its native PHP object. This is shown below. unserialize($box1); So you can serialize the object for it to be able to work with applications outside of PHP and unserialize it to convert it back to native PHP code. Serializing an Array In the same way that we serialized an object, we can serialize an array. An array is a complex structure that may need to be serialized to work with outside applications of PHP. The PHP code below serializes an array and shows the output. <?php $colors= array("blue", "orange", "black", "green"); $colors_serialized= serialize($colors); echo "This is the serialized array: '$colors_serialized'"; ?> This PHP code yields the following shown below. Actual PHP Output This is the serialized array: 'a:4:{i:0;s:4:"blue";i:1;s:6:"orange";i:2;s:5:"black";i:3;s:5:"green";}' So it's really the same principle, just now with arrays. Again, just like with objects, you can unserialize the array and get its back to its native PHP code. And this is all that is required to serialize data in PHP. Related Resources How to Unserialize an Object or Array in PHP

Unserialize an Object or Array

In this article, we show how to unserialize an object or array in By serializing data, an object or an array, we mean we convert the data to a plain text format. By unserializing the data, we convert it back to the native PHP code. So if we serialize an object, we make it a plain text string. If we unserialize it, we get our back our previous object, as is, in PHP. Why would an object need to be serialized? An object is usually serialized when working with applications and languages outside of PHP. This is because other languages can't understand native PHP code, especially the complex data structures such as arrays and objects. Therefore, we serialize the data because it then becomes plain text format, which other languages can understand. So then we can use the serialized data and other languages can work directly with it, whether it's a MySQL database or Javascript. So we may serialize the data for it to work with other languages and applications outside of PHP. However, when we're done with the outside applications, we may want to convert the serialized back into its original unserialized form (meaning back to the regular native PHP). So, again, unserializing data is done through the unserialize function. Below is an example of a code that serializes an object and then unserializes the object. Unserializing an Object So we'll now show how to unserialize an object in PHP. This converts the object to a plain text string and then converts the plain text string back into an ojbect. Below is PHP code that serializes and unserializes an object in PHP and outputs both the serialized data and the unserialized data. <?php class cars { public $color; } $car1= new cars(); $car1->color= "red"; //serializes the object into a plain text string $car1_serialized= serialize($car1); //outputs the serialized text string echo "This is the serialized data shown below:
'$car1_serialized'"; echo "<br>
"; //unserializes the plain text string back into an object $car1_unserialized= unserialize($car1_serialized); //outputs the object and an object property echo "This is the unserialized data shown below:
"; echo var_dump($car1_unserialized); echo "<br>"; echo "Object property:" . $car1_unserialized->color; ?> The PHP output of this code is shown below. Actual PHP Output This is the serialized data shown below:
'O:4:"cars":1:{s:5:"color";s:3:"red";}'

This is the unserialized data shown below:
object(cars)#2 (1) { ["color"]=> string(3) "red" }
Object property:red So you can see the output above. We'll explain the code of it now below. So we create a class called cars. Inside we put a public property $color. Right underneath this class we instantiate an object of the class, $car1. This is an object of the cars class. We set the color property of this car equal to red. We then serialize this $car1 object and store the serialized data into the variable $car1_serialized. We output this serialized data, which is in plain text format in a string. We then unserialized this serialized data thorugh the unserialize() functin. We then output the breakdown of the object through the PHP var_dump() function. We also output the color property of the $cars1_unserialized object so that you can see that it is in fact an object in that we're referencing as an object would be (showing it's an object). Of course, you don't have to call the variable $cars1_unserialized. You can call it the original value $car1 again. Unserializing an Array In the same way that we unserialized an object, we can unserialize an array. An array is a complex structure that may need to be serialized to work with outside applications of PHP. Later on in the code, once we have dealt with the external languages or applications, we may need to convert it back into an array. And we do this through the unserialize function. The PHP code below serializes an array and then unserializes the serialized data back into an array. <?php $colors= array("blue", "orange", "black", "green"); $colors_serialized= serialize($colors); echo "This is the serialized array shown below
: '$colors_serialized'"; $colors_unserialized= unserialize($colors_serialized); echo "<br>
"; echo "This is the unserialized array shown below:
"; echo ""; echo print_r($colors_unserialized); echo "</pre>"; ?> This PHP code yields the following shown below. Actual PHP Output This is the serialized array shown below
: 'a:4:{i:0;s:4:"blue";i:1;s:6:"orange";i:2;s:5:"black";i:3;s:5:"green";}'

This is the unserialized array shown below:
Array ( [0] => blue [1] => orange [2] => black [3] => green ) 1 So it's really the same principle, just now with arrays. We create an array, serialize it, show the serialized array, then unserialize it, getting back the original native PHP array. We then output the array through the print_r() function. We use pre tags just to make the array more readable. And this is all that is required to unserialize data in PHP. Related Resources How to Serialize an Object or Array in PHP

Generate a Random Video id like Youtube

In this article, we show how to generate a random video id like youtube does in PHP. Youtube generates random video ids such as, https://www.youtube.com/watch?v=FXSuEIMrPQk After the ?v= is the random video id that youtube generates. So, in case you didn't know or weren't aware, youtube generates an 11-digit video id every time a user uploads a video. This 11-digit video id is a unique identifier for the video. How youtube does this is it uses base-64 encoding. Base-64 encoding is a system that uses 64 possible characters for each of the 11 digits. Youtube uses 11 digits. Therefore, there are 64 x 64 x 64 x 64 x 64 x 64 x 64 x 64 x 64 x 64 x 64, or 6411, which is equal to 73,786,976,294,838,206,464 possible combinations. So which characters does youtube use? So we know that youtube uses a base-64 encoding system. Which 64 characters does youtube use? The 64 characters that youtube uses is 0-9 (10 combinations), lowercase alphabetical characters a-z (26 characters), uppercase characters A-Z (26 characters), a hyphen (-), and an underscore (_). So the characters are 0-9, a-z, A-Z, -, and _ These are all the possible characters that youtube uses to create a video id. Random video id: 0B7jmvV82Ll Full youtube URL: https://www.youtube.com/watch?v=0B7jmvV82Ll So you can see above we have created a random video id, such as what you would find generated by youtube. If you refresh the page, each time you do so, a new video id will be generated. Again, with just 11 digits, we are able to generate 73,786,976,294,838,206,464 possible video ids. 11 digits can generate over 73 quintillion possible combinations with base-64 encoding. So how can we generate a random 11-digit video id such as youtube does with PHP? The following code below generates a random 11-digit video id, shown below. <?php $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'; $result = ''; for ($i = 0; $i < 11; $i++) $result .= $characters[mt_rand(0, 63)]; ?> So the following PHP code above is able to generate an 11-digit random string from the characters we have provided in the $characters variable. This $characters variable contains 0-9,a-z,A-Z, -, and _ Those are the 64 characters that youtube uses in order to make a video id. We then create a variable named $result and set it equal to '' We then have a for loop in which we put the for loop from 0 to 11, in order to generate an 11-digit string. This string is selected randomly from the $characters variable, choosing any characters from 0-9,a-z,A-Z, -, or _ This $result variable now contains the random-generated 11-digit string. To attach this to the youtube URL, the following line does this, shown below. <?php $youtubeurl= "https://www.youtube.com/watch?v=" . $result; ?> So now we have the full youtube URL with the randomly generated video id. So youtube may do it slightly different. I'm sure they filter out certain words that are offensive so that it doesn't show up in the URL. However, this shows the mere basics with the PHP language. Related Resources How to Insert Images into a MySQL Database Using PHP

How to Insert Videos into a MySQL Database Using PHP

How to Insert Files into a MySQL Database Using PHP

How to Create a Video Manager Using PHP & MySQL

Create a Class

In this article, we go over how to create a class in PHP. A class represents a blueprint or template of objects. For example, if you dealing with a bunch of objects that represent animals, such as a lion, a dog, a cheetah, a pig, the class may be appropriately named animals. This is because all of the objects are animals. Thus, naming the class animals represents the temple or blueprint of these objects. A class is the blueprint of object-oriented programming (OOP). Before you can create objects, you must create a class that represents the template of these objects. PHP, especially versions 5 and now, now support OOP. To create a class in PHP, the general format to do so is shown below. class animals { //properties, objects, and methods go inside here } So in the above code, we have created a class named animals. All you need to do to create a class in PHP is to use the keyword class and follow it with the class name. Unlike Java, for instance, you do not add any keywords before class like public or private. PHP simply uses class by itself. Trying to use public or private with a class will result in a fatal error, in which the program will not run. You simply need to use the keyword class followed by the class name. Inside of this class, we put the properties, objects, and methods that you want in this class. For example, you may have objects such as pigs, dogs, elephants, etc. Methods may include what the animals do, such as eat, run, etc. Properties may include features of the animals such as scaly skin, smooth skin, etc. We show the full PHP code of how to create a class in PHP. <?php class animals { function eat() { echo ("I eat food"); } } $lion= new animals; $lion->characteristic= "King of the jungle"; echo "Lion Characteristic: " . $lion->characteristic . "<br>"; $lion->eat(); ?> So in the above code, we've created a class named animals. To create a class in PHP, all you have to do is use the keyword class followed by the name of the class. Just for demonstration purposes, we made a function in this class called the eat() function. In this function, the animal declares "I eat food", which is a characteristic of every animal on the plantet, including humans. We then create an instance of the animals class, $lion. This represents a lion. We then give the chief characteristic of the lion, which is that it is king of the jungle. We then echo out the lion's characteristic, as well as the lion carrying out the eat() function, in which it declares that "I eat food". This just goes to show you what can be done by creating a class. We can create methods within the class, objects within the class, and so on and so forth. So creating a class is very simple. All that is needed is the PHP keyword class followed by the class name. By convention, PHP classes are normally in lowercase but doesn't have to be. It's just that that's the normal convention. Once you create a class, you delve into the world of OOP in which you have many limitless possibilities of what you can do based on that class. Possibilities include extending the class, in which you create another class that inherits all the properties, methods, and functions of that original class. There's many things you can do in the world of OOP that applies not just to PHP, but to all OO porgramming languages including Java and C++. Going back to the PHP code above, if it's run, this gives the following output shown below. Actual PHP Output Lion Characteristic: King of the jungle
I eat food How to Create a Child Class To create a child class of a class, you can use the keyword extends. The format to create a child class is shown below. class dogs extends animals { } This code creates a new class named dogs, which is a child class of the pets class. This dogs class inherits every method and property of the animals class. This is a fundamental principle of object-oriented programming called inheritance. The child class inherits everything that is in the parent class. In this case, the parent class is animals. Then you can add specialized methods and properties to that child class that may pertain to it. As an example, we have the full code of creating a child class shown below. <?php class animals { public $skin= "furry"; } class dogs extends animals { public $sounds= "barks"; } $bulldog= new dogs; echo "The dog's skin: " . $bulldog->skin . "<br>"; echo "A dog " . $bulldog->sounds . "<br>"; ?> So we begin by creating a class named animals. In this animals class, we create a variable named $skin that is set equal to the value of furry. Later when we create a child class of the animals class, you'll see that this child class will inherit this $skin variable value of furry. We then create a child class of the animals class via using the extends keyword. Inside of this class, we create a variable called $sounds which is set equal to barks, since a dog barks. We then create an object of the dogs class, named $bulldog. We then echo out the bulldog's skin, which is furry. This is because the dogs class inherits the $skin variable of furry from the parent animals class. Inside of the dogs class itself, we create a variable named $sounds which is equal to bark. This is a specialized value to the dogs class and is unique to the dogs class. It's not found in the animals class. It's specialized to the dogs class. We then echo out these values. And this is how a child class can be built in PHP. If we run the above code, this yields the following output below. Actual PHP Output The dog's skin: furry
A dog barks

Create and Access a Class Constant

In this article, we show how to create a class constant in PHP. A constant is a value that is constant, it cannot change. It's the opposite of a variable that can change value. A constant is declared once and stays the same throughout the course of code. A class constant is a constant found in a class. This can be useful whenever you need a constant in object oriented programming such as in classes. To create a constant in a class, you use the keyword const followed by the constant name and the value it is equal to. The following code below creates a class constant and shows how to access this class constant in code. We do so by echoing out the value.. <?php class mathematics { const PI= 3.14159265; } echo mathematics::PI; ?> So the above code creates a class called mathematics. In this class, we define a constant named PI, which is the distance around a circle when the diameter is equal to 1. To create a constant, we simply use the keyword const, followed by the constant name. Normally constants will always be initialized at the time of declaration so we set its value equal to 3.14159265. To access the class constant, you use the name of the class (in this case mathematics), followed by 2 colons (::), followed by the name of the constant (in this case PI). In this code, we echo out the constant, so an echo precedes this code. Usually by convention, constants are put in all uppercase. This is just a coding convention, not a necessity. But this helps to differentiate constants from variables. Running the PHP code above, we get the following output shown below. Actual PHP Output 3.14159265

Instantiate an Object

In this article, we go over how to instantiate an object in PHP. Instantiating an object means that we create a new object of a class in PHP. Before you can create an object, you must create a class. The class is the overall blueprint or template of the object. So you must first have a class. Then once you have a class, you can create an object of a class. So let's say we create a class named vehicles. Vehicles is the overall blueprint or template. Inside of this vehicles class, we can create an object or several objects. One object, for instance, can be a car. Another one can be a truck. Another object can be a boat. Another vehicle can be a van. So from this class, which represents a sort of template, we can create objects of this class. So below in the PHP code is the general standalone to create an object named car from the vehicles class. $car= new vehicles; So in the above code, we have created an object named $car from the vehicles class. We show the full PHP code of how to instantiate an object below. <?php class vehicles { } $car= new vehicles; $car->type= "Toyota Camry"; $car->color="Green"; $car->cost='$20,000'; echo "Car type: " . $car->type . "<br>"; echo "Car color: " . $car->color . "<br>"; echo "Car cost: " . $car->cost . "<br>"; ?> So in the above code, we've created a class named vehicles. To create a class in PHP, all you have to do is use the keyword class followed by the name of the class. We then create an object of the class vehicles and name it $car. This is a new car object we've created. After we've created this instance of a class, we can now do things with the object such as assign it properties. A car has a type, for example, being a toyota camry. A car has a color, for example, green. A car has a cost. In our example, the car costs $20,000. I echoed out the object properties just to show you how it would work to create an object, give it properties, and then output those properties. So this is the most basic example of create an instance of a class. It can get more advanced than this. If the object takes values as parameters, then you would need to create a constructor method that is able to initialize the values to the object. But just to make this tutorial simple, I've just shown how to make the most basic type of object of a class that can be done with PHP. In further tutorials, I'll show more. Going back to the PHP code above, if it's run, this gives the following output shown below. Actual PHP Output Car type: Toyota Camry
Car color: Green
Car cost: $20,000

Delete an Object

In this article, we show how to delete an object in PHP. An object is an instance of a class. Using the PHP unset() function, we can delete an object. So with the PHP unset() function, putting the object that we want to delete as the parameter to this function, we can delete this object. This is shown below. unset($object1); So in the above code, we delete an object named $object1. In the code below, we show a complete example of deleting an object. <?php class cars { public $type; } $car1= new cars(); $car->type= "Hyundai Elantra"; unset($car1); ?> So in the code above, we create a class named cars. Inside of this, we declare one property named $type. This will represent the type of car it is. We then instantiate an object of this class cars, $car1. We assign the $car1 object the type, Hyundai Elantra. We then delete the $car1 object through the unset() function. It's very simple. Creating a Destructor Method You also have the option of puting a destructor method in a PHP class. When an object is deleted, the destructor method is automatically called and you can do anything in this code, just as with any method. For example, you can close a database connection. Output that the object is being deleted. If you're keeping track of the number of objects in a class, you would decrement the variable keeping count by 1 (since an object is deleted when this method is called). This, again, is optional. You don't have to have a destructor method in your code. However, if you want to call a method when an object is being deleted, you would then want to add a destructor method because it's called whenever an object is deleted. Below is an example code in which we add a destructor method. When we delete an object using the unset() function, this destructor method is automatically called. We otuput that the object is being deleted and since we keep track of all the objects in a class, we decrement the variable storing the count by 1. <?php class cars { public static $count=0; public function __construct($type, $year) { $this->type= $type; $this->year= $year; cars::$count++; return true; } public function __destruct() { echo "The " . $this->type . " is being deleted" . "<br>"; cars::$count--; } } $car1= new cars("Toyota Camry", 2014); $car2= new cars("Nissan Altima", 2012); $car3= new cars("Honda Accord", 2010); $car4= new cars("Tesla Model X", 2015); $car5= new cars("Tesla Model 3", 2016); unset($car4); echo "The number of objects in the class is " . cars::$count; ?> So we create a class named cars. In the next line, we create a static variable $count that stores the value of count. We set to equal to 0 initially because no objects have been created or deleted yet. It starts out at the neutral ground of 0. We then create a constructor method which takes in the $type and $year variables as its arguments. When an object is instantiated, the $type and $year values get set based on the values we pass into the object. We increment the $count variable by 1, because a constructor is called when an object is created. We then create the destructor method. In this method, we echo that the object is being deleted. We also decrement the $count variable by 1, since an object is being deleted. (A destructor method is only called when an object is being deleted0)> After, this, we create 5 car objects. During this time, the __construct method is called. The $count variable, thus, gets incremented 5 times, having a value of 5. We delete the $car4 object through the unset() function. It is at this time the __destruct() method is called. Thus, at this time, we output that the object is being deleted and decrement the $count variable by 1. So now the $count variable has a value of 4. We then output the number of objects in the class, which is now 4, since 1 has been deleted. So, again, having a destructor method in your class is optional. It's only if you want something done when an object is being deleted. This can be closing a datbase connection, keeping track of the number of objects in a class, echoing out some output, etc. So this was a tutorial on deleting an object of a class in PHP. Related Resources How to Create a Class Destructor in PHP

Initialize an Object

In this article, we go over how to initialize an object in PHP. Initializing an object means that we give an object that has been created from a class a value or values. For example, say we create an object named car from the vehicles class. The vehicles class represents a range of vehicles and the car is just a particular object or instance of this vehicles class. We can then assign values to the car such as the car's color, the car's cost, the car's engine, etc. If we set the car's color to red, we have initialized the object with this color property. So initialized an object is just giving values to the object, that represent's the object's properties. Before you can create an object, you must create a class. The class is the overall blueprint or template of the object. So you must first have a class. Then once you have a class, you can create an object of a class. So below in the PHP code is the general standalone to initialize properties of an object. //$car is the object $car->color= "green"; $car->type = "Toyota Camry"; $car->doors= 4; So in the above code, we have initialized the color, type, and doors properties of the $car object. All you need to do to initialize an object in PHP is to take the object name and use "->" followed by the property name. You then set this equal to the property value either through single quotes, double quotes, or nothing (if the value is a number, you have this option). And that is all you need to do to initialize object properties in PHP. Below we show the full PHP code of how to initialize an object and how to echo out the values of the object that we've initialized. <?php class vehicles { public $enginetype= "automatic"; } $car= new vehicles; $car->color= "green"; $car->type = "Toyota Camry"; $car->doors= 4; echo "Car type: " . $car->type . "<br>"; echo "Car color: " . $car->color . "<br>"; echo "Car number of doors: " . $car->doors . "<br>"; echo "Car engine type: " . $car->enginetype . "<br>"; ?> So in the above code, we've created a class named vehicles. To create a class in PHP, all you have to do is use the keyword class followed by the name of the class. Inside of the class we put a public variable $enginetype and set it equal to "automatic". You'll see now that every object we create will have an engine type of automatic. Because every object inherits the engine type being equal to automatic. When we create the object o the class below named $car, it inherits this enginetype as being automatic. We then create an object of the class vehicles and name it $car. This is a new car object we've created. After we've created this instance of a class, we've initalized a few values, the type, color, and doors properties. I echoed out the object properties just to show you how it would work to create an object, give it properties, and then output those properties. So this is a basic example of how to initialize and output the initialized values of an object in PHP. Going back to the PHP code above, if it's run, this gives the following output shown below. Actual PHP Output Car type: Toyota Camry
Car color: green
Car number of doors: 4
Car engine type: automatic

Invoke an Object Method

In this article, we show how to invoke a method in a class on an object. Say you've created a class that has a method or methods in it as well as objects in it. How can you invoke those methods on those objects? We'll show below how to invoke methods on objects in PHP. Being that methods typically compose classes and objects are tailored to run methods, this is essential to know. Let's say below we have animals class and we have a walk() method. This simulates that an animals walks. To invoke a method such as this in PHP, the general format to do so is shown below. function walk() { echo "I'm an animal and I walk"; } $turtle= new animals; $turtle->walk(); So in the above code, we have create a function called walk() that echoes out, "I'm an animal and I walk". We then create an instance (or object) of the animals class, $turtle. We invoke the walk() method on this object or you can say that the object invokes this method. Either way, the $turtle object performs the walk() method. To invoke a method on an object, you simply call the object name followed by "->" and then call the method. Since it's a statement, you close it with a semicolon. When you are dealing with objects in PHP, the "->" is almost always used to access that object, whether it's a property or to call a method. It's kind of the way of dealing with objects in PHP. Remember that when you invoke the method, the method must have "()" with it. It will not work without the parentheses. We show the full PHP code of how to invoke a method on an object. <?php class animals { function walk() { echo "I'm an animal and I walk"; } } $turtle= new animals; $turtle->walk(); ?> So in the above code, we've created a class named animals. To create a class in PHP, all you have to do is use the keyword class followed by the name of the class. We then create the walk() function which echoes out, "I'm an animal and I walk". We then create an instance of the animals class, $turtle. We then invoke this walk() method on the $turtle object using "->" in between the object and the method. So it's rather simple to invoke methods on objects in PHP. Of course, some methods take parameters if you've created that for your method. But it works in the same method. If a method takes parameters, it's called in the same way, only with the parameter(s) included. Going back to the PHP code above, if it's run, this gives the following output shown below. Actual PHP Output I'm an animal and I walk.

Access Overridden Methods

In this article, we show how to access overridden methods in PHP. An overriden method is one that is overridden usually by a parent class. Let's say you create a method named move() in a parent class that states, "I run". Then you create a child class and use the same method named move() that states, "I run fast". You have overridden the parent method in the child class. The move() method originally stated, "I run" and in the child class now states "I run fast". So in the child class, even though, you've overridden the move() method, there may be times when you still want to use the parent method. And you still can access the parent method. The PHP code below shows how to access the parent method when you've overridden the method in the child class. <?php class animals { function move($speed) { echo "I run at $speed miles per hour"; } } class cheetahs extends animals { function move($speed) { if ($speed > 60) { echo "As a cheetah, I run fast, at $speed miles per hour"; } else { parent::move($speed); } } } $animal1= new animals; $cheetah1= new cheetahs; $animal1->move(10); echo "<br>"; $cheetah1->move(75); echo "<br>"; $cheetah1->move(15); ?> So in the code above, we create a class named animals. In this function, we have a function named move() which accepts a parameter named $speed. This function outputs "I run at the number of miles per hour". We then create a new class named cheetahs, which is a child class of the animals class. We create the same method move() which accepts the $speed parameter. If the $speed is greater than 60, we echo, "As a cheetah, I run fast, at how many miles per hour". Else, we echo the original parent function. To access the overridden method in PHP, we use the parent keyword, followed by 2 colons (::), followed by the function. So to access the overridden parent method, in this case, the code to do so is, parent::move($speed). And this is all that is required to access a parent class in PHP. Running the code above yields the following output below. Actual PHP Output I run at 10 miles per hour
As a cheetah, I run fast, at 75 miles per hour
I run at 15 miles per hour Related Resources How to Create a Class Destructor in PHP

Create Getter and Setter Methods

In this article, we show how to create getter and setter methods in PHP. Just as the name implies, a getter method is a method that gets or retrieves a value of an object. And a setter method is a method that sets the value of an object. Getter and setter methods are used when you want to provide encapsulation for your data. You make property of the object you are getting or setting either private or protected, providing encapsulation. You then use the getter or setter method to be able to access the private or protected property of the object. Therefore, there isn't direct access to the data and you could provide more control of how the data is changed and what values it can accept. When learning about getter and setter methods, it may seem hard to understand why you would need to provide this type of encapsulation to the data. So let's take an example how why you would want to provide encapsulation to data? Let's say you have a class named kids whose objects represents kids. And the property you want to store is the height of each kid. Without encapsulation, for instance, you can set the height to a value that it can't possibly. For example, you can easily set the value to 1 inch tall or even a negative number. However, if you encapsulate the property and put in a setter method where you put, for example, of instance that you set the height only if it's above a certain level, then this allows you to filter bad data. So it provides the data from bad entries. So this is the power of encapsulation. You run the setter method and you can make it so that the height only gets set if it's a valid, reasonable number. A child's height can't be negative. A child's height can't be 1 inch tall. This is the power of giving encapsulation. It also allows you to filter bad set values, which you wouldn't be able to do if the data isn't encapsulated. So below is an example PHP code that creates a getter and setter method for kids' heights. <?php class kids { private $height; public function setHeight($height) { if ($height > 30) { $this->height= $height; } } public function getHeight() { echo "The child's height is " . $this->height . " inches tall"; } } $kid1= new kids; $kid1->setHeight(40); $kid1->getHeight(); ?> So in the above code we create a class named kids. Because we want to provide encapsulation to the data, we make the object properties private. In this code, we simply create one property $height. This, of course, is made private or protected to provide encapsulation. We make the getter and setter methods public, however. We make to provide access to the data. However, within the getter and setter methods, we create standards of what should be done with the data, so that we can decide what is acceptable and what is not. The rule is to make the data private and the getter and setter methods public. Not that this is always the case, but you can do this for now. So we now create the setter method. I name it setHeight($height). It accepts the $height parameter. It will set this height to the object you call it on as long as the height is greater than 30 (30 inches). We then create the getter method. I name it getHeight(). It accepts no parameters. It retrieves an already set value. We echo out the statement that the child's height is however inches tall. To test the setter and getter methods, we instantiate an object of the kids class, $kid1. We then call the setHeight() function on the $kid1 object. We pass in the parameter 40. This statement sets the child's height to 40, since 40 is greater than 30. If it was less, then the value wouldn't get set. We then call the getHeight() function. This echos out the child's height. So now you've gotten a firsthand experience of what a getter and setter is, what it's used for, and how to create and call them in PHP code. The encapsulation it provides really helps to filter bad data and gives you, the coder cleaner, safer code that doesn't present bad data. Running the above PHP yields the following output shown below. Actual PHP Output The child's height is 40 inches tall There's also a way in PHP that create getter and setter methods using the magic __get and __set methods. This is an alternative and very effective way of setting and getting values for a given class. Related Resources How to Create a Final Method in PHP

Use the PHP __get and __set Magic Methods

In this article, we show how to use the PHP __get and __set magic methods. The PHP __get and __set magic methods function as getters and setters for object values, but it had the added advantage in that you don't have to declare the object properties (variables) in the class. Instead when you set a value (with the object property never declared in the class), the __set magic method is automatically called and sets the value. The same is true for the __get method. Without the object property being declared in the class that you want to get, the __get magic method is automatically called and gets the value. So the __get and __set magic methods function as getters and setters, without the object property variable having to be declared in the class. We will show each of these in the code below. In the code below, we make a class called kids. In this class, we set a child's height through the __set method or get a child's height through the __get method. Getter and setter methods provide encapsulation of data so that in order to set or get data, it has to pass through a method. The reason we do this is because many times we want to test the data first to make sure that's an appropriate or reasonable value. In this class, we are setting the height of a kid. For example, the height cannot be negative. The height can't be 1 inch tall. No child is one inch tall. This is the reason we only allow for heights 30 inches or grader. Imagine this is fifth grade student. They all are way past this point. So passing data first through a method allows us to filter out bad data. It allows for this encapsulation where we don't have to accept bad data, such as a negative height or 0.5 inches tall. This is why getter and setter methods are commonly used. <?php class kids { public function __set($property, $value) { if ($value > 30) { $this->property= $value; } } public function __get($property) { return "The child's height is " . $this->property . " inches tall"; } } $kid1= new kids; $kid1->height= 45; echo $kid1->height; ?> So we create a class called kids. Inside of this class we create the setter and getter methods. The first method that we create the setter method using the __set function. The setter function has to accept 2 parameters, the object property you are defining and the value of this object property. As we are setting a child's height in this code, the height is the object property and the value of the height we set it to is the value. We make it so that if the value passed into the object property is greater than 30, we set the object property to that value. If the value is less than 30, then the magic set method does not set the value. We then create the next function, the getter method using the __get function. The get function accepts one parameter, the $property of the object. We do not need the $value as the parameter, because the $value is already set by the setter function. With the getter function, we do not set the value. We just retrieve the value that's already been set. So in this getter function, we return the child's height in inches by calling the $this->property function. $this->property refers to the value of the property of the object we're getting. All of this will make more sense now below. So underneath this, we create an object of the kids class, $kid1. We then the object property, height, of $kid1 equal to 45. This makes the kid's height 45 inches. What'a amazing about the magic method __set() in PHP is that we have defined the property variable $height anywhere in the class. Yet we're just automatically setting the height of the $kid1 object. This triggers the PHP __set() magic method. The method sees the height as a property of the object and 45 as the value of this height property. $kid1 is the object of this call. So because we automatically set an object property and its height without declaring them or calling a function, this automatically calls the PHP __set() magic method. So the $property value is height. The $value of this property is 45. We set the value only if the value is greater than 30. We set the value through the line, $this->property= $value. $this refers to the object kid1. We set $kid->height= 45. So now you can see how this is set through the PHP __set magic method. This covers the set part. To automatically get the property of an object, you call an output function such as echo or print with the parameter of an object and property. This automatically triggers the PHP __get magic method. The only parameter needed for the __get() method is the $property variable. We return out what the child's height is in inches. So this is all that is required to use the PHP __get and __set magic methods. It's very adaptable because you don't need to declare variables in the class and you don't need to call a function. If you set it up properly, like how demonstrated, it will automatically call the __get or __set magic methods. So in this way, it simplifies code. Running the PHP code above yields the following output shown below. Actual PHP Output The child's height is 45 inches tall Related Resources How to Create Getter and Setter Methods in PHP

Use the PHP __toString() Magic Method

In this article, we show how to use the __toString() magic method in PHP. The __toString method in PHP is one that allows us to call an object and see its components as a string. So by using the echo and print function and having the object in the parameters of the echo or print function, the __toString() magic method is automatically called and it can allow us to see all the contents of an object (the properties of the object). You'll see what I mean when you see the example code shown below. But for now, realize, that the __toString() magic method is automatically called when we use the PHP echo or print function and place an object of a class inside of the echo or print function. We then can use the __toString() method to output all of the contents of the object, such as all the object properties. This saves us a lot of work of using getter methods to access the values of objects. We simply can use the __toString method to output all of the properties of a n object. Not only that, but you can really do anything with the __toString method such as display sentences using object properties. So as an example code, we create a class with private variable properties. We then getter and setter methods to get and set values. We also include a __toString() magic method so that we can output object properties. <?php class cars { private $type; private $year; public function setType($type) { $this->type= $type; } public function setYear($year) { $this->year= $year; } public function getType() { echo $this->type; } public function getYear() { echo $this->year; } public function __toString() { return "Car type: " . $this->type . "
Car year: " . $this->year; } } $car1= new cars; $car1->setType("Toyota Camry"); $car1->setYear(2013); echo $car1; ?> So we create a class named cars. We declare 2 private variables $type and $year. They are declared private, so that we can achieve encapsulation for the data. We then create getter and setter methods to set and get our values. We then create our __toString() magic method. The __toString() method must have a return value. So you must use the keyword return. After the return, you put the data that we want to return. Since the car object we are creating has a type and year, we output these values. After this, we then create an object of the cars class, $car1. We set the 2 values of the car, the type to a "Toyota Camry" and the year to 2013. We then simply echo the object, $car1. When we do this, what we put into the __toString method is output. If we echoed out the object without the __toString method in the code, the program would output a fatal error, such as the following: Catchable fatal error: Object of class cars could not be converted to string. Running the PHP code above yields the following output below. Actual PHP Output Car type: Toyota Camry
Car year: 2013 Related Resources How to Create Getter and Setter Methods in PHP

Create a Final Class

In this article, we show how to create a final class in PHP. A final class is a class in which the class cannot be extended, meaning a child class cannot be created. Just as the name final implies, it's a class that can't be manipulated. It's final. So with a final class, no child class can be created from it. So trying to use the keyword extends to create a child class will not work. To create a final class in PHP, you simply have to put the keyword final before the keyword class. So the following code below creates a final class named animals. final class animals { } So the class above is a final PHP class. No child class can be created from it. If you attempt to create a child class from a final class, you will get a fatal error. I took the above animals class and tried to create a subclass named zebras from it. I got an output shown as that shown below. Fatal error: Class zebras may not inherit from final class (animals) A final class is one where you absolutely do not want any inheritance. You do not want any child classes to inherit a final class. In this way, a final class can be seen as a standalone class. And making a class final, as you can see, is really simple. The final keyword simply needs to precede it. Related Resources How to Create a Final Method in PHP

Create a Final Method

In this article, we show how to create a final method in PHP. A final method that cannot be overridden. So if you create a final method in a parent class, you cannot override that method in a child class. If you attempt to define a method in a child class that is the same as a final method in a parent class, a fatal error will be thrown. Once a method is declared to be final, another inherited class cannot use the same method name. The method in the parent class cannot be modified. In other words, it's final, as the name implies. To create a final method in PHP, you simply have to put the keyword final before the keyword function. So the following code below creates a final method named move(). class animals { public final function move() { echo "Move ahead"; } } So the class above creates a class named animals. Being that we've declared this function to be final, it cannot be modified in any child class at all. No child class can even use the same method in name, or a fatal error will be output. Just to show you the output you would get if you created a child class and attempted to use the same method name move(), I created a child class and named a method in the child class the same name, move(). In return, the program output a fatal error, such as shown below. Fatal error: Cannot override final method animals::move() A final method is one where you absolutely do not want any change to the method at all in the parent class or any child classes. In this way, a final class can be seen as an immutable method. And making a method final, as you can see, is really simple. The final keyword simply needs to precede it. Related Resources How to Create a Final Class in PHP

Create an Abstract Class

In this article, we show how to create an abstract class in PHP. An abstract class is a class that which an object cannot be instantiated. Instead the class serves as a blueprint for children classes of this abstract class. In a PHP abstract class, you must define at least one abstract method. Each child of this abstract class then can implement the method or methods specified in the abstract class. In other words, all an abstract class does is serve as a future blueprint for children classes in terms that it lays out the methods the children classes should implement. The abstract class normally doesn't implement the method themselves. Normally the methods are empty. The name of the method is just declared so that it can be defined for future children classes. So the parent class is abstract. The children classes are tangible. To make a class abstract in PHP, all you have to do is put the keyword abstract before the keyword class. This makes the class an abstract class. As stated, the methods of the abstract class must be labeled abstract. This is done by putting the keyword abstract in the method declaration. So, as an example, below, we created an abstract class called shapes. <?php abstract class shapes { abstract public function calculateArea(); } So we created an abstract class called shapes. Inside of it, we created an abstract public function called calculateArea(). When you think about this, it makes sense. Shape can be seen as a generic or abstract concept. A shape is can be one of many things. It isn't specific. So a shape object really cannot be instantiated. However, if you create a child class in which you specify the shape, you can have child classes such as circle, triangle, square, rectangle, etc, which are definite shapes. So a shape is abstract. A circle, rectangle, triangle, is tangible. It's a definite shape. You cannot calculate the area of a shape, since it's generic. However, you can calculate the area of a circle, rectangle, triangle, since it's tangible. So this is the methodology behind abstract classes. Now, that you understand the concept behind, there are a number of rules for using abstract classes in PHP. As stated previously, abstract classes must contain at least one method that is also marked abstract. These methods are called abstract methods. If a class contains an abstract method, the class must also be declared abstract. However, abstract classes can contain non-abstract methods. Abstract methods are not implemented in the abstract class. Instead the methods are implemented in a child class that extends the abstract parent. If a subclass fails to implements all the abstract methods in the parent class, then it itself is abstract and another class must be created to further subclass the child and implement the remaining methods. Abstract methods cannot be defined as private, because they need to be inherited. Abstract methods also cannot be defined as final, because they need to be overridden. Lastly, when you specify the abstract method in the parent class, the exact same method with the exact same parameters must be used in all the children classes. Meaning you cannot have a method that accepts different parameters in any of the child classes. It must be the exact methods that receives the same exact arguments, or else an error will be output. So just to give a complete example of abstract code, see the following code below.


Complete Code of an Abstract Class <?php abstract class shapes { abstract public function calculateArea(); } class circle extends shapes { public function calculateArea() { echo "You calculate the area of a circle by the formula, A= πr2"; } } class square extends shapes { public function calculateArea() { echo "You calculate the area of a square by the formula, A= (length)2"; } } $circle1= new circle; $circle1->calculateArea(); echo "<br>"; $square1= new square; $square1->calculateArea(); ?> You can see how we create an abstract class called shapes. This abstract class has an abstract method called calculateArea(). This method will give us the formula for the shapes we specify. Each child class must implement this calculateArea() method. So we create our first child class under the abstract class named circle. In this class, we create a public function called calculateArea(). This calculateArea() function when called will show the formula for calculating the area of a circle. We then create another child class of the abstract shapes class named square. In this class, we create a public function calculateArea(). This funtion when called will show the formula for calculating the area of a square. We then create objects of each of the classes and call the methods. This leads to us getting the following output shown below. Actual PHP Output You calculate the area of a circle by the formula, A= πr2
You calculate the area of a square by the formula, A= (length)2 So you can see how the abstract class provides the abstract foundation. And then we create child classes that actually implement the methods. So this is a quick run-down of abstract classes, how it can be created, and the rules that apply for them in PHP. Related Resources How to Create a Final Method in PHP

Create and Implement an Interface

In this article, we show how to create and implement an interface in PHP. An interface is the equivalent of an agreement to implement certain methods. So in an interface we declare certain methods. If a class implements an interface, it must implement all the methods set up in the interface. So you can see that creating an interface and then a class that implements that interface is a great way to ensure that the class carries out all of the functions defined in the interface. To create an interface in PHP, all you must do is use the keyword interface followed by the name of the interface (any name). When you create a class that you want to implement that interface, you simply declare the class, as you would normally would and follow that line with implements name_of_interface. So below in the PHP code, we create an interface named calculation. The class that we then create named circle implements this interface. So this means that this circle class must implement the functions listed in the interface named calculation. <?php interface calculation { public function calculateArea(); } class rectangle implements calculation { public function calculateArea() { echo "The formula to calculate the area of a rectangle is, A= l x w"; } } $rectangle1= new rectangle; $rectangle1->calculateArea(); ?> So in the code below we create an interface named calculation. In this interface function, we define a public method named calculateArea(). We then create a class named rectangle that implements this interface, calculation. Because this class, rectangle, implements the calculation interface, it must implement the method(s) defined in the interface. Since there is one method named calculateArea() in the calculation interface, this class rectangle must implement this calculateArea() function. In the calculateArea() function, we echo out the formula for a rectangle. To test the code, we create an object of the rectangle class, $rectangle1. We then invoke the calculateArea() method on the $rectangle1 object. And the code works. Running the above PHP code yields the following output below. Actual PHP Output The formula to calculate the area of a rectangle is, A= l x w If the class that you create that implements an interface does not implement the method(s) in the interface, a fatal error will be output, such as shown below. Fatal error: Class rectangle contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (calculation::calculateArea) There's a few other rules when you are dealing with interfaces in PHP. The interface itself does not implement any methods. The methods in the interface are empty methods; they contain nothing. It's the class that implements the interface that contains a method that is defined and implements the methods. Another rule is that the methods in an interface must be declared public. It cannot be private because other classes have to access the methods to implement. For the same reason, the method(s) defined in the interface cannot be declared final. Another rule is that the method that you define must have the same name obviously as the method in the interface but it must also accept the same exact parameters in all classes that implement the method(s). So if a method takes no parameters in the interface, it must take no parameters in the classes that implement the interface. If the method takes one parameter named $length, for instance, it must take one parameter named $length in the classes that implement the interface. So this is all that is required to create and implement an interface in PHP.

Clone an Object

In this article, we go over how to clone an object in PHP. When you clone an object, you create a new object with all the same properties as the original object. There are many reasons why you would want to clone an object in PHP. Imagine you have a class named cars that represent car objects. Now imagine a car object has several properties such as car type, the year of the car, the year of the car, the color of the car, whether it's automatic or manual, what condition it is, etc. In other words, a long list of properties. Imagine it's a car salesman who's keeping a list of these cars in programming. Imagine now that another car comes to the lot. It's the same exact car as one you have. Instead of creating a new object from scratch and filling in all the properties, it would far easier and quicker just to clone the car that's the exact copy. That way, all the properties are copied or cloned onto the new created object. And it doesn't even have to be an exact copy. For example, everything could be the same, the color, car type, automatic engine, except the year is different. In this case, you close the orignal object and just change the year property. So cloning an object can be a great, quick solution when all or most of the properties are the same as the orignal object. It provides for less coding. So below in the PHP code is the general code to clone an object. $car2= clone $car1; So in the above code, we have created an object, $car2, which is a clone of $car1. So $car2 has all of the properties of $car1. We show the full PHP code so you can this demonstrated. <?php class cars { } $car1= new cars; $car1->type="Toyota Camry"; $car1->year= "2015"; $car1->color= "Green"; $car1->enginetype= "Automatic"; $car2= clone $car1; $car2->year= "2014"; echo 'Car 1: ' . $car1->type . ' ' . $car1->year . ' ' . $car1->color . ' ' . $car1->enginetype; echo "<br>"; echo 'Car 2: ' . $car2->type . ' ' . $car2->year . ' ' . $car2->color . ' ' . $car2->enginetype; ?> So in the above code, we've created a class named cars. We then create an instance (or object) of this class named $car1. We assign this $car1 object properties, such as the type, year, color, and engine type. The $car1 object is a 2015 Toyota Camry that is a green and has an automatic engine. We then create a new object, $car2, and set this equal to clone $car1. Thus, $car2 is a clone of $car1. We then modify the year property of the $car2 object. We change the year to 2014. So the $car2 object is the same as the $car1 object, except $car2 is a 2014, not 2015. This still saved us a lot of time, because we didn't have to write out all the properties again. All we had to do was change the year property. So this is all that is needed to clone an object of a class in PHP. Going back to the PHP code above, if it's run, this gives the following output shown below. Actual PHP Output Car 1: Toyota Camry 2015 Green Automatic
Car 2: Toyota Camry 2014 Green Automatic

Inspect an Object

In this article, we go over how to inspect an object in PHP. If we ever want to check all of the parameters of an object, you can use the PHP var_dump function. This lets you see everything in an object, all the properties that have been assigned to the object. The PHP var_dump() function is very similar to the PHP print_r() function, which lets you see the internal composition of an array. So below I give code on how to check an object we create called $car1. It represents a car object of the cars class. We then inspect this $car1 object using the var_dump() function. <?php class cars { public $type; public $year; public $engine; public $energy; } $car1= new cars; $car1->type= "Tesla Model 3"; $car1->year= 2017; $car1->engine= "Automatic"; $car1->energy= "Electric"; echo ""; echo var_dump($car1); echo "</pre>"; ?> So in the code above, we create a class named cars. In this class, we declare 4 property variables, $type, $year, $engine, and $energy. We then create an object of this cars class called $car1. We assign this $car1 object its type, year, engine type, and energy type. We then echo out the object using the var_dump() function. We use the <pre></pre> tags just to make the code readable. These tags separate the data into separate lines, making the code more readable. Running the PHP code yields the following output below. Actual PHP Output object(cars)#1 (4) { ["type"]=> string(13) "Tesla Model 3" ["year"]=> int(2017) ["engine"]=> string(9) "Automatic" ["energy"]=> string(8) "Electric" } So you can see the output above. It tells you the name of the object, what index it is for the objects of a class, and how many characters the name of the object is composed of. It then tells you each property that makes up an object and the value of each of the properties. For each value, it tells you what data type it is and how many characters make up the value. So the PHP var_dump function is very good for inspecting an object and, thus, can be used for troubleshooting an object. It really tells you all there is to know about an object. So this is how you can inspect an object in PHP. Related Resources How to Instantiate an Object in PHP How to Delete an Object in PHP How to Initialize an Object in PHP How to Invoke a Method On an Object in PHP How to Clone an Object in PHP How to Count the Number of Objects in a Class in PHP

Create a Class Constructor

In this article, we go over how to create a class constructor in PHP. A constructor is necessary when you want to initialize values for an object when the object is created. If you are creating an object has no default values or properties assigned to it, then you do not need to create a constructor. A default constructor is already created and called when you instantiate an object that takes in no values. However, if when you instantiate an object, you want to pass values to that object, you have to create a constructor that specifies what values the object will take in with the constructor. A constructor is a method that is called when you instantiate (create) an object. If a constructor has values in the parameters, then these are the values you need to pass to the object at the time of instantiation. So, say if we create a class named vehicle and we want to create objects of vehicles such as a car, truck, van, jeep, etc. When we create an object, we want to absolutely know the type and year of the car. For example, a toyota camry, year 2015. In a case like this, we would create a constructor that has 2 properties, $type representing the type of car and $year representing the year of the car. The general format for creating a constructor in PHP is shown below. public function __construct($type, $year) { $this->type= $type; $this->year= $year; return true; } } So the code above creates a constructor in a class that has 2 variables or properties, $type and $year. To create a constructor, we use public function or private function or protected function based on the type you want followed by 2 underscore symbols and construct (__construct). We then have the variables that we want to pass to an object when it is instantiated. Remember, the constructor is the method that is called when you instantiate an object. Based on this constructor, it determines what values and how many values you pass to the object at the point of instantiation. So when we create an object based on this constructor, we must pass the type and year of the vehicle. $this is a keyword in PHP that refers to the object being instantiated. Being that you wouldn't know the name of the object until you create it, $this refers to the name of the object you create when you create it. So since $this refers to the object, you can t think of it like replacing $this with the object name that you create. You then can see more clearly that we are assigned the property type and year to the object we created and assign them the values passed into the object when instantiated. So when we are creating a constructor in PHP, we always use the keyword $this to refer to the object we instantiate. At the time of instantiation, the $this keyword is replaced by the object name. And, thus, the object gets the values of type and price assigned to it. The values are set equal to the parameters we pass into the object when instantiated. The full PHP code to create a constructor of a class named vehicles is shown below. <?php class vehicles { public function __construct($type, $year) { $this->type= $type; $this->year= $year; return true; } } $car= new vehicles("Honda Accord", 2009); echo $car->type . " " . $car->year; ?> So in the above code, we have created a class named vehicles. We then create a public constructor with the parameters of $type and $year. This means that if we create an object in this class, we must pass along 2 parameters, the type and year of the car, or else the program will throw us warnings. Since we do not know the name of an object until we instantiate one, the keyword $this will refer to the name of the object when it is instantiated. Remember, this constructor method is called when we instantiate an object in this class. At this point, the $this keyword is replaced by the object name. Thus, the object gets assigned the property value type and year when created. And these values are based on what we pass into the parameters of the object when instantiated. Then below we actually create an object, $car, that has a type value of "Honda Accord" and the year 2009. The constructor is called. These values get passed into the $car object. We then echo out the values of the $car object based on the standard way of echoing out object properties. Taking the object name and property with "->" in between. And this is call that is required to create class constructors in PHP. Going back to the PHP code above, if it's run, this gives the following output shown below. Actual PHP Output Honda Accord 2009

Create a Class Destructor

In this article, we show how to create a class destructor in PHP. A destructor is a method in a class that is called when an object is deleted. If an object is being deleted, then PHP automatically calls the destructor method. We can do do anything at this time, including echoing out a message that the object is being deleted. We can close a database connection. Or because a destructor is called when an object is being deleted, if we are keeping track of the number of objects in a class, decrease the count by 1. So the PHP __destruct() function allows us to perform any action when an object is deleted. To create a destructor method in PHP, you use the public keyword, followed by the word function, followed by __destruct(). 2 underscores (__) precedes the word destruct(). This is shown below. public function __destruct() { //code to run } Below is a PHP program that contains a destructor method that outputs that the object is being deleted and decrements the count of a variable that stores the number of objects in a class. This is because an object is being deleted when a destructor is called, so we want to decrement the count of the objects by 1. <?php class cars { public static $count=0; public function __construct($type, $year) { $this->type= $type; $this->year= $year; cars::$count++; return true; } public function __destruct() { echo "The " . $this->type . " is being deleted" . "<br>"; cars::$count--; } } $car1= new cars("Toyota Camry", 2014); $car2= new cars("Nissan Altima", 2012); $car3= new cars("Honda Accord", 2010); $car4= new cars("Tesla Model X", 2015); $car5= new cars("Tesla Model 3", 2016); unset($car4); echo "The number of objects in the class is " . cars::$count; ?> So we create a class named cars. In the first line of this class, we define and initialize a static $count variable. This variable will keep hold of the number of objects in the class. We create a constructor method, which is a method that is called when an object is instantiated. Since the objects represent cars, 2 parameters that we pass into the constructor method are the $type and $year of the car. Based on the values passed in, we store these values into the $type and $year variables using the $this keyword. We then access the static count variable and increment it by 1. This is because the constructor is called only when a new object is instantiated. We then create the destructor method. A destructor method never accepts any arguments. So it's always destruct(). In this destructor method, we output that the object is being deleted. We also have the static property $count decrement by 1. Because this variable keeps track of the number of objects in a class and an object is now being deleted, we decrement the count by 1. Below is a list of 5 objects we create that represent cars. For each object that is created, the constructor method is called. This assigns the type and year of each car. It also increments the static $count property so that it now holds the value 5 (due to 5 objects). We then delete the $car4 object using the PHP unset() function. When this occurs, the PHP __destruct() function is automatically called. This function outputs that the object is being deleted. We also decrement the static $count property by 1, so that it now has a value of 4. And this is all that is required to make a destructor method in PHP. Again, a destructor method is called whenever an object is deleted using the PHP unset() function. It also will be called after a script ends. And this is all that is required to make a destructor method in PHP. Running the PHP code above yields the following output shown below. Actual PHP Output The Tesla Model X is being deleted
The number of objects in the class is 4 Related Resources How to Create a Class Constructor in PHP How to Delete an Object in PHP

Overloading Constructors

Sorry, my fellow PHPeople, but as of today of me writing this (July 23, 2016), PHP (Version 7) does not support the overloading of constructors. I'm not knocking PHP in any way. I'm the biggest PHP fan. Most of this website was written in PHP, but it doesn't yet support the overloading of constructors. I tried running a program in which I had 2 constructors (__construct methods). The 2 methods had different parameters or arguments. However, what happened was the program output a fatal error, such as shown below. Fatal error: Cannot redeclare vehicles::__construct() This was the complete program that I ran, shown below. <?php class vehicles { public function __construct($type, $year) { $this->type= $type; $this->year= $year; return true; } public function __construct($type, $year, $engine) { $this->type= $type; $this->year= $year; $this->engine= $engine; return true; } } $car= new vehicles("Honda Accord", 2009); $car2= new vehicles("Honda Accord", 2009, "automatic"); echo $car->type . " " . $car->year; echo $car2->type . " " . $car2->year . " " . $car2->engine; ?> You can see that I have 2 constructors (__construct methods) in the class vehicles. Each constructor has different parameters. However, PHP outputs that you can't redeclare the __construct method within a given class, meaning you cannot overload constructors. So PHP, though it has great object oriented ability and has come a long way from PHP4 to PHP5, it does not yet have the OOP capability of Java, for instance, which does support constructor overloading. But again, this may change in future versions and I'm almost sure it will be updated. However, as of now, it does not yet support constructor overloading directly. I'm not sure if there's any ways or tricks around it. I don't know of any. But as of direct constructor overloading, PHP does not yet support this. Note: If you are reading this article and PHP has added functionality so that constructors can be overloaded, please write a comment below and I'll get to it and update this article. Thank you. It would be much appreciated. Related Resources How to Create a Final Class in PHP

Create and Access Static Properties and Methods

In this article, we go over how to create and access static properties and methods in PHP. For example, in a class, we can define properties and methods that are static. A static method or property is one that can be used without creating an object first. So, with a regular, non-static method used in a class, you must create an instance (or object) of the class before you can call the method. The method can only be used by being invoked upon an object. This takes the form, object->method(). The same is true for a regular, non-static property or variable. Before the property can be accessed, an object must be created in the class. Only through the object could the property be accessed. This takes the form, object->property. However, with a static method or property, the method or property is independent of the object. The static property is a variable that belongs to the class only, not any object. So the property does not belong or is tied to any object. A static method is a method that is not invoked on any object. It is simply an independent method from any objects. Therefore, when you are creating a static method, inside of it there is no mention of the keyword $this. The keyword $this is used only for non-static methods, since it refers to an object. Since there is no object with static methods, there is no use of the keyword $this. Static properties are often seen in libraries where the functionality is independent of any object properties. It can be seen as a property separate from the object properties. Static methods, similarly, can be seen as outsiders to objects. Being that they aren't directly invoked on objects, they can be used for outside tasks such as getting the number of objects created in a class, for example. Static Properties So now we show how to create static properties inside of a class in PHP. To create a static property, you add the static keyowrd just before the property name. Below is an example. class thisClass { public static $number=20; } So the above is a static property named $number. We set it equal to 20. To access a static property, you write the class name, followed by 2 colons (::) followed by the property name (preceded by a $ symbol). So the code below shows how to access and output the static property $number of the class thisClass. echo thisClass::$number; So now we output the static property $number. Static Methods So now we show how to create static methods inside of a class in PHP. To create a static method, you add the static keyowrd just before the method name. Below is the general format to do so. class thisClass { public static function move() { echo "Move this box"; } } So the above is a static method named move(). Inside of this method is the line echoing, "Move this box". To call a static method, you write the class name, followed by 2 colons (::) followed by the method name, which includes the parentheses (). So the code below shows how to call the move() method of the thisClass class. thisClass::move(); Full PHP Code So below is PHP code that creates a static object and a static method. We then output the static property and call the method, so that you can see how to do so. <?php class kids { //static property public static $number=20; //static method public static function move() { echo "Get up kids"; } } //output static property echo kids::$number; echo "<br>"; //call static method kids::move(); ?> So in the above code, we create a class named kids. The first thing we do in the class is create a public static property named $number and set it equla to 20. Right underneath is we create a public static method named move(). Inside of this move() method, we output the line, "Get up Kids". We then output the static property $number. This is done through using the class name, followed by 2 colons (::), followed by the property variable. This outputs 20, which is what this property is set to. We then have a break line just for spacing to make the output more readable. We then call the move() method by using the class name, followed by 2 colons (::), followed by the method name. This outputs "Get up kids". Running the above PHP code above yields the following output below. Actual PHP Output 20
Get up kids

Count the Number of Objects in a Class

In this article, we go over how to count the number of objects in a class in PHP. Every time we instantiate (create) a new object, we can keep track of this through a static property. Thus, we can count the number of objects instantiated for a given class. As far as I know, PHP does not have a built-in function that counts the number of objects in a class, so we simply create a custom one and it's very easy to do. We create a static property (since it isn't tied to an object but to the class) and we put inside of the constructor. Since the constructor is called every time that an object is instantiated, we add increment the static property keeping count by 1 each time an object is instantiated, we can keep track of the number of objects in a class. So in the PHP code below, we have created a program that counts the number of objects created for a class in PHP. <?php class cars { public static $count=0; public function __construct($type, $year) { $this->type= $type; $this->year= $year; cars::$count++; return true; } } $car1= new cars("Toyota Camry", 2014); $car2= new cars("Nissan Altima", 2012); $car3= new cars("Honda Accord", 2010); $car4= new cars("Tesla Model X", 2015); $car5= new cars("Tesla Model 3", 2016); echo "The number of objects in the class is " . cars::$count; ?> So in this code, we create a class named cars. We declare a public static property named $count and we set it equal to 0. This variable will be used to count the number of objects created in a class. We then create the constructor for the class. Since this is a class that represents cars, each object created is a car object (represents a car). We want to pass into the car objects the type and year of the car. So in the constructor, we pass in the arguments $type and $year, representing the type and year of the car. We then use the $this keyword to assign the value of the type and year to the $type and $year variables. We then use the increment operator to increment the cars::$count property. Because the constructor is called each time an object is created, we can use this fact to keep track of how many objects are created. Initially, the cars::$count variable is 0. However, with each object that is instantiated, the count goes up by 1. Thus, we're able to know how many objects have been created. Since we've created 5 cars, at the end of this program, you'll see that the program says there are 5 objects created. Actual PHP Output The number of objects in the class is 5 Keeping Count of the Number of Objects If Any Are Deleted You could make this program a little more elaborate. For example, what if an object is destroyed? What if we delete one or more of the objects after they are created? In that case, you would also have to make a destructor function for the class. When an object is destroyed (if you unset an object) then you place in the destructor function, a decrement operator for the cars::$count variable. So if an object is destroyed, the count goes down by 1. This way, you can keep track of how many objects currently exist for a class. So below is the code that keeps track of all currently existing objects in a class. If an object is created, the count goes up by 1. If an object is destroyed, the count goes down by 1. <?php class cars { public static $count=0; public function __construct($type, $year) { $this->type= $type; $this->year= $year; cars::$count++; return true; } public function __destruct() { cars::$count--; } } $car1= new cars("Toyota Camry", 2014); $car2= new cars("Nissan Altima", 2012); $car3= new cars("Honda Accord", 2010); $car4= new cars("Tesla Model X", 2015); unset($car4); $car5= new cars("Tesla Model 3", 2016); echo "The number of objects in the class is " . cars::$count; ?> So all the code is mostly the same except now we have a class destructor and we intentionally delete an object, $car4. Inside of the destructor, we have the cars::$count variable decrementing by 1 each time the destructor is called. And the destructor function is called when we delete an object through the PHP unset() function. So whenever we delete an object, the count goes down by 1. So now when we run our code, now that we've deleted one of the objects, the count will be 4. So if I run the PHP code above, we get the following output below. Actual PHP Output The number of objects in the class is 4 So using a static variable is a very effective and easy way to keep track of the number of objects in a class. Because a static variable isn't tied to an object and is instead tied to a class, it is independent of any object in the class. Therefore, it has an outsider view, so to speak, and can keep track of all objects in a class. So this is how you can keep track of the number of objects in a class in PHP.

Autoload Classes

In this article, we show how to autoload classes in PHP. This means that we automatically load class files into a PHP script so that they can be used, even though they aren't in the current PHP script. It's a lot like the include or require PHP functions, in that it includes another PHP script in the current script, as if that external PHP file was written into the current script. But it's a bit different in that it gets that script and looks specifically for a class that you mention. With autoloading, you create an __autoload() function somewhere in your script. This function should accept a classname as an argument. Then, whenver your script attempts to create a new object from a class that doesn't exist in your current script, __autoload() is automatically called, passing in the class name. This allows your __autoload() functcion the opportunity to find and include the class file, thereby allowing the PHP script to carry on and create the object you are trying to create with the class name you have used. So, again, the __autoload() function is called if the PHP script cannot find the class you are referencing when you are creating an object of a class. If not in the current script, it looks for it in the PHP file you specify in the __autoload() function. The function stores the name of the nonexistent class in a $classname parameter. You then would normally use a require or require_once function to include the script in the function. The function will then go through the script to find the class name you specified. So let's go through an example now of an autoload function. __autoload() Function Code The following below is a very common and used __autoload() function example. <?php function __autoload($classname) { require_once("$classname.php"); } $elephant1= new elephant; echo "This elephant is " . $elephant1->color; ?> So you can see that this is one PHP file. In this PHP file, we have an __autoload() function that accepts a $classname parameter which represents the class name of any object we are trying to instantiate. In this example, we try to instantiate the object $elephant1 through the elephant class. So elephant then becomes the $classname parameter passed into the __autoload() function. Since there is no elephant class in the current script, the __autoload() function is automatically called, so that this elephant class can be found. Inside of this elephant.php file must be our elephant class. So if we have an elephant.php file with the elephant class, this file should work. So now let's look at the elephant.php file shown below. <?php class elephant { public $color= "brown"; } ?> You can view the contents of this at the following link: elephants. So now look at this elephant.php file, you can see it has an elephant class, what we are looking for. Inside of this elephant class, we have a public property of $color equal to the value of brown. This is in the elephant class. Going back to the PHP file with the __autoload function, we are able to create the $elephant1 object because the elephant class has been found. The $elephant1 object has now been instantiated. Since the elephant class has the property $color equal to brown, we output that the $elephant1 object is brown. And this is how the PHP __autoload() function works. It's always a good practice to name a PHP file and class the same name. And it's a good idea to keep one class per file. So if you are creating a Toy class, you would put in a separate Toy.php file. This makes for good organization. And this makes the __autoload function work. So the __autoload function would not work above if the file and class name were different. If you need to use more than one class, nothing changes with the __autoload function. For each occurrence of a new class it meets in the code, it will invoke the __autoload() function. So if you have multiple statements that call classes that aren't in your current script, then each time a new class is called, the __autoload() function will be invoked in order to try and find that class. An example of object instantiation from multiple classes can be found at the following link: Multiple Classes. If the PHP script can't find an __autoload() function or if your __autoload() function fails to find the class in the file specified, the script withts with a Class Not Found error. So going back to the original PHP script above, if this is run, this yields the following output shown below. Actual PHP Output This elephant is brown Related Resources How to Write JSON with PHP

Read JSON

In this article, we show how to read JSON data with PHP. JSON stands for JavaScript Object Notation. It began as a way to represent objects in Javascript, but along the way, many modern programming languages have built-in support for working with JSON. PHP is one of those languages that has built-in support for working with JSON, whether reading JSON data or writing JSON data. JSON is a lightweight format; the size of the data packet is small and it is simple, which makes it fast and easy to process. This way, you can include web service content in your web page. You can also use AJAX requests to read JSON data asynchronously. JSON is a good choice for mobile device applications; its small size and simple format allows for fast transfer of data, as well as placing minimal strain on the client device to decode it. So we'll see in this article how to read JSON data with PHP. So below we show the code how to read (decode) JSON data using PHP. <?php $jsonData= '[ {"title":"The Wandering Oz", "PublicationDate":2007}, {"title":"The Roaming Fox", "PublicationDate":2009}, {"title":"The Dominant Lion", "PublicationDate":2012} ]'; $books= json_decode($jsonData, true); echo ""; print_r($books); echo "</pre>"; ?> So, first, in the code above we create JSON data. We create book objects (objects that represent books). And for each book object, we specify what the title property is and what the publication data property is. So this is data in JSON format. We now want to read this JSON data using PHP. To read JSON data, PHP has a built-in function, the json_decode() function, which converts JSON data into a PHP associative Each object in the array is converted into an element of the PHP associative array. The first book titled, "The Wandering Oz" is element 0. The second book is titled "The Roaming Fox" and it is element 1 in the array. The third book, titled "The Dominant Lion", is element 2. We then use the print_r() function to show the contents of the PHP array. We place the <pre></pre> tags in between the print_r() function just to make the result more readable. The output of the PHP code above is shown below. Actual PHP Output Array ( [0] => Array ( [title] => The Wandering Oz [PublicationDate] => 2007 ) [1] => Array ( [title] => The Roaming Fox [PublicationDate] => 2009 ) [2] => Array ( [title] => The Dominant Lion [PublicationDate] => 2012 ) ) Related Resources How to Write JSON with PHP

Write JSON

In this article, we show how to write JSON data with PHP. JSON stands for JavaScript Object Notation. It began as a way to represent objects in Javascript, but along the way, many modern programming languages have built-in support for working with JSON. PHP is one of those languages that has built-in support for working with JSON, whether reading JSON data or writing JSON data. JSON is a lightweight format; the size of the data packet is small and it is simple, which makes it fast and easy to process. This way, you can include web service content in your web page. You can also use AJAX requests to read JSON data asynchronously. JSON is a good choice for mobile device applications; its small size and simple format allows for fast transfer of data, as well as placing minimal strain on the client device to decode it. So we'll see in this article how to write JSON data with PHP. So below we show the code how to write (encode) JSON data with PHP. <?php $books= array(array("title" => "The Wandering Oz", "PublicationDate" => 2007), array("title" => "The Roaming Fox", "PublicationDate" => 2009), array("title" => "The Dominant Lion", "PublicationDate" => 2012) ); echo json_encode($books); ?> So, first, in the code above we create an array which contains arrays. We assign this to the variable $books, since it is made up of arrays representing books. Within each of the arrays is the title property and the PublicationDate property. These hold the value of the title and the publication date of each book. So the PHP equivalent of a JSON representation. To actually encode this in JSON, we use the built-in PHP json_encode() function. This turns the PHP arrays within an array into JSON data, Javascript objects. So it really is as simple as creating a PHP arrays within an overlapping parent array. This data can then be converted into JSON with the PHP built-in json_encode() function. So PHP makes it very easy to work with JSON with its built-in capabilities. Thus, PHP and JSON work very well with each, similarly how PHP works well with other technologies, seemingly flawlessly such as MySQL. So taking the PHP code above, we get the following output shown below. You can see how it's in beautiful JSON format. Actual PHP Output [{"title":"The Wandering Oz","PublicationDate":2007},{"title":"The Roaming Fox","PublicationDate":2009},{"title":"The Dominant Lion","PublicationDate":2012}] Related Resources How to Read JSON with PHP

Parse JSON

In this article, we show how to parse JSON data with PHP. By parsing through JSON data, this means that we are able to sort through it and look for what we want from the JSON data. 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. So below we show the code how to access JSON data using PHP. <?php $jsonData= '[ {"name":"Bill Smith", "city":"Fort Lauderdale", "state":"Florida"}, {"name":"Vanessa Halls", "city":"New York City", "state":"New York"}, {"name":"Ryan Mitchells", "city":"Miami", "state":"Florida"} ]'; $people= json_decode($jsonData, true); //Access all of the JSON Data echo $people[0]["name"] . "<br>"; echo $people[0]["city"] . "<br>"; echo $people[0]["state"] . "<br>
"; echo $people[1]["name"] . "<br>"; echo $people[1]["city"] . "<br>"; echo $people[1]["state"] . "<br>
"; echo $people[2]["name"] . "<br>"; echo $people[2]["city"] . "<br>"; echo $people[2]["state"] . "<br>
"; ?> So, we first have json data stored in the variable $jsonData. PHP cannot read or handle json data, as is. So it converts the json data into something that PHP can understand through the json_decode function. The json_decode() function is a built-in PHP function that converts JSON data into a multidimensional PHP array. We then can handle all of the data after the json_decode function like a multidimensional array (which it now is). So in the above, we output all of the data of by accessing each individual data item in the multidimensional array. Running the above PHP code, we get the following output shown below. Actual PHP Output Bill Smith
Fort Lauderdale
Florida

Vanessa Halls
New York City
New York

Ryan Mitchells
Miami
Florida So we can access all of the data individually that we want through the above code, but this is not really parsing through the data. Let's say we are actually looking for something specific. We want to find all people who live in the state of Florida. To do this we use the following PHP code below. <?php $jsonData= '[ {"name":"Bill Smith", "city":"Fort Lauderdale", "state":"Florida"}, {"name":"Vanessa Halls", "city":"New York City", "state":"New York"}, {"name":"Ryan Mitchells", "city":"Miami", "state":"Florida"} ]'; $people= json_decode($jsonData, true); $count= count($people); //Access any person who lives in Florida for ($i=0; $i < $count; $i++) { if ($people[$i]["state"] == "Florida") { echo $people[$i]["name"] . "<br>"; echo $people[$i]["city"] . "<br>"; echo $people[$i]["state"] . "<br>
"; } } ?> So we have the same JSON data as before of people their name, city, and state. We then decode this JSON data through the json_decode() function, which creates a multidimensional PHP array. We have the number of elements in the array, so that we know how many people it's composed of (we need this later for the for loop). We place this value in the variable $count. We then creat a foor loop. Since arrays begin at element 0, this for loop starts at the value of 0. It counts up 1 value after each iteration. When it gets one less than the count of the number of elements in the array, this means it has looped through all elements in the array. We then want to know which of these people live in Florida. So we access the state of each person through the code, $people[$i]["state"]. If this value is equal to Florida, then we know that that person lives in Florida. If this is the case, we echo out all values of that person, including the name, city, and state of that person. And this is how we can parse JSON data with PHP. So, as a recap, first we must take the json data and decode it through the json_decode() function. This converts the json data to a PHP multidimensional array. Then we can just handle the data as you would a multidimensional array. You can access a particular value in an array and use the standard programming methods to extract data, such as through using for loops. If I take the above PHP code and run it, I get the following output shown below. Actual PHP Output Bill Smith
Fort Lauderdale
Florida

Ryan Mitchells
Miami
Florida So now you see how you can access any element and use for loops. If we want to see whether a person has the name "Vanessa Halls" from the JSON data and output her city and state, we can use the following PHP code. //Find if there is a Vanessa Halls and output her city and state for ($i=0; $i < $count; $i++) { if ($people[$i]["name"] == "Vanessa Halls") { echo $people[$i]["city"] . "<br>"; echo $people[$i]["state"] . "<br>
"; } } ?> So this finds if there is a person named Vanessa Halls and finds her city and state. Running the full PHP code gives us the following output. Actual PHP Output New York City
New York So, by now, you can pretty much see the trend of how you can manipulate what was originally JSON data and convert it to PHP through the json_decode() function. This data gets converted from JSON to a PHP multidimensional array. We then can parse through this data as you would any PHP multidimensional array. So this is an easy way to parse JSON with PHP. Related Resources How to Write JSON with PHP How to Write JSON with PHP

Access the Google Maps API in JSON Format

In this article, we go over how to access the google maps API encoded in JSON format with PHP. JSON is Javascript Object Notation. PHP has built-in functions that allows it to work easily with JSON data. We'll show how to obtain JSON data from the google maps API and work with it in PHP. So in this example code that we'll make, we will extract the latitude and longitude of a city using the google maps API. So we put in a location, such as Detroit Michigan, and we will get the latitude and longitude values associated with Detroit Michigan from the google maps API. So to access the google maps API, the URL is, https://maps.googleapis.com/maps/api/geocode/json?address=detroit,michigan So the hyperlink above brings us to the google maps API where the address is detroit, michigan. The generic link to access the google maps API page of any location is, https://maps.googleapis.com/maps/api/geocode/json?address= After the word address, you simply put in the location that you want to enter. This can be any type of location such as a state or a city in a state or a full street address. You can really put anything after address. Using this base URL, we can have a user enter in an address, concatenate it to the above URL, putting in the address in the URL, retrieve the page with PHP, decode the JSON data with PHP, and then extract the data that we want from the API. As said before, we will extract the latitude and longitude associated with the address. So let's go on to the code necessary to do this. This is shown below. We'll separate it into blocks. First Block of PHP Code So the first block of PHP code does the majority of the work as far as PHP code is concerned. It takes the address from the form that a user has entered and puts into the URL representing the google maps API. It then retrieves the page, decodes the JSON data, and extracts the latitude and longitude value from the google maps API. <?php $location= $_POST['location_entered']; //extracts data from text box representing the address if (!empty($location)) { $url= 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($location); $jsoncontent= file_get_contents($url); $decodedarray= json_decode($jsoncontent, true); $latitude= $decodedarray['results'][0]['geometry']['location']['lat']; $longitude= $decodedarray['results'][0]['geometry']['location']['lng']; } ?> So we'll go through the code above. So we create a PHP variable named $location. We use the PHP superglobal array, $_POST to extract the data from the text box with the address that the user has entered in. So now we have the address that the user has entered in. We then create an if statement so that we can know whether the data has been entered into the text box or not. We do not want the following code to run if the text box is empty. We then create the a $url variable. This holds the URL of the google maps api for the address entered in. We have the base of the URL and then we have in the address ($location variable) by the concatenator. We put it in a urlencode() function so that if the user enters spaces in the address, this is accounted for. We then create a variable called $jsoncontent. THis holds the all of the data produced in the goole maps api. Since this data is in JSON format, I call this data $jsoncontent. Next, we decode the json data with the PHP json_decode() function. This converts the JSON data into a PHP array. Lastly, we extract the latitude and longitude values from this google maps api data. Since the latitudes and longitudes are found under the first element of results, this is located in ['results'][0]. Under results, it is found in geometry. Under geometry, it is found in location. In location, the attribute is lat for latitude and lng for longitude. We create the PHP variable $latitude and $longitude and set them equal to these points. HTML Code Next we have the HTML code that we need so that we can create a form where a user can enter the address into. It's a very simple form that just has a text box for entering the address and a submit button for submitting the data through. <form action="" method="POST"> Enter An Address to Find Latitude and Longitude Values: <input type="text" name="location_entered" value='<?php echo $location; ?>'/><br> <input type="submit" name="Submit" value="Submit"/> </form> So here we have a form. Since we want the form to submit the data input into to this current page, we leave the action attribute empty. Therefore, the data entered into the form stays on this page. The method is POST, since we don't need it appended to the current page's URL. Instead we want it appended to the URL we have in the code. Using POST, therefore, is better than using GET. We then create the text box and assign it the name location_entered. We set its value equal to $location, which is the PHP variable that stores the address that the user has entered. This is so that we can see the address that the user has entered into the text box even after the submit button is clicked. We then have a submit button so that the form can be submitted to the server. This concludes the HTML code. Second Block of PHP Code We then have our last block of PHP code, which is very simple, put underneath the text box. <?php if (!empty($location)) { echo "Latitude: $latitude" . "<br>"; echo "Longitude: $longitude" . "<br>"; } ?> The last block of PHP simply outputs the latitude and longitude for the address that has been entered in. And this concludes how we can use the google maps API to get data in JSON format such as the latitude and longitude of an address. All it is is a matter of knowing the URL of the google maps API and how you can enter an address and append it to the URL to get the data on the address you want. You then work with the data as you would with any JSON data with PHP. So this is how it is done when the API is presented in JSON format. You can also do the same exact thing if the data is in XML format. To see how to use the google maps API with the data in XML format to access information, see How to Access the Google Maps API in XML Format with PHP. Related Resources How to Obtain the Zip Code from the Google Maps API Using PHP

Create an XML Document

In this article, we show how to create an XML document with PHP. This means that we use PHP code to write the contents of an XML document. This can be done in actually a few ways. The 2 most popular ways to write XML code is through the SimpleXML extension or the DOM extension. Both are effective ways of creating XML content via PHP. The DOM can be described as more powerful and complex, while SimpleXML is simpler. Below we show how to create an XML document using PHP through the SimpleXML extension. <?php $simplexml= new SimpleXMLElement('<?xml version="1.0"?>'); $book1= $simplexml->addChild('book'); $book1->addChild("booktitle", "The Wandering Oz"); $book1->addChild("publicationdate", 2007); $book2= $simplexml->addChild('book'); $book2->addChild("booktitle", "The Roaming Fox"); $book2->addChild("publicationdate", 2009); $book3= $simplexml->addChild('book'); $book3->addChild("booktitle", "The Dominant Lion"); $book3->addChild("publicationdate", 2012); echo $simplexml->asXML(); ?> So the first thing we do in this code is to create the $simplexml variable. This creates a new XML element, where we declare the document to be an XML document of version 1.0. We then create the root elment, books. We then create the first element within the root element, book. We create a variable named $book1 and add the element, book. Within this book element, we add the booktitle element with the contents in between the booktitle tags being "The Wandering Oz". We then add the publicationdate element with the contents in between the publicationdate tags being 2007. We then go onto the next book element. We again add the child element book. To this book element we add the booktitle element with the contents of "The Roaming Fox". We then add the publicationdate element with the contents being 2009. We then create one last book element. We add a booktitle element with the contnets of "The Dominant Lion" and a publicationdate element with the contents being 2012. We then echo out all of these XML instructions through the statement, $simplexml->asXML(). This displays all of the tags we entered and actually renders it as XML. Being that the XML declaration has to go to the top of the page of a web document, I can't show how it would render by placing the PHP below. Instead, I have to create a new PHP file with solely this code in it. That way, the XML declaration is at the top of the page. Doing so yields the following PHP page: books.php. ?> Creating a Separate XML Document The following code above is great and generates XML. However, the XML data is generated on a PHP page. This is probably not what you want. However, you more than likely want XML generated on a complete and separate XML page. This way, it's just as if you created an XML document (with .xml extension) and wrote it complete with XML tags. To do this, the following code above, just needs a slight modification. We add in the file_put_contents() function into the code and into this function we create a separate XML file called books.xml. This is all shown below. <?php $simplexml= new SimpleXMLElement('<?xml version="1.0"?>'); $book1= $simplexml->addChild('book'); $book1->addChild("Booktitle", "The Wandering Oz"); $book1->addChild("PublicationDate", 2007); $book2= $simplexml->addChild('book'); $book2->addChild("Booktitle", "The Roaming Fox"); $book2->addChild("PublicationDate", 2009); $book3= $simplexml->addChild('book'); $book3->addChild("Booktitle", "The Dominant Lion"); $book3->addChild("PublicationDate", 2012); file_put_contents('books.xml', $simplexml->asXML()); ?> So you can see now we have most of the code we previously had, but instead of echoing the contents of the XML tags we wrote onto the current PHP page, we use the file_put_contents() function to create an XML file named books.xml. We then write the contents of the XML tags we wrote into this books.xml file. So we now have a separate XML document. The following link shows this XML document: books.xml. You can see how it's a perfect-looking XML document that has been generated through PHP. This is the power of PHP and XML. PHP has built-in code that allows you to work very well with XML. The advantage of using this code is that you generate dynamic XML on the fly with PHP. You don't simply have to write XML code. XML code can be generated dynamically through a dynamic language such as PHP. Related Resources How to Read JSON with PHP

Read XML

In this article, we show how to read XML, either an XML file or a string containing XML, with PHP. This means that we use PHP code to read the contents of an XML document or a string containing XML. We'll show how to do these things below. Reading an XML File First, we'll go over how to read an XML file. This is a file with a .xml extension that contains full XML code. A regular, typical XML file. There's many ways that this can be done, but probably the easiest way to read an XML file with PHP is to use the simplexml_load_file() function. Inside the parameters of this function, you specify the XML document or file that you want to read. This function loads the entire document into memory and then you can display the document using the PHP print_r() function which is able to show the contents of the array. As an example XML file, I have an XML named books.xml. This is an XML file that contains book elements which show the title and the publication date of each book. We will be reading this file as our example code shown below. PHP Code The PHP code to read the contents of the XML file, books.xml, is shown below. <?php $file= simplexml_load_file('books.xml'); echo ""; print_r($file); echo "</pre>"; ?> So, in this code, we create a variable named $file and set it equal to the simplexml_load_string('books.xml); This loads in the books.xml function into memory. We then print out the contents of the $file variable which holds the XML document using the PHP print_r() function. The print_r() function is a function which can show us the contents of a PHP array. So running the above PHP yields the following output below. Actual PHP Output SimpleXMLElement Object ( [book] => Array ( [0] => SimpleXMLElement Object ( [Booktitle] => The Wandering Oz [PublicationDate] => 2007 ) [1] => SimpleXMLElement Object ( [Booktitle] => The Roaming Fox [PublicationDate] => 2009 ) [2] => SimpleXMLElement Object ( [Booktitle] => The Dominant Lion [PublicationDate] => 2012 ) ) ) So the above PHP output is the output that we get when we read the XML file, books.xml, with the simplexml_load_file() function. Looking at this output, you can see that PHP converts the XML document into an array. So the simplexml_load_file() takes the elements from the XML file and puts them in an array. The <pre></pre> tags makes the output very readable. The first element of the root element books is book that has a title of "The Wandering Oz" and a publication date of 2007. So you can see [0] next to this set of data. The second element has a title of "The Roaming Fox" and a publication date of 2009. So you can see [1] next to this set of data. The third element has a title of "The Dominant Lion" and a publication date of 2012. So you can see [2] next to this set of data. So this is how with the simplexml_load_file() function, we can read an XML file with PHP. Reading a String Containing XML Now that we've shown how to read an XML file, we'll now show how to read a string containing XML. PHP also has a built-in function, simplexml_load_string(), that can read a string containing XML. It works in the same way as the simplexml_load_file() function except that it reads a string instead of a file. This is demonstrated in the code below. <?php $classics= ' Jurassic Park 1993 Home Alone 2 1992 '; $read= simplexml_load_string($classics); echo ""; print_r($read); echo "</pre>"; ?> So with this PHP code above, we read the XML string contained in the variable $classics. We read this string using the simplexml_load_string() function and place the variable holding the string, $classics, into this function as the parameter. We then output the result using the PHP print_r() function, just as before. And as before, we use the pre tags for better formatting and readability. Below is the results of this PHP output. Actual PHP Output SimpleXMLElement Object ( [movie] => Array ( [0] => SimpleXMLElement Object ( [movietitle] => Jurassic Park [year] => 1993 ) [1] => SimpleXMLElement Object ( [movietitle] => Home Alone 2 [year] => 1992 ) ) ) Related Resources How to Create an XML Document with PHP How to Parse an XML Document Using PHP

Parse an XML Document

In this article, we show how to parse an XML document using PHP. PHP is a powerful language that can extract the information you need from an XML document. It's actually very simple. Say, for example, there is an API written in XML and you want to extract data from it. You can do this with PHP. In this example, we're going to extract information from a simple XML document that lists the contact information of 3 different people. Each person has a unique id. And for each person, we have their name, email, and phone number. The XML document that we are going to parse can be found at the following link: contacts.xml. So we'll show now how to use PHP to extract from the fields of the person element. PHP Code So we use the following PHP code to extract the name, email, and phone number of each person on the XML document. <?php $xmlload= simplexml_load_file('contacts.xml'); foreach($xmlload->person as $person) { $name= $person->name; $email= $person->email; $phonenumber= $person->phonenumber; $city= $person->city; $state= $person->state; echo "name: $name
email: $email
phone number: $phonenumber
city: $city
state: $state

"; } ?> The $xmlload variable is set equal to the simplexml_load_file() function. Inside of this function, we put the XML document that we want to parse. Since the XML document that I want to parse is contact.xml, we put this inside of this function. The simplexml_load_file() function can take relative paths or absolute paths. So if the XML is located on an external site, which is going to be the case the majority of the times, you put the absolute pathway to the file inside of this function . This function loads the XML document that you want to parse. We then make a foreach loop. This loops through all the person elements in the XML document. Inside of this foreach loop, we put the name of the element we want to find each of in the document. In this case, we want to loop through each person element in the XML document. We then use the as keyword to save each occurrence as the PHP variable $person. We then create a PHP variable for all the elements within the person element. We create a variable for the name, email, phonenumber, city, and state elements. The $person element represents the person element we are accessing. We then use "->" and specify the element within this person element that we want the data of. This is how we extract all the data within the elements of the person element. We then echo out the results. So using the XML document above, the PHP output is shown below. Actual PHP Output name: John Smith
email: Johnsmith@gmail.com
phone number: (111)111-1111
city: Miami
state: Florida

name: Peter Phils
email: Peterphils@gmail.com
phone number: (222)222-2222
city: New York City
state: New York

name: Michael Thoms
email: Michaelthoms@gmail.com
phone number: (333)333-3333
city: Daytona Beach
state: Florida Parsing for More Specific Data Let's say you don't want to output every person. You instead want to find every person that lives in Florida and only output their information. The following PHP code does this below. <?php $xmlload= simplexml_load_file('contacts.xml'); foreach($xmlload->person as $person) { $name= $person->name; $email= $person->email; $phonenumber= $person->phonenumber; $city= $person->city; $state= $person->state; if ($state =="Florida") { echo "name: $name
email: $email
phone number: $phonenumber
city: $city
state: $state

"; } } ?> So now we've shown how to parse data from an XML document and only extract data that matches a certain criterion. Now we only show people who live in Florida from an XML document. We loop through all the person elements and use a simple if statement to see if the state equals Florida. The PHP output of the above code is shown below. Actual PHP Output name: John Smith
email: Johnsmith@gmail.com
phone number: (111)111-1111
city: Miami
state: Florida

name: Michael Thoms
email: Michaelthoms@gmail.com
phone number: (333)333-3333
city: Daytona Beach
state: Florida How to Parse an Attribute of an Element Now that you know how to parse elements of an XML document using PHP, we now show how to parse an attribute of element. Going back to our example XML document, the only attribute we use is the id attribute. This ranges from 1 to 3 for the 3 individual people. To parse an attribute of an element, the PHP code to do is shown below. $id=$person['id']; Instead of using "->" like when accessing an element, to access an attribute, [] is used. So the full PHP code to show all person elements along with the ID attributes is shown below. <?php $xmlload= simplexml_load_file('contacts.xml'); foreach($xmlload->person as $person) { $name= $person->name; $email= $person->email; $phonenumber= $person->phonenumber; $city= $person->city; $state= $person->state; $id=$person['id']; echo "name: $name
id: $id
email: $email
phone number: $phonenumber
city: $city
state: $state

"; } ?> Now all the id attributes will be printed as well. Actual PHP Output name: John Smith
id: 1
email: Johnsmith@gmail.com
phone number: (111)111-1111
city: Miami
state: Florida

name: Peter Phils
id: 2
email: Peterphils@gmail.com
phone number: (222)222-2222
city: New York City
state: New York

name: Michael Thoms
id: 3
email: Michaelthoms@gmail.com
phone number: (333)333-3333
city: Daytona Beach
state: Florida So this is all the basics of parsing a basic XML document using PHP. This is done through SimpleXML, which makes it easy for PHP to interact with XML. This can be used in all types of applications, such as when you want to read a configuration file written in XML or parse an RSS feed.

Access the Google Maps API in XML Format

In this article, we go over how to access the google maps API encoded in XML format with PHP. XML stands for Extensible Markup Language and it is a very popular type of data exchage used on the web for a variety of things, including as functioning as a data exchange format language for APIs. PHP has built-in functions that allows it to work easily with XML data. We'll show how to obtain XML data from the google maps API and work with it in PHP. So in this example code that we'll make, we will extract the latitude and longitude of a city using the google maps API. So we put in a location, such as Honolulu, Hawaii, and we will get the latitude and longitude associated with Honolulu, Hawaii from the google maps API. So to access the google maps API, the URL is, https://maps.googleapis.com/maps/api/geocode/xml?address=honolulu,hawaii So the hyperlink above brings us to the google maps API where the address is Honolulu, Hawaii. The generic link to access the google maps API page of any location is, https://maps.googleapis.com/maps/api/geocode/json?address= After the word address, you simply put in the location that you want to enter. This can be any type of location such as a state or a city in a state or a full street address. You can really put anything after address. Using this base URL, we can have a user enter in an address, concatenate it to the above URL, putting in the address in the URL, retrieve the page with PHP, decode the JSON data with PHP, and then extract the data that we want from the API. As said before, we will extract the latitude and longitude associated with the address. So let's go on to the code necessary to do this. This is shown below. We'll separate it into blocks. First Block of PHP Code So the first block of PHP code does the majority of the work as far as PHP code is concerned. It takes the address from the form that a user has entered and puts into the URL representing the google maps API. It then retrieves the page, loads in the XML data, and extracts the latitude and longitude value from the google maps API. <?php $location= $_POST['location_entered']; if (!empty($location)) { $url= 'https://maps.googleapis.com/maps/api/geocode/xml?address=' . urlencode($location); $xmlcontent= file_get_contents($url); $xmlload= simplexml_load_string($xmlcontent); $latitude= $xmlload->result->geometry->location->lat; $longitude= $xmlload->result->geometry->location->lng; } ?> So we'll go through the code above. So we create a PHP variable named $location. We use the PHP superglobal array, $_POST to extract the data from the text box with the address that the user has entered in. So now we have the address that the user has entered in. We then create an if statement so that we can know whether the data has been entered into the text box or not. We do not want the following code to run if the text box is empty. We then create the a $url variable. This holds the URL of the google maps api for the address entered in. We have the base of the URL and then we have in the address ($location variable) by the concatenator. We put it in a urlencode() function so that if the user enters spaces in the address, this is accounted for. We then create a variable called $xmlcontent. THis holds the all of the data produced in the goole maps api. Since this data is in XML format, I call this data $xmlcontent. Next, we load the data into the memory of our file using the PHP simplexml_load_string() function. This method loads the content obtained in the $xmlcontent variable, which is the content retrieved by the PHP file_get_contents() function. Even though it's already retrieved in by the PHP file_get_contents() function, it isn't loaded in in simple XML format. Therefore, we have to then pass this data into the simplexml_load_string() function. We now have all of the XML data ready to parse through. Being that we want the latitude and the longitude for the address the user enters in, we target these 2 values in the xML document. The latitude and longitude values are both found under result, geometry, location section. The latitude is found in the tags lat. The longitude is found in the tags lng. So therefore, going forward from the loading point, we have $xmlload->result->geometry->location->lat for the latitude. And we have $xmlload->result->geometry->location->lng for the longitude. These give us the latitude and longitude values for the address entered in. We create the PHP variable $latitude and $longitude and set them equal to these values. HTML Code Next we have the HTML code that we need so that we can create a form where a user can enter the address into. It's a very simple form that just has a text box for entering the address and a submit button for submitting the data through. <form action="" method="POST"> Enter the location: <input type="text" name="location_entered" value=''/><br> <input type="submit" name="Submit"/> </form> So here we have a form. Since we want the form to submit the data input into to this current page, we leave the action attribute empty. Therefore, the data entered into the form stays on this page. The method is POST, since we don't need it appended to the current page's URL. Instead we want it appended to the URL we have in the code. Using POST, therefore, is better than using GET. We then create the text box and assign it the name location_entered. We set its value equal to $location, which is the PHP variable that stores the address that the user has entered. This is so that we can see the address that the user has entered into the text box even after the submit button is clicked. We then have a submit button so that the form can be submitted to the server. This concludes the HTML code. Second Block of PHP Code We then have our last block of PHP code, which is very simple, put underneath the text box. <?php if (!empty($location)) { echo "Latitude: $latitude" . "<br>"; echo "Longitude: $longitude" . "<br>"; } ?> The last block of PHP simply outputs the latitude and longitude for the address that has been entered in. And this concludes how we can use the google maps API to get data in XML format such as the latitude and longitude of an address. All it is is a matter of knowing the URL of the google maps API and how you can enter an address and append it to the URL to get the data on the address you want. You then work with the data as you would with any XML data with PHP. So this is how it is done when the API is presented in XML format. You can also do the same exact thing if the data is in JSON format. To see how to use the google maps API with the data in JSON format, see How to Access the Google Maps API in JSON Format with PHP. Related Resources How to Obtain the Zip Code from the Google Maps API Using PHP

Connect to a MySQL Database

To connect to a database in MySQL from PHP, this is done by the mysql_connect function shown below: <?php $servername="server_name"; $username="user_name"; $password="password_name"; $database="database_name"; //Connection to Database mysql_connect($servername, $username, $password); @mysql_select_db($database) or die("Unable to select datbase"); echo "Connected to MySQL"; ?> where servername is the address of the server where the MySQL database is located, username is the user name to log into this MySQL server, and password is the password that allows access to this MySQL server. How to Connect to the MySQL Server To connect to the MySQL server, not database, just the server, the line of code that allows us to make this connection is: mysql_connect($servername, $username, $password); This line of code above connects to the MySQL server. This is how connection to the MySQL server is established. How to Connect to a Database Once we connect to the desired MySQL server, we now can connect to the database in this server that we desire to connect to. We connect to the desired database in MySQL by adding the following line to the above code: @mysql_select_db($database) or die("Unable to select database"); The @mysql_select_db($database) function selects the database that is desired to be connected to, where $database is the variable that contains the name of the database. Output if Successfully Connected to Database If the line: Connected to MySQL Database is shown, you have successfully connected to the database in the MySQL database. This is because PHP will only reach the echo function if there were no errors in any of the above lines.

Connect to a MySQL Database Using PHP Data Objects (PDO)

In this article, we show how to connect to a MySQL database using PHP Data Objects (PDO). PHP supports all the major relational databases used by large companies, including Oracle, IBM's DB2, and Microsoft's SQL server. It also serves open source databases, such as SQLite, PostgreSQL, and MySQL. In this code, we specifically focus on how to connect to a MySQL database with PHP, specifically using PHP Data Objects (PDO). PDO, PHP Data Objects extension, is a data-access abstraction layer. With PDO< you no longer need to use functions for specific databases. PDO is a consistent interface for multiple databases. With PDO, you no longer have to use the mysql_ functions or sqlite_ functions. Instead, you can simply use the PDO interface to work with all relational databases with the same code (with the same functxions). If you change databases, you'll only have to change the Data Source Name (DSN) of the PDO for the code to work. So to access a MySQL database using a PDO, the code is shown below. <?php $dsn= 'mysql:host=hostname;dbname=database_name;'; $user= 'user_name'; $password= 'password'; try { $connect= new PDO($dsn, $user, $password); } catch (PDOException $error) echo 'Connection failed" ' . $error->getMessage(); } ?> By running this code, you should be able to connect to a serve that hosts a MySQL database. If you wanted to connect to another database, such as PostgreSQL or SQLite, then you would just need to change the data source name. Note that for PostgreSQL or SQLite, only the DSN is needed to connect to the database, not the username and password. For MySQL, the DSN, username, and password are needed to connect to the database. For the DSN for PDO, there are 3 basic parts: the PDO driver name (such as mysql, sqlite, or pgsqul), a colon, and the driver-specific syntax. For MySQL, the host name and the database name are needed to connect to the database. Related Resources How to Connect to a PostgreSQL Database using PHP Data Objects

Connect to a PostgreSQL Database Using PHP Data Objects (PDO)

In this article, we show how to connect to a PostgreSQL database using PHP Data Objects (PDO). PHP supports all the major relational databases used by large companies, including Oracle, IBM's DB2, and Microsoft's SQL server. It also serves open source databases, such as SQLite, PostgreSQL, and MySQL. In this code, we specifically focus on how to connect to a PostgreSQL database with PHP, specifically using a PHP Data Object (PDO). PDO, PHP Data Objects extension, is a data-access abstraction layer. With PDO, you no longer need to use functions for specific databases. PDO is a consistent interface for multiple databases. With PDO, you no longer have to use the mysql_ functions or sqlite_ functions. Instead, you can simply use the PDO interface to work with all relational databases with the same code (with the same functxions). If you change databases, you'll only have to change the Data Source Name (DSN) of the PDO for the code to work. So to access a PostgreSQL database using a PDO, the code is shown below. <?php $dsn= 'pgsql:host=hostname;port=portnumber dbname=database_name password=password'; try { $connect= new PDO($dsn, $user, $password); } catch (PDOException $error) echo 'Connection failed" ' . $error->getMessage(); } ?> By running this code, you should be able to connect to a serve that hosts a PostgreSQL database. If you wanted to connect to another database, such as MysQL or SQLite, then you would just need to change the data source name. Note that for MySQL databases, only the DSN, the username and the password (separately) are needed to connect to the database. For SQLite databases, like PostgreSQL databases, only the DSN is needed to connect to the database. For the DSN for PDO, there are 3 basic parts: the PDO driver name (such as mysql, sqlite, or pgsqul), a colon, and the driver-specific syntax. For PostgreSQL, the host name and the database name are needed to connect to the database. Related Resources How to Connect to a MySQL Database Using PHP Data Objects

Create a MySQL Table

In this tutorial, we show how to create a MySQL table using PHP. PHP, as you probably know, can work very well in conjunction with MySQL. We use PHP to write MySQL queries to the database. MySQL is the language of communicating and accessing databases. PHP, in conjunction with it, can write MySQL queries so that we can create a table. A table can be created in MySQL using the following code shown below. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; // Connection to DBase mysql_connect($host,$user,$password); @mysql_select_db($dbase) or die("Unable to select database"); $connection= mysql_connect($host,$user,$password); $createtable= "CREATE TABLE customers ( ". "ID INT NOT NULL AUTO_INCREMENT, ". "firstname VARCHAR(50) NOT NULL, ". "lastname VARCHAR(50) NOT NULL, ". "state CHAR(2) NOT NULL, ". "PRIMARY KEY (ID) ); "; $create= mysql_query($createtable, $connection); if ($create) { echo "Table created successfully"; } else { die ("Table unsuccessfully created"); } ?> So the following code shown above creates a table named customers. First, we must connect to a MySQL database. In order to do so, we need a user name, password, hosting name, and database name. We then use the mysql_connect() function to connect to the database server. Using the @mysql_select_db() function, we can specify which database on the server we want to connect to. We then create a $connection variable, which we'll use below to create a table that we want on the database we selected. We then create a variable called $createtable. This variable creates a table named customers. As most MySQL tables have (should have) is a column called ID. This ID serves as the primary key for the table and it is set to auto increment, because we want each value to be unique and we want sequential order. Next, we create a variable named firstname, which is meant to store people's first name. I declared this to be of VARCHAR(50) type, which means it can be a string of variable length up to 50 characters. Usually people's first or last name doesn't exist 50 characters, but if you feel it would, you can make this longer. If you feel 50 is excessive, you can make it shorter. The value of making it shorter is that less memory is used. But for the average user, memory is probably not a big deal. Next, we create a variable named lastname, which is meant to store people's last name. This also is of type VARCHAR(50). We then create a variable called state, which is meant to store the acronymn of the state that the user lives in, such as NY (for New York), NJ (for New Jersey), PA (for Pennsylvania), etc. Because the abbreviation for each state is 2 characters, we can declare it to be of type CHAR(2), which is a string with a fixed length, in this case of 2 characters. In the next line, we declare the ID column to be the primary column. It is desired to make a column primary when creating a table. So we've created the query to create the following table which we have. But it isn't executed until later in the code. So, thus far, we've set up the framework to create the table, but haven't actually executed the table creation yet. We then create a variable named $create, which creates the query to create the table. The mysql_query() function takes the $createtable variable and the $connection variable, which specifies the chosen database, and creates the table. And with the following code, we now execute the code. The if statement, if ($create), echos out the "Table created successfully" if it has been. Or "Table unsuccessfully created" if it hasn't been. The value held in the $create variable from the mysql_query() function will either hold true or false. If true, the table has been created. If false, it has not been. And this is all that is required to create a MySQL table using PHP. Related Resources How to Select a Table from a MySQL Database How to Check if a MySQL Table Exists Using PHP How to Show All Tables of a MySQL Database Using PHP How to Delete a MySQL Table Using PHP How to Rename a MySQL Table Using PHP How to Add a Column to a MySQL Table Using PHP How to Add a Primary Key to a Column of a MySQL Table Using PHP How to Make a Column of a MySQL Table Unique Using PHP How to Rename a Column of a MySQL Table Using PHP How to Delete a Column of a MySQL Table Using PHP How to Set the Default Value of a Column of a MySQL Table Using PHP How to Drop the Default Value of a Column Of a MySQL Table Using PHP How to Modify the Defintion or Data Type of a Column of a MySQL Table Using PHP How to Insert Data into a MySQL Table Using PHP How to Delete a Row of a MySQL Table Using PHP How to Delete All Rows of a MySQL Table Using PHP How to Insert Data Into a Table of a MySQL Database From an HTML Form Using PHP How to Update a Value in a MySQL Table Using PHP

Delete a MySQL Table

In this article, we show how to delete a MySQL table using PHP. We delete a table using PHP to write the drop table MySQL query to delete the table. Shown below is the general format of the MySQL query to delete a table. DROP table customers; So the above is the MySQL code to delete a table. We'll now show how to tie this MySQL code with PHP to delete a table. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($dbase, $connection); $delete= mysql_query("DROP TABLE customers"); if($delete !== FALSE) { echo("This table has been deleted."); }else{ echo("This table has not been deleted."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $delete. This $delete variable is set equal to a mysql_query() function that has the parameter "DROP TABLE customers". This deletes the table named customers. If the table name is entered into a variable, instead of putting the table name directly into the DROP TABLE query statement, put the variable instead. An example of this is shown in the following link: Code to Delete a MySQL Table Using a Variable for the Table Name. Related Resources How to Create a MySQL Table Using PHP How to Select a Table from a MySQL Database

How to Check if a MySQL Table Exists Using PHP

How to Show All Tables of a MySQL Database Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

Rename a MySQL Table

In this article, we show how to rename a MySQL table using PHP. We rename a table using PHP to write the MySQL query to rename the table. ALTER TABLE Java RENAME TO PHP; So the above is the MySQL code to rename a table named Java to PHP. So the original name of the table is Java and we rename the table to PHP. The table will now be called PHP. We'll now show how to tie this in completely with the full PHP code to rename a table. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $rename= mysql_query("ALTER TABLE Java RENAME TO PHP"); if($rename !== FALSE) { echo("The table has been renamed."); }else{ echo("The table has not been renamed."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $rename. This $rename variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE Java RENAME TO PHP". This renames the existing table Java in our database to PHP. If the table name is entered into a variable, instead of putting the table name directly into the DROP TABLE query statement, put the variable instead. And this is all that is needed to rename a MySQL table using PHP. Related Resources How to Create a MySQL Table Using PHP How to Select a Table from a MySQL Database

How to Check if a MySQL Table Exists Using PHP

How to Show All Tables of a MySQL Database Using PHP

How to Delete a MySQL Table Using PHP

How to Add a Column to a MySQL Table Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Set the Default Value of a Column of a MySQL Table Using PHP

How to Insert Data into a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

How to Insert Data Into a Table of a MySQL Database From an HTML Form Using PHP

How to Update a Value in a MySQL Table Using PHP

How to Copy a Table Definition in MySQL Using PHP

Add a Column to a MySQL Table

In this article, we show how to add a new column to a MySQL table using PHP. We add a new column to a MySQL table using PHP to write the MySQL query to add the column the table. ALTER TABLE customers ADD email VARCHAR(50) NOT NULL; So the above is the PHP code to add a column to a MySQL table at the end of table, meaning it will be the last column. So a column named email is added to the last column of the table. So if the table had 2 columns named first name and last name. It will now contain first name, last name, and email, in that order. We'll now show how to tie this in completely with the full PHP code to add a column to a MySQL table. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $added= mysql_query("ALTER TABLE customers ADD email VARCHAR(50) NOT NULL"); if($added !== FALSE) { echo("The column has been added."); }else{ echo("The column has not been added."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $add. This $add variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers ADD email VARCHAR(50) NOT NULL". This adds the column, email, to the customers table. PHP. The email column is of type VARCHAR(50) NOT NULL. This makes it a variable string up to 50 characters in length. How to Add a Column After a Specified Column So the code above shows how to add a column to the end of a table. The column you add will be the last column of the table. However, you may not want to add the column to the end of a table. You may want to add it after a specific column. The MySQL query below is the general format to add a column after a specified column. ALTER TABLE customers ADD email VARCHAR(50) NOT NULL AFTER firstname; So the code above adds a column named email of type VARCHAR(50) after the column firstname to the table customers. We'll now show how to tie this in completely with the full PHP code to add a column to a MySQL table after a specified column. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $added= mysql_query("ALTER TABLE customers ADD email VARCHAR(50) NOT NULL AFTER firstname"); if($added !== FALSE) { echo("The column has been added."); }else{ echo("The column has not been added."); } ?> So the code above adds a column named email of type VARCHAR(50) after the column named firstname. So the MySQL keyword AFTER can enable us to add columns after a specified column in a table. How to Add a Column to the Beginning of a Table Now we show how to add a column to the beginning of a MySQL table. The MySQL query below is the general format to add a column to the beginning of a table is shown below. ALTER TABLE customers ADD ID INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; So the code above adds a column named email of type VARCHAR(50) after the column firstname to the table customers. We'll now show how to tie this in completely with the full PHP code to add a column to a MySQL table after a specified column. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $added= mysql_query("ALTER TABLE customers ADD ID INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;"); if($added !== FALSE) { echo("The column has been added."); }else{ echo("The column has not been added."); } ?> So this code shows how to add a column to the beginning of a MySQL table using PHP. Related Resources How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Concatenate Column Values in MySQL Using PHP

Add a Primary Key to a Column of a MySQL Table

In this article, we show how to add a primary key to a column of a MySQL database using PHP. Usually at least one column of a MySQL table should have at least one primary key, usually this is the ID column. When a column is made to be a primary key, this signifies that that each row of the column mis forced to be NOT NULL and each row must have a unique value. So a row of a column must have a value in it; it cannot be NULL. And each value in a row must be unique. This means that no values can duplicated. Again, this fits very well, such as in an example as the ID column. You want each row to have a value and the value must be unique. We make a column a primary key in a MySQL table by using PHP to write the MySQL query to make the the column a primary key. The general MySQL code to make a column a primary key is shown below. PRIMARY KEY (ID) So the above is the MySQL code to make a column a primary key. We'll now show how to tie this in with the full PHP code to make the column a primary key. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; // Connection to DBase mysql_connect($host,$user,$password); @mysql_select_db($dbase) or die("Unable to select database"); $connection= mysql_connect($host,$user,$password); $createtable= "CREATE TABLE customers ( ". "ID INT NOT NULL AUTO_INCREMENT, ". "firstname VARCHAR(50) NOT NULL, ". "lastname VARCHAR(50) NOT NULL, ". "PRIMARY KEY (ID) ); "; $create= mysql_query($createtable, $connection); if ($create) { echo "Table created successfully"; } else { die ("Table unsuccessfully created"); } ?> So, first, we must connect to the database. After this, we create a $createtable variable which creates a table named customers. After this, we create the line, PRIMARY KEY (ID). This makes the ID column a primary key. How to Make Multiple Columns of a MySQL Table a Primary Key So, in the above code, we make a single column the ID column. In other instances, it may be necessary to make multiple columns a primary key. More than one column can be a primary key. And, in certain instances, you may need more than one column to be a primary key. For example, let's say we have a MySQL table that holds customer information. Each customer has a customerID and an orderID for when the customer orders something. You may want each value entered into this column to be unique, because 2 customers can't have the same customerIDs and 2 customers cannot have the same orderIDs when they order something. The row also must be entered into; thus it must be NOT NULL. Therefore, it is the perfect fit for being a primary key. So this is how the $createtable varies above. It is the only thing that changes in the code above. $createtable= "CREATE TABLE customers ( ". "customerID INT(11) NOT NULL, ". "firstname VARCHAR(50) NOT NULL, ". "lastname VARCHAR(50) NOT NULL, ". "orderID INT(11) NOT NULL, ". "PRIMARY KEY (customerID, orderID) ); "; So in this code, we simply have to change the $createable variable. We now have the customerID and orderID as 2 primary keys. If you wanted to make more columns primary keys, you would just have to add them to the PRIMARY KEY line. Related Resources How to Add a Column to a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Concatenate Column Values in MySQL Using PHP

Make a Column of a MySQL Table Unique

In this article, we show how to make a column of a MySQL table unique using PHP. When a column is made unique, this means that no 2 values in the column can be the same. Each value must be unique in each row. So if one user enters into an email, for instance, abc@gmail.com, another user cannot enter in the same email abc@gmail. Each value must be unique. Making a column is very commonplace and valuable for many things. One example is an email address. 2 different users can't have the same email address. Therefore, if a user types in an email address already in the table, the MySQL won't accept it. It will give an error that the entry is a duplicate and the new data will not be added to the MySQL table. So having a unique column is very valuable for any data that can't be a duplicate. Examples are email, cell phone numbers, social security numbers, credit card numbers, etc. So making a column unique has plenty of application. So below a create a table with a first name, last name, and email column. The email column is made unique. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; // Connection to DBase mysql_connect($host,$user,$password); @mysql_select_db($dbase) or die("Unable to select database"); $connection= mysql_connect($host,$user,$password); $createtable= "CREATE TABLE customers ( ". "ID INT NOT NULL AUTO_INCREMENT, ". "firstname VARCHAR(50) NOT NULL, ". "lastname VARCHAR(50) NOT NULL, ". "email VARCHAR(50) NOT NULL UNIQUE, ". "PRIMARY KEY (ID) ); "; $create= mysql_query($createtable, $connection); if ($create) { echo "Table created successfully"; } else { die ("Table unsuccessfully created"); } ?> So, first, we must connect to the database. After this, we create a $createtable variable which creates a table named customers. create an ID, firstname, lastname, and email column. To make the email column is made unique by adding UNIQUE to the definition of the declaration. This makes the email column unique. It's very simple. How to Make an Existing Column Unique So above we created a table and made a column unique. How can an existing column be made UNIQUE when the table has already been made? The following PHP code below modifies the existing email column to be unique. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $unique= mysql_query("ALTER TABLE customers MODIFY email VARCHAR(50) NOT NULL UNIQUE"); if($unique !== FALSE) { echo("The column has been made unique."); }else{ echo("The column has not been made unique."); } ?> So the PHP code above makes the email column unique. The SQL MODIFY keyword allows a column to be modified. When modifying a column, put the full definition of the column. So we declare the email column to be of type VARCHAR(50), NOT NULL, and UNIQUE. So this is how a column of an existing table can be made unique. Related Resources How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

Rename a Column of a MySQL Table

In this article, we show how to rename a column of a MySQL table using PHP. We rename a column using PHP to write the drop table MySQL query to delete the table. The general format of the MySQL query to rename a column of a MySQL table is shown below. ALTER TABLE customers CHANGE emailaddress email VARCHAR(50) NOT NULL UNIQUE; So the above is the MySQL code to rename a column originall named emailadress to email. Even though we mean to simply rename the column and not change the structure of the column, nevertheless, we must specify all of the attributes of the renamed column including type and whether it is not null, unique, etc. We'll now show how to tie this in with PHP to rename a column of a table. <?php $user = "DatabaseExamples"; $password = "Swishand1!"; $host = "DatabaseExamples.db.7475584.hostedresource.com"; $database = "DatabaseExamples"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $renamecolumn= mysql_query("ALTER TABLE customers CHANGE emailaddress email VARCHAR(50) NOT NULL UNIQUE"); if($renamecolumn !== FALSE) { echo("The column has been renamed."); }else{ echo("The column has not been renamed."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $renamecolumn. This $renamecolumn variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers CHANGE emailaddress email VARCHAR(50) NOT NULL UNIQUE". This renames the column, emailaddress, to email in the customers table. Again, even though we are simply changing the name, we must specify all parameters of the renamed name of the column, including the type, length, NOT NULL, UNIQUE, PRIMARY, etc. This renamed column is of type VARCHAR(50), is NOT NULL, and is UNIQUE. UNIQUE means that the email must be unique. In other words, no 2 emails entered into this column can be the same exact emaail. So this is how you can rename a column in a MySQL table using PHP. Related Resources How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Set the Default Value of a Column of a MySQL Table Using PHP

How to Drop the Default Value of a Column Of a MySQL Table Using PHP

How to Modify the Defintion or Data Type of a Column of a MySQL Table Using PHP

Delete a Column of a MySQL Table

In this article, we show how to delete a column of a MySQL table using PHP. We delete a column using PHP to write the drop table MySQL query to delete the table. The general format of the MySQL query to delete a column of a MySQL table is shown below. ALTER TABLE customers DROP email; So the above is the MySQL code to delete a column named email of a MySQL table. We'll now show how to tie this in with PHP to delete a column of a table. <php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $deletecolumn= mysql_query("ALTER TABLE customers DROP email"); if($deletecolumn !== FALSE) { echo("The column has been deleted."); }else{ echo("The column has not been deleted."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $deletecolumn. This $deletecolumn variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers DROP email". This deletes the column, email, from the customers table. So this is how you can delete a column from a MySQL table using PHP. Related Resources How to Delete a MySQL Table Using PHP

How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Concatenate Column Values in MySQL Using PHP How to Set the Default Value of a Column of a MySQL Table Using PHP

How to Drop the Default Value of a Column Of a MySQL Table Using PHP

How to Modify the Defintion or Data Type of a Column of a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

How to Copy a Table Definition in MySQL Using PHP

Set the Default Value of a Column of a MySQL Table

In this article, we show how to set the default value of a column of a MySQL table using PHP. So with SQL query languages, like MySQL, a user has the option have setting the default value of a column. The default value is the value that the column will contain by default. This means that without the user specifying a value for the row the user inserts, the value for that particular column will contain this default value. Most of the time, this is not used, because you want the user to enter in the value for a column. But in certain circumstances, you may want a value specified by default. For example, say, you are hosting an event for locals and you're in the state of NY. So you expect most people attending the event to be from NY. So, say, you want to store the user's address, for instance. You may have the user enter in his or her street address and city, but have the state and country column (if it exists) entered in by default, to save the user time typing it in. You may need the user's address to mail them information about future events and so on. So this would be a use of specifying a default value for a column in MySQL. The general format of the MySQL query to set the default value of a column of a MySQL table is shown below. ALTER TABLE customers ALTER state SET DEFAULT 'NY'; So the above is the MySQL code to set a default value for the state column in the customers table to a default value of NY. So all rows in the state column will have NY as their entered in default value, unless the user overrides this by entering in a value. Again, putting in default values in a table, especially when that's what the value will be the vast majority of the time, saves time. We'll now show how to tie this in with PHP. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $setdefault= mysql_query("ALTER TABLE customers ALTER state SET DEFAULT 'NY'"); if($setdefault !== FALSE) { echo("The column now has a default value."); }else{ echo("The default value has not been set."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $setdefault. This $setdefault variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers ALTER state SET DEFAULT 'NY'". This sets the default value of the state column to NY. So this is how you can set the default value of all of the rows of a column of a MySQL table using PHP. Related Resources How to Drop the Default Value of a Column Of a MySQL Table Using PHP

How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

Drop the Default Value of a Column of a MySQL Table

In this article, we show how to drop the default value of a column of a MySQL table using PHP. So we've shown how to set the default value of a column of a MySQL Using PHP. Now we will show how to drop the default value of a column. So whatever the default value of a column was set to, whether a NULL value or a certain character or string, we can get rid of it. With SQL query languages, like MySQL, a user has the option have dropping the default value of a column. The general format of the MySQL query to drop the default value of a column of a MySQL table is shown below. ALTER TABLE customers ALTER state DROP DEFAULT; So the above is the MySQL code to drop the default value for the state column in the customers table. So whatever the default value of the column was, it is now dropped and gone. So all rows in the state column will now not have a default value. We'll now show how to tie this in with PHP. <?php $user = "user"; $password = "password"; $host = "host"; $database = "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $dropdefault= mysql_query("ALTER TABLE customers ALTER state DROP DEFAULT"); if($dropdefault !== FALSE) { echo("The default value has been dropped."); }else{ echo("The default value has not been dropped."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $dropdefault. This $dropdefault variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers ALTER state DROP DEFAULT". This drops the default value of the state column. So this is how you can drop the default value of all of the rows of a column of a MySQL table using PHP. Related Resources How to Set the Default Value of a Column of a MySQL Table Using PHP

How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Modify the Defintion or Data Type of a Column of a MySQL Table Using PHP

How to Insert Data into a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

How to Update a Value in a MySQL Table Using PHP

How to Copy a Table Definition in MySQL Using PHP

Modify the Definition or Data Type of a Column of a MySQL Table

In this article, we show how to modify the definition and/or data type of a column of a MySQL table using PHP. By definition, we are talking about things about the column such as the length of the column, whether it's NOT NULL, PRIMARY, UNIQUE, etc. By data type, we are talking about whether it's VARCHAR, CHAR, INT, DATE, etc. The general format of the MySQL query to modify a column of a MySQL table is shown below. ALTER TABLE customers MODIFY middlename CHAR(1) NOT NULL; So the above is the MySQL code to modify the definition or data type of a column named middlename to be of type CHAR(1). Like, for example, say you had a column named middle name for a user to enter in his or her middle name. You now want to change it so that only the middle initial is stored. So when a user was typing in his or her full name, the data type more than likely was a VARCHAR(50) or something close to that. Now you only want the person's middle initial, so you change it to data type CHAR(1). This is one example of many why you change the definition and/or data type of a column. We'll now show how to tie this in with PHP. <?php $user = "user"; $password = "password"; $host = "host"; $database = "dataabase"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $modifycolumn= mysql_query("ALTER TABLE customers MODIFY middlename CHAR(1) NOT NULL"); if($modifycolumn !== FALSE) { echo("The column has been renamed."); }else{ echo("The column has not been renamed."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $modifycolumn. This $modifycolumn variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers MODIFY middlename CHAR(1) NOT NULL". This changes the middlename column from whatever it was before to now be of type CHAR(1) and made NOT NULL. So this is how you can modify the definition and/or data type of a column in a MySQL table using PHP. Related Resources How to Add a Column to a MySQL Table Using PHP

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Set the Default Value of a Column of a MySQL Table Using PHP

How to Drop the Default Value of a Column Of a MySQL Table Using PHP

Insert Data Into a MySQL Table

To insert data into a MySQL table using PHP, you must first have a connection to the MySQL Server containing the database. After you have the connection, you select the database that you would like to connect to. After you've selected the database, you now use the INSERT INTO command to insert data into the table that you specify. The code to perform this is below: Coding <?php $user= "user_name"; $password= "password"; $host= "host_name"; $database= "database_name"; $table= "table_name"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); mysql_query("INSERT INTO $table (column1_name, column2_name, column3_name) VALUES ('Value1', 'Value2', 'Value3')"); mysql_close($connection); ?> Author's Note:- Using PHP to insert data into a MySQL table is a great and the best method for when you have to automate the insertion of data into a MySQL table, for example, when retrieving data from an HTML form to store the data in a MySQL table. You can also use this method when inserting data into your own table. Remember, also you can directly manually enter in data from phpmyAdmin.

Delete a Row of a MySQL Table

In this article, we show how to delete a row of a MySQL table using PHP. We can delete any row in the table meeting any type of specification. For example, we can delete a row where the user's first name is Melissa. The general format of the MySQL query to delete a row of a MySQL table is shown below. DELETE FROM Users_table WHERE name='Michelle'; So the following code above deletes from the table named Users_table where the row called name is equal to Michelle. In other words, we're deleting Michelle from the list of users. We'll now show how to tie this in with PHP to delete a row from a table. <?php $user = "user"; $password = "password"; $host = "host"; $database= "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $deleterow= mysql_query("DELETE FROM Users_table WHERE name='Michelle'"); if($deleterow !== FALSE) { echo("The row has been deleted."); }else{ echo("The row has not been deleted."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $deleterow. This $deleterow variable is set equal to a mysql_query() function that has the parameter "DELETE FROM Users_table WHERE name='Michelle'". This deletes the row that contains Michelle in the name column. So this is how you can delete a row from a MySQL table using PHP. Related Resources How to Delete a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

Delete All Rows of a MySQL Table

In this article, we show how to delete all rows of a MySQL table using PHP. In other words, we are completely clearing all records from the table and wiping it blank. The table will still exist, because we're deleting the table itself. But we are deleting all rows (or all records) of the table. This can be used if we want the table structure but just want to clear all records from the table. The general format of the MySQL query to delete all rows of a MySQL table is shown below. It uses the MySQL TRUNCATE keyword. TRUNCATE TABLE table_name; So the following code above deletes all rows from the table named table_name. We'll now show how to tie this in with PHP. <?php $user = "user"; $password = "password"; $host = "host"; $database= "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $truncatetable= mysql_query("TRUNCATE TABLE table_name"); if($truncatetable !== FALSE) { echo("All rows have been deleted."); } else { echo("No rows have been deleted."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $truncatetable. This $truncatetable variable is set equal to a mysql_query() function that has the parameter "TRUNCATE TABLE table_name". This deletes all rows (or records) of the table named table_name. So this is how you can delete all rows from a MySQL table using PHP. Related Resources How to Delete a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

Insert Data Into a Table of a MySQL Database From an HTML Form

In this tutorial, we will show how to insert data into a MySQL table of a database from an HTML form. The data which a user enters into a form, such as in the one below, will go straight into a MySQL database, so that we store a the user-entered information directly to a database. This could be useful whenever you want to store information directly to a database. Below is a form which asks a user for his first name, city, and country. <form action="#table" method="post"> <label>First Name:</label><input type="text" name="firstname_entered"/> <label>City:</label><input type="text" name="city_entered"/> <label>Country:</label><input type="text" name="country_entered"/> <input type="submit" name=submit value="Submit"/> </form> How do we put this data into a MySQL Database so that we can have a table containing everyone who enters to join this email list? MySQL The first thing you must do is create the MySQL table in which you are going to transfer the data to. Choose or create the database which is going to contain the table and then create the table. In this example, the table will be called email_list. The MySQL code to create the table is: CREATE TABLE (first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR (50)); Once this table is created, we now create the PHP code. To create the PHP code, we must first examine the HTML code of the form. HTML Code <form action="" method="post"> <label>First Name:</label><input type="text" name="firstname_entered"/> <label>City:</label><input type="text" name="city_entered"/> <label>Country:</label><input type="text" name="country_entered"/> <input type="submit" name=submit value="Submit"/> </form> The HTML code creates the HTML form. This form has 3 fields: first name, city, and country. It also has a submit button. PHP code is added to this HTML form, so that if any of the fields are left empty after the submit button is clicked, the statement is output, "This field cannot be left empty". So the next thing we do is create the PHP code that adds functionality to this HTML form. PHP Code <?php //Block 1 $user = "user"; //Enter the user name $password = "password"; //Enter the password $host = "host"; //Enter the host $dbase = "database"; //Enter the database $table = "table"; //Enter the table name //Block 2 $firstname= $_POST['firstname_entered']; $city= $_POST['city_entered']; $country= $_POST['country_entered']; //Block 3 $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); //Block 4 mysql_query("INSERT INTO $table (column1, column2, column3) VALUES (value1, value2, value 3)"); //Block 5 mysql_close($connection); ?> This PHP Code is separated into 7 blocks in order for us to review each part of the code and know what each part is doing. Block 1 is where you enter all of the information to your MySQL server. This is so that you can later make a connection to your server to connect to the table of your database to insert the user's info into. Block 2 is the code used to retrieve the information that the user entered into the HTML form field. All of the user's information is saved within the PHP variables. Block 3 is the code used to make a connection to the MySQL server and the desired database you would like to connect to. Block 4 is the code that actually executes the insertion of the data into the database. Block 5 closes the database connection.

Update a Value in a MySQL Table

Update John's State:
 In this article, we show how to update a value in a MySQL table using PHP. By updating, we mean we change a value in the MySQL table. The general format of the MySQL query to update a MySQL table is shown below. UPDATE table_name SET column_name1='value' WHERE column_name2='value'; So this MySQL code above updates a table named table_name, setting a column name equal to a certain value where a certain column is equal to a value. I'll give a practical example because this is kind of hard to understand. An example is shown below. UPDATE Users_table SET state='FL' WHERE name='John' In the example shown above, we update a table named Users_table and set the state column equal to FL where the name column equals to John. In simpler words, we want to update the user John's state to FL. Maybe he moved from NY to FL. This setup is great anytime you need to update values. We will show how to tie this in with PHP to update a value in a table. <?php $user = "user"; $password = "password"; $host = "host"; $database= "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $update= mysql_query("UPDATE Users_Table SET state='FL' WHERE name='John'"); if($update !== FALSE) { echo("The column has been deleted."); }else{ echo("The column has not been deleted."); } ?> So, first, we must connect to the database. After we do this, we create a variable named $update. This $update variable is set equal to a mysql_query() function that has the parameter "UPDATE Users_Table SET state='FL' WHERE name='John'". This updates the user John's state to FL. The UPDATE keyword is used followed by the table name. This is how the code knows which table in the database we want to update. After this, we use the SET keyword to set a certain column equal to a certain value where a certain column is equal to a certain value so that we know which row to update. And this is how a value in a MySQL table can be updated using PHP. Related Resources How to Create a MySQL Table Using PHP How to Select a Table from a MySQL Database

How to Check if a MySQL Table Exists Using PHP

How to Show All Tables of a MySQL Database Using PHP

How to Delete a MySQL Table Using PHP

How to Modify the Defintion or Data Type of a Column of a MySQL Table Using PHP

How to Insert Data into a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

How to Insert Data Into a Table of a MySQL Database From an HTML Form Using PHP

How to Copy a Table Definition in MySQL Using PHP

Copy a Table Definition In MySQL

In this article, we show how to copy a table definition in MySQL using PHP. By copying the defintion of a table, we are copying all the columns of a table and the definition and data types that these columns are made of. We are not copying the contents in the rows of the table. We are just copying the same structure that the table is made of. So if a table named Users has an ID int(11) column, first name VARCHAR(50) column, last name VARCHAR(50) column, the table we create will be composed of the exact same columns with the exact same definitions. Again, none of the inserted rows of the table are copied over, just the column defintions. So even if the table you are copying has 12 rows of users, none of this data will be transferred to the new table we create. We are simply copying the definition or structure of the table. This has good application if you simply want to repeat a table but maybe use this table for another purpose. For example, you have a table composed of toys for boys and now you want to create the same structure table but this as a table for toys for girls. So the MySQL code to copy a table definition is shown below. CREATE TABLE table2 AS SELECT * FROM table1 WHERE 1=0"; So the above is the MySQL code to create a table, table2, which copies the structure of table 1 (has all the same structured columns). We'll now show how to tie this in with PHP. PHP Code The PHP code to copy a table definition is shown below. <?php $user = "user"; $password = "password"; $host = "host"; $database= "database"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($database, $connection); $copytabledefinition= "CREATE TABLE table2 AS SELECT * FROM table1 WHERE 1=0"; $create= mysql_query($copytabledefinition, $connection); if ($create) { echo "The table has been successfully copied."; } else { echo "The table has not been copied"; } ?> So the following code gets the data required to make a connection to a database and actually selects a database. We then create a variable named $copytabledefinition that creates a table named table 2, which copies the structure of table 1. So now a new table, table2, is created that has identicial columns as table 1. We make a variable called $create, which runs a $copytabledefinition query. We then execute the query through the if statement. If the $create variable returns true, the table has been successfully copied. If not, the table has not been. This is all that is required to copy a table definition or copy the structure of MySQL table using PHP. Related Resources How to Create a MySQL Table Using PHP How to Select a Table from a MySQL Database

How to Check if a MySQL Table Exists Using PHP

How to Show All Tables of a MySQL Database Using PHP

How to Delete a MySQL Table Using PHP

How to Modify the Defintion or Data Type of a Column of a MySQL Table Using PHP

How to Insert Data into a MySQL Table Using PHP

How to Delete a Row of a MySQL Table Using PHP

How to Delete All Rows of a MySQL Table Using PHP

How to Insert Data Into a Table of a MySQL Database From an HTML Form Using PHP

How to Update a Value in a MySQL Table Using PHP

View User Privileges of a MySQL Database

In this article, we show how to view the privileges of a database user (of MySQL) using PHP By seeing the privileges that a user has, you can find out many, many things. You can find out whether the user has access to all the databases or maybe just one database. You can find out whether the user has global privileges, privileges to just one database, privileges to just a table on one database, or privilege to simply a column of a certain table on a database. Then you can what Data Manipulation Statements a user can execute such as SELECT, UPDTE, INSERT, and DELTE statements. All of this can be visible when you view the privileges of a database user. We can show the privileges of a database user using the following MySQL query. SHOW GRANTS FOR user; So the above is the MySQL code to view a database user's privileges. We'll now show how to tie this in with PHP. <?php $user = "user"; $password = "password"; $host = "host"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } $result= mysql_query("SHOW GRANTS FOR username"); while($row=mysql_fetch_array($result)){ echo $row[0]; } ?> So, first, we must log on to the database server. After we do this, we create a variable named $result. This $result variable is set equal to a mysql_query() function that has the parameter "SHOW GRANTS FOR username". This allows us to view all the privileges granted to the username. PHP. If a user has global privileges with no restrictions, you'll see a statement that looks similar to the following shown below. GRANT USAGE ON *.* TO 'user' IDENTIFIED BY PASSWORD 'password' GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE ON `database`.* TO 'user' Below is a table that summarizes the 4 types of privileges that a user can have as far as the privilege level is concerned.
Privilege Level Description Example
Global All databases and all tables *.*
Database All tables on the specified database customer_database
Table All columns on the specified table CustomerOrders_table
Column Only the specified column or columns (email) CustomerOrders_table
Related Resources How to Show the Structure of a MySQL Table Using PHP How to Display a MySQL Table of a Database using PHP How to Display a MySQL Table Without Duplicate Entries Using PHP

Display a MySQL Table of a Database

In this article, we will show how to display a table that you have in a MySQL database. To do this, first we have to connect to the database of the MySQL server and select the table we would like to display. Once we do this, we can display the table with PHP using the HTML elements to place information in tabular form. PHP Code The full code to choose a table from a MySQL table and to display it is: <?php //First Block- Database Information $servername="server_name"; $username="user_name"; $password="password_name"; $database="database_name"; $table="table_name"; //Second Block- Connection to Database mysql_connect($host, $user, $password); @mysql_select_db($database) or die("Unable to select database"); //Third Block- Selects the Table You Want To Display $result= mysql_query ("SELECT * FROM $table) or die("SELECT Error: ".mysql_error()); //Fourth Block- Prints Out and Displays the Table print "<table width=540 border=1>\n"; while ($row = mysql_fetch_array($result1)){ $images_field= $row['images']; $Type= $row['Type']; $price= $row['Price']; $image_show= "/images/$images_field"; print "<tr>\n"; print "\t<td>\n"; echo "<div align=center><img src=". $image_show."></div>"; print "</td>\n"; print "\t<td>\n"; print "<font face=arial size=4/><div align=center>$Type</div></font>"; print "</td>\n"; print "\t<td>\n"; echo "<font face=arial size=4/>$$price</font>"; print "</td>\n"; print "</tr>\n"; } print "</table>\n"; ?> The first block of code is where you place in your servername, user name, password, database name, and table name of the MySQL server, database, and table, that you want to connect to. The second block of code connects you to the MySQL server and the database of in the MySQL server that you want to connect to. The line mysql_connect($host, $user, $password); connects you to the MySQL server and the line @mysql_select_db($database) or die("Unable to select datbase"); connects you to the database in the server which you would like to connect to. If the program can't connect successfully to the database, the line "Unable to select database" will appear. The third block of code connects you to the table in the database which you would like to display. This connection is stored in the $result variable. We will use this variable in the next block of code to print out the table in table form. The fourth block of code prints outs all the rows in the table. This uses standard HTML elements to create the table.
  • The first line print "<table width=540 border=1>\n"; creates the table and gives it a width of 540 and a border of 1. If you like you can increase or decrease the width of the table, to personal preference. If you would like the table to have a border, the line border=1 must be appended. If you do not want a border, you can either change border=1 to border=0, or you can just remove the line completely. If you would like a thicker border, you can increase border=1 to a larger value, such as border=2 or a greater value, according to your preference.
  • The second line while ($get_info= mysql_fetch_row($result)) uses a while loop to retrieve all of the rows of the MySQL table. The $result variable has the value of the selected table and the mysql_fetch_row function retrieves all of the rows of the table and stores it in the $get_info variable.
  • The lines $images_field= $row['images']; $Type= $row['Type']; $price= $row['Price']; retrieve the values of the images column, the Type column, and the Price column. With this data, now we can show these columns. For your table, substitute these column names with the names of the columns of your table.
  • The line $image_show= "/images/$images_field"; specifies the path of images. When we put images in our MySQL tables which are displayed, we don't place the whole images in the database. All we do in the MySQL table is specify the image name and type. Using PHP code, we then specify the complete path to the image in order to display. This line specifies the complete path to the images, so that they can be displayed. These images are located in the /images/ folder. If they are located somewhere else, then specify that path. If you're not putting images in your table, this line can be disregarded.
  • The line print "<tr>\n"; creates a new row in the table. Every time a while statement loops back and starts from the beginning, a new row is created each time until there are no more rows left in the table.
  • The print "\t\n"; and print "\n"; lines create each of the columns for each row of data. If you have 3 columns which you want to display, then you have to have three of these statements. If you have 7 columns, then you'll have to have 7 of these lines. It all depends on the amount of columns in the table. In the above example, we have three of them. They display the images column, the Type column, and the Price column. If you want to align the data from the column in the center of it, you would add the line <div align=center></div> to it.
  • The remaining line print "</table>\n"; closes the table, respectively.
And this is how a table can be selected and displayed with using PHP. Related Resources How to Create a MySQL Table Using PHP How to Select a Table from a MySQL Database

How to Check if a MySQL Table Exists Using PHP

How to Show All Tables of a MySQL Database Using PHP

How to Delete a MySQL Table Using PHP

How to Copy a Table Definition in MySQL Using PHP

Insert Images into a MySQL Database

In this tutorial, we will show how you can insert images into a MySQL table using PHP. Below is an example of a MySQL table which contains images: Fruits
Banana
$0.79
Mango
$1.99
Cantaloupe
$3.99
Honeydew
$4.99
The above table shown is a table from a MySQL database. You can see the images to the left of the table. This is not HTML. This is PHP code. So now you know that I know how to build a MySQL table and insert images. How to Insert Images into a MySQL Database Table In order to insert images into a MySQL database, we don't actually put the images in the database. We put the images in our regular folder of our website, which most people do by placing images in their images folder. In the MySQL database, all you do is place the image name along with the image type using the format image_name.image_type into the table. For example, we may name a picture of a clown, clown.jpg. This is the only piece of information we place in our MySQL table. We will go through this below. In this demonstration, I'm going to use phpMyAdmin. When creating a table in MySQL, you must create a separate column for storing and then showing images. I name this column images, which I will use to later store all the paths to the images and then display them. So when you create your table, create a separate images column. To create an images column, all we must do is put it to type Varchar and put a good enough length. Above we chose 50. Now to insert an image into the table, all we put do is type the image name and image format using the format image_name.image.format. Thus, if we have a image file named clown and it's a jpg file, we place clown.jpg into the table. This is shown below: Once we place this into the table, along with the other column information upon insertion of all the row data, we are finishing with the MySQL part of this program. We now can proceed to the PHP code to extract the data from the MySQL database table and display, such as the table shown above. PHP Code The PHP Code of the table shown above is: <?php $user = "user_name"; $password = "password"; $host = "host_name"; $database = "datbase_name"; $table = "table_name"; // Connection to Database mysql_connect($host,$user,$password); @mysql_select_db($database) or die("Unable to select database"); $result1= mysql_query( "SELECT images, Type, Price FROM $table ORDER BY Price" ) or die("SELECT Error: ".mysql_error()); print "<table border=1>\n"; while ($row = mysql_fetch_array($result1)){ $images_field= $row['images']; $image_show= "/images/$images_field"; $Type= $row['Type']; $price= $row['Price']; print "<tr>\n"; print "\t<td>\n"; echo "<div align=center><img src=". $image_show."></div>"; print "</td>\n"; print "\t<td>\n"; print "<font face=arial size=4/><div align=center>$Type</div></font>"; print "</td>\n"; print "\t<td>\n"; echo "<font face=arial size=4/>$$price</font>"; print "</td>\n"; print "</tr>\n"; } print "</table>\n"; ?> The first block of PHP code creates php variables which store the username, password, host name, database name, and table name of our MySQL server. We will need this later to connected to the database we want to connect to. The second block of PHP code connects to the MySQL database. If you're unfamiliar with this, check out the resource How to Connect to a MySQL database using PHP. The third block of PHP code selects the columns which we want to show in our table. The only reason we use this is because we do not want to show our primary ID column. And, specifically in this table, we use the ORDER By column to place the elements in order by price. You may not want to do this. This is just an extra feature. If not, just delete the "ORDER By Price" line, and it will not order the rows using any method. The fourth block of code creates a table that has a length of 540px. You can create any length size which you want. Of course, if you make it too small, it won't be able to hold the images and text so there is a minimum size but you can expand it as you want. The while loop fetches each of the rows of data in the table. We can a $images_field PHP variable which represents the value in the column of images for each row. We then create a next PHP variable which contains the path of the image we will show in the database. Because I stored all of the images to be shown in the database in the images folder, the path of all the images are in /images/. We then retrieve all the other values in the other two columns, which are named Type and Price. All of the other elements in the program are to structure and show table and show the text and image of each row. And this is how images can be inserted into MySQL tables of databases. Just as a note, I created a website, https://www.docpid.com, that allows for users to upload any type of files that they want and share it with the rest of the world. The site accepts video uploads, audio uploads, image uploads, pdfs, word documents...anything. It's like youtube but it's for any type of file. Like youtube, registration is free and uploading files is free. The files uploaded can be any size, megabytes or even gigabytes. There are no restrictions regarding size. Any files that are uploaded and made public get put in all the search engines. Signup can be done quickly either through a form or through a social account, google or facebook. So if you want to share files, then go to the link above in this paragraph. Related Resources How to Insert Videos Into a MySQL Database Using PHP How to Select a Table from a MySQL Database How to Create a Confirmation Page for an HTML Web Form Using PHP

How to Redirect to Another URL with PHP

How to Create a Search Engine Using PHP

How to Upload Images to a Website Using PHP

How to Upload Files to a Website Using PHP

How to Create a Searchable Database Using MySQL and PHP

How to Search a MySQL Table For Any Word or Phrase Using PHP

How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP

Insert Videos into a MySQL Database

In this tutorial, we will show how to insert videos into a MySQL database using PHP. In fact, we really are not inserting videos into the database. Doing that would be the harder way of doing it. Instead the easier way of going about it is to upload the video to a directory on your website and simply insert the filename of the video into the MySQL database. Then all you need to do after that is specify the full path to that filename, so that the video can be displayed and played. This is a much, much easier, and simple way of going about it then to actually upload videos into the database, which is complex and really unnecessary. Below we used to have a form for users to upload videos but have taken it out due to malware concerns. In order to insert videos into a MySQL database, as explained before, we don't actually put the videos in the database. We put the videos in a regular folder on our website. I created a videos folder (or directory) on my website which the video files will upload to. In the MySQL database, all you do is place the video name along with the file extension of the video. We also place a description of the video in the database. However, to display the video, all we need is the file name of the video and the file extension. Once we have these, all we have to do in the PHP code is specify the full path to this video, so that it can be displayed and played. So, again, we upload the video to a directory on our website. We don't put the video directly in the MySQL database. We upload it to a directory on our site. We simply get the video file name and file extension of the video and place it in the MySQL database. We then have the complete pathway to the video in our code so that we can show and play it. So if we're saving a video named, amazon.mp4, we save the full file name, amazon.mp4 and we also save the file extension of the video, which is mp4. We will go through this below. In this demonstration, I'm going to use phpMyAdmin. When creating a table in MySQL, we create 4 columns. One column is the ID column, which should be present in really any MySQL table. This column is unique and should be set to autoincrement. It counts sequentially 1 up from any new row of data inserted. So it starts at 1. If you insert 5 rows of data, the fifth row will have an ID of 5. The purpose of it is that it's unique and it gives you a way to order the new uploads in order of when they were uploaded. You could also do this in other ways. But this is probably the easiest way of showing the videos in order from when they were uploaded. The second column that I created was a description column. This holds a description of the video being entered. Once the user puts a description of the video in the text box and uploads the video along with the description, the description of the video entered will be inserted into the descripton column of the table. The third column that I created is the filename column. This holds the full file name of the video. So if you're uploading a video named basketballgame.mp4, the full file name entered into the filename column is basketballgame.mp4 The fourth and last column that I created is the fileextension column. I created a dedicated column for the file extension because we play the videos using the HTML video tag (<video>). With this tag, you must specify the file extension of the video. Therefore, it's best to create a column that holds the file extension for each video. There are other ways you could get the file extension, but this is the best and surest way to do so. Below you can see the structure of the table created that serves as the video uploads table. Since it holds video information, I named the table, 'Videos'. You can see the image of the structure of the table below. So you can see the structure of the table above. The ID column is of type int (11). The description column is set to VARCHAR(100) to allow it to hold a good deal of characters. Sometimes the user may want to put in a somewhat good description of the video, so we allow up to 100 characters. The filename column is set to VARCHAR(50) to allow for a somewhat long filename. The file extension is set to VARCHAR(4), since file extensions can be up to 4 characters long. The reason we use VARCHAR for all these fields is because it allows a variable amount of characters. CHAR is a fixed amount. You would use CHAR when every upload is the same amount of characters. This would be the case for a few things such as state abbreviations, since they are all 2 characters. In this case, CHAR wouldn't work for any of the fields. Even the file extension can vary between 3 characters (mp4) and 4 characters (webm). Of course, if you need to, modify the amount parameters to satisfy your needs. HTML Code So now let's go over the HTML code needed to create the uploader seen above, which allows for videos to be uploaded. The HTML code is shown below. <form action="" method='post' enctype="multipart/form-data"> Description of Video: <input type="text" name="description_entered"/> <input type="file" name="file"/> <input type="submit" name="submit" value="Upload"/> </form> The HTML code above creates an upload form. Since we want this page to keep all information obtained from the form, we set action equal to "". If we wanted to send the information entered into this uploader to another page, we would specify that PHP page. But since we want the information for later PHP code on this page, we set action equal to nothing. The method is POST. And for file uploading, the statement, enctype="multipart/form-data" must be input. If not, file uploading will not work. The line underneath is a line that creates a text box, which holds the description of the video. If no description is entered and the user clicks the Upload button, the statement, "A description must be entered" is output. We then create a line allowing for the file upload. If no file is entered, the statement, "Please choose a file" is output. We then create a submit button, as pretty much every form needs. We give it the value, "Upload", so that Upload appears on the button. If not, it would just have submit by default. We then close the form. This concludes the HTML needed for this page. PHP Code First Block of PHP Code There are 3 blocks of PHP codes needed. The first block is shown below. This block is for uploading the file entered to the directory, where we will store the video, in this case this is the Uploads/videos/ directory. <?php $name= $_FILES['file']['name']; $tmp_name= $_FILES['file']['tmp_name']; $submitbutton= $_POST['submit']; $position= strpos($name, "."); $fileextension= substr($name, $position + 1); $fileextension= strtolower($fileextension); $description= $_POST['description_entered']; $success= -1; $descript= 0; if (empty($description)) { $descript= 1; } if (isset($name)) { $path= 'Uploads/videos/'; if (!empty($name)){ if (($fileextension !== "mp4") && ($fileextension !== "ogg") && ($fileextension !== "webm")) { $success=0; echo "The file extension must be .mp4, .ogg, or .webm in order to be uploaded"; } else if (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm")) { $success=1; if (move_uploaded_file($tmp_name, $path.$name)) { echo 'Uploaded!'; } } } } ?> So this code takes the file that the user entered. Once entered, we are able to find out the file extension of the file by looking for the "." in the file. What follows after this will be the file extension, such as mp4, webm, or ogg. We also take the description that the user entered of the video and place it in the $description variable. We specify the directory that we want the video uploaded to. In this case, it is the Upload/videos/ directory. If the user has clicked the Upload button without specifying a file, the statement, "Please choose a file" is output. If the user enters a file but it is not of the format, mp4, ogg, or web, the statement, "The file extension must be .mp4, .ogg, or .webm in order to be uploaded" is output. If the user enters a file and it is mp4, ogg, or webm, the file is uploaded to the directory we specified through the move_uploaded_file() function. This function creates a temporary name for the file upload and then permanently transfers the file to the directory we specify. The statement, "Uploaded" is then output. This concludes this block of PHP code. Second Block of PHP Code The next block of PHP code inserts the data into the MySQL table for storage. These include the description of the video, the filename of the video, and the file extension of the video. This block of code is shown below. <?php //Block 1 $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; $table = "table"; //Block 3 $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($dbase, $connection); //Block 4 if((!empty($description)) && ($success == 1)){ mysql_query("INSERT INTO $table (description, filename, fileextension) VALUES ('$description', '$name', '$fileextension')"); } //Block 5 mysql_close($connection); ?> Videos This block of code establishes connection to the MySQL database being used. This requires a user, password, host, database, and table name. As stated above, a MySQL table was created with phpMyAdmin. This table has 4 columns: ID, description, filename, fileextension. If the description text box is not empty, then we insert into the Videos MySQL table the description, filename, and fileextension of the video. We then close the database. Third Block of PHP Code The next block of PHP code displays the table with the video description and actual video. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; $table = "table"; // Connection to DBase mysql_connect($host,$user,$password); @mysql_select_db($dbase) or die("Unable to select database"); $result= mysql_query( "SELECT description, filename, fileextension FROM $table ORDER BY ID DESC LIMIT 5" ) or die("SELECT Error: ".mysql_error()); print "<table border=1>\n"; while ($row = mysql_fetch_array($result)){ $videos_field= $row['filename']; $video_show= "Uploads/videos/$videos_field"; $descriptionvalue= $row['description']; $fileextensionvalue= $row['fileextension']; print "<tr>\n"; print "\t<td>\n"; echo "<font face=arial size=4/>$descriptionvalue</font>"; print "</td>\n"; print "\t<td>\n"; echo "<div align=center><video width='320' controls><source src='$video_show' type='video/$fileextensionvalue'>Your browser does not support the video tag.</video></div>"; print "</td>\n"; print "</tr>\n"; } print "</table>\n"; ?> So again, we establish connection to the MySQL databas which contains the Videos table. We query the table containing the video information. We then display the table with the html <table> tag. The statement, while ($row = mysql_fetch_array($result)) gives a loop so that every row in the accounted for. As long as there are rows, the statement, mysql_fetch_array($result) will be true, so the loop won't be exited until all rows are output. Using the $row['value'] feature, we are able to get all of the information from each of the columns for each row. So we obtain the description, filename, and file extension for each row, which represents a video. And this concludes all the code which is necessary for building a video uploader which works in combination with MySQL to store tables of videos. And this is how videos can be used with MySQL to hold a table containing videos. Note that the video you uploaded is public, which is how you were able to access the page. If you didn't think it would work and you uploaded an embarrassing video or one you just simply don't want on the site, just email me and I'll take it down. I'll be checking regularly anyway to see if any offensive videos have been posted. Guys, please keep the videos clean. Any violent, offensive, or pornographic videos will be taken down. Thank you for all cooperation. Related Resources How to Insert Images into a MySQL Database Using PHP How to Insert Files into a MySQL Database Using PHP How to Create a Video Manager Using PHP & MySQL How to Select a Table from a MySQL Database How to Create a Confirmation Page for an HTML Web Form Using PHP

How to Redirect to Another URL with PHP

How to Create a Search Engine Using PHP

How to Upload Images to a Website Using PHP

How to Upload Files to a Website Using PHP

How to Create a Searchable Database Using MySQL and PHP

How to Search a MySQL Table For Any Word or Phrase Using PHP

How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP

Insert Files into a MySQL Database

In this tutorial, we will show how to insert files into a MySQL database using PHP. In fact, we really are not inserting files into the database. This article actually doesn't take the route of inserting the actual files into the MySQL database. Instead, we simply upload files to the server. And we place the filename into the database. We then specify the complete path to the file so that we can access it. In my view, this is much simpler. However, if you are looking to actually insert the file into the database using blob, then we haven't created a tutorial on this. And you'll probably exit this page. However, if we want to display a table with stored files based on a MySQL database, this tutorial is really good to show you how to do so. So, again, with this method, all we have to do is place the filename in the MySQL database. We then can, using PHP code, show the file by specifying the full path to that file. This is a much, much easier, and simple way of going about it then to actually upload files into the database, which is more complex. We used to allow users to upload files on to the site but have stopped due to concerns of malware. In order to insert files into a MySQL database, as explained before, we don't actually put the files in the database. We put the files in a regular folder on our website. I created a files folder (or directory) on my website which the files will upload to. In the MySQL database, all you do is place the file name. We also place a description of the file in the database. However, to display the file, all we need is the file name. Once we have this, all we have to do in the PHP code is specify the full path to this file, so that it can be displayed. So, again, we upload the file to a directory on our website. We don't put the file directly in the MySQL database. We upload it to a directory on our site. We simply get the file name and place it in the MySQL database. We then have the complete pathway to the file in our code so that we can show and display it. So if we're saving a file named, mortgage.pdf, we save the full file name, mortgage.pdf. We will go through this below. In this demonstration, I'm going to use phpMyAdmin. When creating a table in MySQL, we create 3 columns. One column is the ID column, which should be present in really any MySQL table. This column is unique and should be set to autoincrement. It counts sequentially 1 up from any new row of data inserted. So it starts at 1. If you insert 5 rows of data, the fifth row will have an ID of 5. The purpose of it is that it's unique and it gives you a way to order the new uploads in order of when they were uploaded. You could also do this in other ways. But this is probably the easiest way of showing the files in order from when they were uploaded. The second column that I created was a description column. This holds a description of the file being entered. Once the user puts a description of the file in the text box and uploads the file along with the description, the description of the file entered will be inserted into the descripton column of the table. The third and final column that I created is the filename column. This holds the full file name of the file. So if you're uploading a file named records.txt, the full file name entered into the filename column is records.txt Below you can see the structure of the table created that serves as the files uploads table. Since it holds files information, I named the table, 'Files'. You can see the image of the structure of the table below. So you can see the structure of the table above. The ID column is of type int (11). The description column is set to VARCHAR(100) to allow it to hold a good deal of characters. Sometimes the user may want to put in a somewhat good description of the file, so we allow up to 100 characters. The filename column is set to VARCHAR(50) to allow for a somewhat long filename. The reason we use VARCHAR for all these fields is because it allows a variable amount of characters. CHAR is a fixed amount. You would use CHAR when every upload is the same amount of characters. This would be the case for a few things such as state abbreviations, since they are all 2 characters. In this case, CHAR wouldn't work for any of the fields. Of course, if you need to, modify the amount parameters to satisfy your needs. HTML Code So now let's go over the HTML code needed to create the uploader seen above, which allows for files to be uploaded. The HTML code is shown below. <form action="#file" method='post' enctype="multipart/form-data"> Description of File: <input type="text" name="description_entered"/> <input type="file" name="file"/> <input type="submit" name="submit" value="Upload"/> </form> The HTML code above creates an upload form. Since we want this page to keep all information obtained from the form, we set action equal to "". If we wanted to send the information entered into this uploader to another page, we would specify that PHP page. But since we want the information for later PHP code on this page, we set action equal to nothing. The method is POST. And for file uploading, the statement, enctype="multipart/form-data" must be input. If not, file uploading will not work. The line underneath creates a text box, which holds the description of the file. If no description is entered and the user clicks the Upload button, the statement, "A description must be entered" is output. We then create a line allowing for the file upload. If no file is entered, the statement, "Please choose a file" is output. We then create a submit button, as pretty much every form needs. We give it the value, "Upload", so that Upload appears on the button. If not, it would just have submit by default. We then close the form. This concludes the HTML needed for this page. PHP Code First Block of PHP Code There are 3 blocks of PHP codes needed. The first block is shown below. This block is for uploading the file entered to the directory, where we will store the file, in this case this is the Uploads/files/ directory. <?php $name= $_FILES['file']['name']; $tmp_name= $_FILES['file']['tmp_name']; $submitbutton= $_POST['submit']; $position= strpos($name, "."); $fileextension= substr($name, $position + 1); $fileextension= strtolower($fileextension); $description= $_POST['description_entered']; if (isset($name)) { $path= 'Uploads/files/'; if (!empty($name)){ if (move_uploaded_file($tmp_name, $path.$name)) { echo 'Uploaded!'; } } } ?> So this code takes the file that the user entered. We also take the description that the user entered of the file and place it in the $description variable. We specify the directory that we want the file uploaded to. In this case, it is the Upload/files/ directory. If the user has clicked the Upload button without specifying a file, the statement, "Please choose a file" is output. If the user enters a file, the file is uploaded to the directory we specified through the move_uploaded_file() function. This function creates a temporary name for the file upload and then permanently transfers the file to the directory we specify. The statement, "Uploaded" is then output. This concludes this block of PHP code. Second Block of PHP Code The next block of PHP code inserts the data into the MySQL table for storage. These include the description of the file and its filename. This block of code is shown below. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; $table = "table"; $connection= mysql_connect ($host, $user, $password); if (!$connection) { die ('Could not connect:' . mysql_error()); } mysql_select_db($dbase, $connection); if(!empty($description)){ mysql_query("INSERT INTO $table (description, filename) VALUES ('$description', '$name')"); } mysql_close($connection); ?> This block of code establishes connection to the MySQL database being used. This requires a user, password, host, database, and table name. As stated above, a MySQL table was created with phpMyAdmin. This table has 3 columns: ID, description, filename. If the description text box is not empty, then we insert into the Files MySQL table the description and filename of the file. We then close the database. Third Block of PHP Code The next block of PHP code displays the table with the file description and the link to the actual file. <?php $user = "user"; $password = "password"; $host = "host"; $dbase = "database"; $table = "table"; // Connection to DBase mysql_connect($host,$user,$password); @mysql_select_db($dbase) or die("Unable to select database"); $result= mysql_query( "SELECT description, filename FROM $table ORDER BY ID desc" ) or die("SELECT Error: ".mysql_error()); print "<table border=1>\n"; while ($row = mysql_fetch_array($result)){ $files_field= $row['filename']; $files_show= "Uploads/files/$files_field"; $descriptionvalue= $row['description']; print "<tr>\n"; print "\t<td>\n"; echo "<font face=arial size=4/>$descriptionvalue</font>"; print "</td>\n"; print "\t<td>\n"; echo "<div align=center><a href='$files_show'>$files_field</a></div>"; print "</td>\n"; print "</tr>\n"; } print "</table>\n"; ?> So again, we establish connection to the MySQL database which contains the Files table. We query the table containing the files information. We then display the table with the html <table> tag. The statement, while ($row = mysql_fetch_array($result)) gives a loop so that every row in the accounted for. As long as there are rows, the statement, mysql_fetch_array($result) will be true, so the loop won't be exited until all rows are output. Using the $row['value'] feature, we are able to get all of the information from each of the columns for each row. So we obtain the description and filename for each row, which represents a file. And this concludes all the code which is necessary for building a file uploader which works in combination with MySQL to store tables of files. And this is how files can be used with MySQL to hold a table containing files. Note that the file you uploaded is public, which is how you were able to access the page. If you didn't think it would work and you uploaded an embarrassing file or one you just simply don't want on the site, just email me and I'll take it down. I'll be checking regularly anyway. Related Resources How to Insert Images into a MySQL Database Using PHP How to Insert Videos into a MySQL Database Using PHP How to Select a Table from a MySQL Database How to Create a Confirmation Page for an HTML Web Form Using PHP

How to Redirect to Another URL with PHP

How to Create a Search Engine Using PHP

How to Upload Images to a Website Using PHP

How to Upload Files to a Website Using PHP

How to Create a Searchable Database Using MySQL and PHP

How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP

Create a Send Email Form Using PHP & MySQL

In this article, we show how to create a send email form using PHP & MySQL. We are going to create a Send Email Form in this article to send emails to all contacts that we have on an email list table in a MySQL database. Before doing this article, check out how to create an HTML form that places user information into a database. When we write the subject and body of the email and then click the submit button, it will be made so that the email goes to all of the contact emails contained within a MySQL table. The form below is nonfunctional, so nothing will happen. It simply shows you how the frontend interactive is when you write the code. The HTML Code to create the above forms is below: HTML Code <form action="sendemail.php" method="post"> <label>Subject of email:</label><br> <input type="text" name="subject" id="subject"/><br> <label>Body of email:</label><br> </textarea><br> <input type="submit" name=submit value="Submit"/> </form> The HTML form transfer to the PHP file, sendemail.php, and then this file executes the PHP script that is located in it. So after creating this, we now must create the PHP file, sendemail.php. PHP Code <?php //Block 1 $user = "user_name"; $password = "password"; $host = "host_name"; $dbase = "database_name"; $table = "table_name"; //Block 2 $from= 'email_address'; //Block 3 $subject= $_POST['subject']; $body= $_POST['body']; //Block 4 $dbc= mysqli_connect($host,$user,$password, $dbase) or die("Unable to select database"); //Block 5 $query= "SELECT * FROM $table"; $result= mysqli_query ($dbc, $query) or die ('Error querying database.'); //Block 6 while ($row = mysqli_fetch_array($result)) { $first_name= $row['first_name']; $last_name= $row['last_name']; $email= $row['email']; //Block 7 $msg= "Dear $first_name $last_name,\n$body"; mail($email, $subject, $msg, 'From:' . $from); echo 'Email sent to: ' . $email. '
'; } //Block 8 mysqli_close($dbc); ?> The following PHP code is broken up into blocks so that we can go over each block and see what each one does. Block 1 is where you enter in your user name, password, host name, database name, and table name to connect to the table of the MySQL server that you want to connect to. Block 2 is the email address from which you want to send out the email to all the contacts that you have on your email list. Block 3 is the PHP code used to retrieve the subject title and the body of the email content that you enter in and want to send to all members of your email list. Block 4 is the code used to connect to the database of your MySQL server. Block 5 is the code to select all emails that are on the email list and the code that actually executes the connection to the database. Block 6 is the code that fetches each row in your email list table of your database to extract all the information from each and every user. In this table, we store 3 sets of information, the user's first name, last name, and email. If we just used $row= mysqli_fetch_array($result));, this would only retrieve one row of a user's information and we would have to keep repeating this line over and over. Besides being terrible coding, it's also inefficient because we wouldn't know how many rows there are in the table unless we checked. A while loop is is perfect because while the fields are not empty or equal to zero, it will keep retrieving row after row until there are no more rows left to achieve. We run the while and we retrieve each of the three sets of information, the first name, last name, and email of the user. Block 7 writes the salutation of the email and mails off the email using the mail function. We're able to address the user by his or her first and last name, since we have all of this information on the database. We then use an echo statement to confirm that the email was, in fact, sent to the user. Block 8 closes the connection to the database. Related Resources How to Create a Search Engine Using PHP How to Upload Images to a Website Using PHP How to Upload Files to a Website Using PHP How to Create Your Own File Transfer Protocol (FTP) For Your Website Using PHP How to Create a Register and Login Page Using PHP

Create a Newsletter from Scratch Using PHP & MySQL



Creating a newsletter that you could use for your website is actually not too difficult of a procedure at all. You can do this fairly easily using PHP and MySQL. You use MySQL as a database storage system that stores the contact information of all the users who sign up for the newsletter. Once you have all the emails of the users who have signed up for the database, we will show how you can write PHP code so that you can write one email and mass deliver it to all the users in your MySQL database who have signed up for the newsletter. For example, the following newsletter below asks for a user's first name, last name, and email to sign a user up. <fieldset> <legend>Sign up for Newsletter</legend> <form action="addcontact.php" method="post"> <label>First Name:</label><input type="text" name="firstname" id="firstname"/><br><br> <label>Last Name:</label><input type="text" name="lastname" id="lastname"/><br><br> <label>Email:</label><input type="text" name="email" id="email"/><br> <input type="submit" name=submit value="Submit"/> </form> </fieldset> In actuality, you may ask just for email, or you may ask for the first and last name and email as below, or you may even ask for additional information. The choice is yours. However, we will use the above model to create the newsletter that asks just for these 3 pieces of information. Once you know the HTML, PHP, and MySQL code to create fields, you will be able to modify to add what you want. To create this newsletter above, the HTML code to do is:

HTML Code <br><textarea cols="35" rows="20" id="para1"> <fieldset> <legend>Sign up for Newsletter</legend> <form action="Newsletter-signup.php" method="post"> <label>First Name:</label> <input type="text" name="firstname" id="firstname"/><br><br> <label>Last Name:</label> <input type="text" name="lastname" id="lastname"/><br><br> <label>Email:</label> <input type="text" name="email" id="email"/><br> <input type="submit" name=submit value="Submit"/> </form> </fieldset> </textarea><br> Above is the HTML code just to create the text boxes with their various names, which in this case are First Name, Last Name, and Email, along with the title, which is Sign up for Newsletter. This HTML code, though, will be the basis for the PHP code which we are going to write. In order to extract data from this form, we need PHP to retrieve the data and place it in the database we will create. This data is the first name, last name, and email of whoever signs up. If you look at the first line of the HTML code, the form tag specifies the action attribute, which is set to Newletter-signup.php. This is the separate PHP page that we'll have to create which processes the data that the user types in (his or her name and email) and places it into a database, which we can use to gather every email of everyone who signs up. After that, we just have to create one more HTML and PHP page, which sends out an email to everyone on the list.

MySQL Table Creation Before we create the PHP code to retrieve the HTML form data and places them all in one table of a database, we have to create the MySQL table first so that it can be entered into that database. In order to create a MySQL table, go into your web hosting account and find out where the resource is to create a MySQL table. Most web hosts offer MySQL database creation. If you have one, find out how to access this resource. If not, you will have to obtain a web host that offers MySQL or some other SQL server access. Having a database is crucial to keeping a list of all the people who sign up for the newsletter you want to create, so it's absolutely important to have one. Once you create a database name, a username and a password, you then will have a host name for that account. This you need to enter into the PHP code. Then you'll just have to create a table. To create the table which we want, we will need to have 4 columns. The first column will serve as the primary key. This serves as a chronological list to make each entry into the table unique, so if we wanted to, we can definitely refer to each row. The 2nd, 3rd, and 4th columns serve as the columns to store the first name, last name, and email of each user. The PHP code to create the Newsletter-signup.php page is below:

PHP Code <?php $user = "user_name"; $password = "password"; $host = "host_name"; $dbase = "database_name"; $table = "table_name"; $first_name= $_POST['firstname']; $last_name= $_POST['lastname']; $email= $_POST['email']; // Connection to DBase $dbc= mysqli_connect($host,$user,$password, $dbase) or die("Unable to select database"); $query= "INSERT INTO $table ". "VALUES ('$first_name', '$last_name', '$email')"; mysqli_query ($dbc, $query) or die ("Error querying database"); echo 'You have been successfully added.' . '
'; mysqli_close($dbc); ?>

The PHP code above retrieves the data from all the fields from the HTML form, First Name, Last Name, and Email. Let's go over each line so you can understand the PHP code. The first block of PHP code connects you to the MySQL Database which you want to gather all of the user's information. Basically, from this point, you have to create a MySQL database and then create a table in that database where you will store the user's information. In the first 4 lines in the above code, you must enter the username, password, host name, database name, and table name of that MySQL connection. The next block of code, all using the superglobal array POST method, retrieves data from the HTML forms we created. We create a PHP variable for each data that we collect and then we set that variable equal to the $_POST method and the name of what we assigned the name attribute to in the HTML code. If you need help understanding this, check out the tutorial on How to Retrieve Data from an HTML Form Using PHP. Once you read and understand this article well, you will be brought easily to speed on the progress thus far. The next line inserts the user's data into the 3 columns we have created in the MySQL table, named first_name, last_name, and email. The data which PHP retrieved from the HTML forms will be inserted into the MySQL table we have specified. If everything has gone through successfully, the PHP code will tell the user once he or she has signed up that "You have been successfully added." Now that we have the HTML code to create the newsletter-signup, the MySQL table where we will gather all the users' information, and the PHP code to retrieve the data the user enters and place all contact info in one table, all we need now is the HTML code where we can write an email and have it sent out to all user's on our newsletter-signup database. This code is shown below:

HTML Code to Send Out Mass Email <form action="send-email.php" method="post"> <label>Subject of email:</label><br><input type="text" name="subject" id="subject"/><br> <label>Body of email:</label><br><textarea cols="35" rows="10" name="Comments"></textarea><br> <input type="submit" name= "submit" value="Submit"/> </form> This will bring up an interface such as shown below:<br><br> <form action="" method="post"> <label>Subject of email:</label><br><input type="text" name="subject" id="subject"/><br> <label>Body of email:</label><br><textarea cols="35" rows="8" name="Comments"></textarea><br> <input type="submit" name= "submit" value="Submit"/> </form><br> The above email form does not have functionality. You can use this interface to send out emails to everyone on your list. All that is needed now is one more PHP page, which we call send-mail.php. The PHP code before retrieved the user data from the HTML text boxes and placed them into the MySQL table. This PHP code takes all the emails from the list and sends the email out to all users on the list. The PHP code to do this is below:

<?php $user = "user_name"; $password = "password"; $host = "host_name"; $dbase = "database_name"; $table = "table_name"; $from= 'email_to_be_sent_from';//specify here the address that you want email to be sent from $subject= $_POST['subject']; $body= $_POST['body']; // Connection to DBase $dbc= mysqli_connect($host,$user,$password, $dbase) or die("Unable to select database"); $query= "SELECT * FROM $table"; $result= mysqli_query ($dbc, $query) or die ('Error querying database.'); while ($row = mysqli_fetch_array($result)) { $first_name= $row['first_name']; $last_name= $row['last_name']; $email= $row['email']; $msg= "Dear $first_name $last_name,\n$body"; mail($email, $subject, $msg, 'From:' . $from); echo 'Email sent to: ' . $email. '
'; } mysqli_close($dbc); ?>

The above PHP code again connects us to the table of the MySQL database which has all the user contact info of the people who signed up for the newsletter. We make $from variable equal to the email address which we want our email sent from. This can be our personal email, if we want our personal email to be the from email of the email or our website address email, or any other emails we would it sent from. In the next block of code with the $_POST superglobal arrays, we retrieve the data from the HTML subject and body which we created, the interface which we use to send out emails. We then connect to our database. If there is an error, the line "Error querying datbase" will be given. If not, the code has been executed successfully. The block of code with the while loop goes through each of the email contacts we have, extracting all the user's information, first name, last name, and email address. The next block of code then delivers the message using the mail function. Realize that you can modify the $msg variable to anything you want. In this example, we start it over addressing each person with "Dear first_name last_name and then skipping a line and giving them the body of the email. However, you may choose to do it a different way. If you want to, just modify the $msg variable. If everything has gone successfully, you will get the screen with the words "Email Sent to: " followed by all the email contacts we have on our database.

Unsubscribe Option Of course, you may have to add one more functionality to this email, a link that you can put on emails so that subscribers can unsubscribe if they decide they no longer want emails about your service. This isn't difficult, but also requires a separate HTML and PHP page of its own. The HTML code to delete a subscriber by him entering his email is shown below.

This produces the following, which is the page that you can redirect a user to if s/he links on the unsubscribe link at the bottom of the emails that you send out:

Please enter the email for which you want to unsubscribe:

The PHP Code which then looks up the email that the user types in and then searches the database, looking that user account, is:

<?php $user = "user_name"; $password = "password"; $host = "host_name"; $dbase = "database_name"; $table = "table_name"; $email_entered= $_POST['emailentered']; $from= 'support@learningaboutelectronics.com'; $subject= $_POST['subject']; $body= $_POST['body']; // Connection to DBase $dbc= mysqli_connect($host,$user,$password, $dbase) or die("Unable to select database"); $query="DELETE FROM email_list WHERE email='$email_entered'"; $result= mysqli_query ($dbc, $query) or die ('Error querying database.'); mysqli_close($dbc); ?> You have successfully unsubscribed from this newsletter.

When the user enters his or her email and has been successfully unsubscribed (deleted from the list), the line will appear, You have successfully unsubscribed from this newsletter.


This is how a newsletter could be created from scratch from HTML, MySQL, and PHP. It isn't very complicated if you understand the basics of all languages or if you don't, it could present some challenges. The best advice is to read and study the basics of all the concepts presented from all the 3 languages, then you'll have a better feel to do this on your own. There are many advantages to creating your own newsletter rather than buying an available one online including:
  1. Saving Money- Most newsletter service programs charge monthly fees. Do away with this if you learn how to create your own
  2. Having More Control- When you create your own newsletter from scratch, you know every element of how it operates including the MySQL tables and all the HTML and PHP coding to create it. If you want at any time, you can modify any element of your newsletter. Say, your newsletter asks for only the email but you decide you also want their city or country of residence, maybe to guage geographically the places where people who are living subscribe to your site. Modifying this is simple once you know the coding involved.
  3. Can Lose Your Newsletter- If the newsletter program which you subscribe for goes down or out of business, you can lose all the contacts in your newsletter. If you do your own and have confidence in the web host provider you have, the chances of this happening is much less.
The following lists all the information you need to create a newsletter, but if you want to know this inside out, I can walk you through all the above steps and have a newsletter set up on your site in a half an hour or less. I'll make sure that you successfully create your own database on your web host that you current have, create the table where you want to store all the contacts of people who sign up for your newsletter, and help you build all the HTML and PHP code to create the newsletter. And I'll do this all for a one-time fee of $9.99. Hopefully this will not be necessary, as I'm hoping everything above is self-explanatory, but if you want personal help with each level of code and want to know how to do it yourself, we can set something up where I can teach you how this is done so that you can get your newsletter up and running quickly and gather visitor contact info and start sending out emails. Thank you for reading. Related Resources How to Create a Search Engine Using PHP How to Upload Images to a Website Using PHP How to Upload Files to a Website Using PHP How to Create a Register and Login Page Using PHP

PHP Script to Convert Any Web Page File Extension

In this article, we show how to write a PHP script which can convert any web page file extension to another web page file extension in a directory. This means that any .html files can be changed to .php files. .php files can be changed to .html files. .html files can be changed to .asp files. .php files can be changed to .asp files. And the list goes on and on and on and on. The point is, you can change any file extension with PHP pretty easily. If you have hundreds or thousands of files in a directory, this could save hours, days, or weeks of manual work. So how is this done? Basically, the gist of it is that PHP is a powerful server side language. It can access and manipulate the backend of a website such as the directories that comprise a website. Once it access a directory, it can loop through each file in the directory. When it loops through each file in the directory, we can check the file extension of that file. If the file extension is .html, we can convert it to .php, changing the file from an HTML file to a PHP file. And we can convert any file extension from one to another. Yes, this is the power of a server side language such as PHP. We will go over this below. PHP Script to Convert HTML Files (.html) to PHP Files (.php) Files Okay, let's take one case first. Let's convert HTML files (.html) to PHP files (.php). So let's say you want to upgrade your website from static HTML to dynamic PHP pages, which offer much more power for your webpages. So how can you loop through all the files in your website that you want to? The PHP code to loop all files in your home directory and all files in the subdirectories of the home directory is shown below. <?php $homedirectory = "."; $home_directory_files = scandir($homedirectory); if ($open_home_directory = opendir($homedirectory)){ while (($files_home_directory = readdir($open_home_directory)) !== false){ if (is_dir($files_home_directory)) { if ($open_subdirectories = opendir($files_home_directory)){ while (($files_subdirectories = readdir($open_subdirectories)) !== false){ if (strpos($files_subdirectories, ".html") !== false) { $file_rename= str_replace(".html", ".php", $files_subdirectories); rename("$files_home_directory". "/". "$files_subdirectories", "$files_home_directory". "/". "$file_rename"); echo "$files_subdirectories has been renamed to $file_rename" . "<br>"; } } } } } } ?> So this code shown above is very powerful. Be cautious. Use at your only risk. If you copy the above code, save it as a PHP file, and upload it to the root directory of your website, it will convert every HTML page to a PHP page. Only use it and upload it to your website if you actually want to convert every HTML file to a PHP file. The code loops through every file in the home directory and every file in any subdirectory of the home directory. If the file is an HTML file, it converts the html file to a PHP file. We'll now go over all the code so that you can understand. So first, if you want to go all through the files on your website, the best way to do so is through the home directory. So we create a variable called $homedirectory and make it equal to "." This gives us the home directory. Now to say all the files in the home directory, we use the PHP scandir() function. We open the directory and use a while loop to loop through all files in the directory. We then use an if statement to check to see which of these files are directories. We open these directories through the opendir() function again. We then loop through all the files in these subdirectories. Since each of the subdirectories contains a backwards link to the home directory, it's as if the home directory is in the subdirectories. So we're able to loop through all the files in the home directory and all files in the subdirectories of the home directory. We then use an if statement that if the file has an .html extension, we use the str_replace() function to replace the .html file extension with .php file extension. We then use this new replaced string to rename the file to this new name. Being that we're going to upload this PHP script to the root directory of our website, when using the PHP rename() function, we must make it relative to the home directory. Therefore, we have to put, for example, subdirectory/file_name.file_extension in order for the rename() function to work. This is what we do in the code. Otherwise, it will not work. The rename() function script cannot be uploaded to one directory and made it work in another directory without specifying the path to the directory that you want to rename a file. So after the file is now renamed, we echo out which files have been changed by this update. If you don't want to convert every HTML file on your website to a PHP file but instead just all HTML files in a certain directory, then you would use the code below, changing the $directory variable to the directory that you want. <?php $directory = "Documents/"; //Change to the directory you want to convert files in // Open a directory, and read its contents if (is_dir($directory)){ if ($opendirectory = opendir($directory)){ while (($file = readdir($opendirectory)) !== false){ if (strpos($file, ".html") !== false) { $file_rename= str_replace(".html", ".php", $file); rename($directory.$file, $directory.$file_rename); echo "$file has been renamed to $file_rename" . "<br>"; } } closedir($opendirectory); } } ?> So you can see that this code above is a lot simpler than the previous one that loops through all the directories in the home directory. Change the $directory variable to the directory that you want to convert the files. Other than that, most things else is the same. This, again, converts all HTML files in the directory you specify to PHP files. PHP Script to Convert PHP Files (.html) to HTML Files (.php) Files So now we'll do the reverse. Below is the code to convert all PHP files in the root directory and all subdirectories in the root directory on your website to HTML pages. <?php $homedirectory = "."; $home_directory_files = scandir($homedirectory); if ($open_home_directory = opendir($homedirectory)){ while (($files_home_directory = readdir($open_home_directory)) !== false){ if (is_dir($files_home_directory)) { if ($open_subdirectories = opendir($files_home_directory)){ while (($files_subdirectories = readdir($open_subdirectories)) !== false){ if (strpos($files_subdirectories, ".php") !== false) { $file_rename= str_replace(".php", ".html", $files_subdirectories); rename("$files_home_directory". "/". "$files_subdirectories", "$files_home_directory". "/". "$file_rename"); echo "$files_subdirectories has been renamed to $file_rename" . "<br>"; } } } } } } ?> Everything is the same as the previous code but now we search for PHP files and use the str_replace() function to replace the .php extension with the .html extension. PHP Script to Convert PHP Files (.html) to ASP Files (.asp) Files And we really can convert any file extension to any other file extension with this PHP code. Below is the code to convert all PHP files in the root directory and all subdirectories in the root directory on your website to ASP (active server pages) pages. <?php $homedirectory = "."; $home_directory_files = scandir($homedirectory); if ($open_home_directory = opendir($homedirectory)){ while (($files_home_directory = readdir($open_home_directory)) !== false){ if (is_dir($files_home_directory)) { if ($open_subdirectories = opendir($files_home_directory)){ while (($files_subdirectories = readdir($open_subdirectories)) !== false){ if (strpos($files_subdirectories, ".php") !== false) { $file_rename= str_replace(".php", ".asp", $files_subdirectories); rename("$files_home_directory". "/". "$files_subdirectories", "$files_home_directory". "/". "$file_rename"); echo "$files_subdirectories has been renamed to $file_rename" . "<br>"; } } } } } } ?> To convert any file extension to any file extension with PHP, all you have to do is manipulate the if statement that searches the string (this is the if statement that has the PHP strpos() function. And you just have to manipulate the $file_rename variable via the PHP str_replace() function. Once you do this, you can convert any file name to any file name. PHP Script to Convert ASP Files (.asp) to PHP Files (.php) Files Below is the code to convert all ASP files in the root directory and all subdirectories in the root directory on your website to PHP pages. <?php $homedirectory = "."; $home_directory_files = scandir($homedirectory); if ($open_home_directory = opendir($homedirectory)){ while (($files_home_directory = readdir($open_home_directory)) !== false){ if (is_dir($files_home_directory)) { if ($open_subdirectories = opendir($files_home_directory)){ while (($files_subdirectories = readdir($open_subdirectories)) !== false){ if (strpos($files_subdirectories, ".asp") !== false) { $file_rename= str_replace(".asp", ".php", $files_subdirectories); rename("$files_home_directory". "/". "$files_subdirectories", "$files_home_directory". "/". "$file_rename"); echo "$files_subdirectories has been renamed to $file_rename" . "<br>"; } } } } } } ?> And you can do this for any files. You probably get the point now. You dont simply have to convert file names just matching purely from the perspective of file names. You can convert file names to another if the file has something in it. For example, you want to convert all files on your website that have the name HTML4 in it and is an HTML file to a PHP file. In that case you would add an AND statement to the if statement containing the PHP strpos() function to include this. You can do plenty of modifications. So yeah, this code is very powerful. Be aware again. It's a great script for converting a large batch of files quickly to another type of file. Be aware, though, that if you convert these files to another file type, this could reap disaster on your website. If you have links all over the pages of your websites, these links won't be changed by this update. This means this could produce a wide range of broken links on your site (404 errors) that could render your site largely unusable. So be aware of this. To change all the hyperlinks on your site, you would need to create a spider to crawl your site and change the links. I haven't created a tutorial on that yet. But keep this in mind.

Obtain the Zip Code of an Address from the Google Maps API

In this article, we go over how to obtain the zip code of an address from the google maps API using PHP. To see this code in action, see the following page: Zip Code Finder. In this example, for the google maps API, we are going to use the API when it is encoded in JSON format. The other format is XML, which can also be readily used. However, for this example, we focus on JSON. To see the code of how to obtain the zip code when the data in the API is in XML format, see the following link: Code to Get the Zip Code from the Google Maps API in XML Format with PHP. PHP has built-in functions that allows it to work easily with JSON data or XML data. When a user inputs a street address into the the google maps API, you can always obtain the zip code of that address, because all street addresses have zip codes. If you enter just the city and state, google maps may or may not have the zip code. This is because many cities are huge and have multiple zip codes. So if you enter an address such as New York, NY, the google maps API doesn't give the zip code, because there are multiple zip codes for this city. However, if you enter in a full street address, the google maps API will always have the zip code in the API. So to access the google maps API, the URL is, https://maps.googleapis.com/maps/api/geocode/json?address=159-40 Cross Bay Blvd, Queens, NY 11414 So the hyperlink above brings us to the google maps API where the address is 159-40 Cross Bay Blvd, Queens, NY 11414. This represents the address of a McDonalds in Queens, New York. The generic link to access the google maps API page of any location is, https://maps.googleapis.com/maps/api/geocode/json?address= After the word address, you simply put in the location that you want to enter. This can be any type of location such as a state or a city in a state or a full street address. You can really put in any address. But as stated before, the google maps API will only return a zip code for a full street address or a city that only has one zip code. Using this base URL, we can have a user enter in an address, concatenate it to the above URL, putting in the address in the URL, retrieve the page with PHP, decode the JSON data with PHP, and then extract the data that we want from the API. As said before, we will extract the zip code for the address. The zip code is in 5-digit format without the 4-digit extension. So let's go on to the code necessary to do this. This is shown below. We'll separate it into blocks. First Block of PHP Code So the first block of PHP code does the majority of the work as far as PHP code is concerned. It takes the address from the form that a user has entered and puts into the URL representing the google maps API. It then retrieves the page, decodes the JSON data, and extracts the zip code from the google maps API. <?php $location= $_POST['location_entered']; if (!empty($location)) { $url= 'https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($location); $jsoncontent= file_get_contents($url); $decodedarray= json_decode($jsoncontent, true); $zipcode= $decodedarray['results'][0]['address_components'][7]['long_name']; } ?> So we'll go through the code above. So we create a PHP variable named $location. We use the PHP superglobal array, $_POST to extract the data from the text box with the address that the user has entered in. So now we have the address that the user has entered in. We then create an if statement so that we can know whether the data has been entered into the text box or not. We do not want the following code to run if the text box is empty. We then create the a $url variable. This holds the URL of the google maps api for the address entered in. We have the base of the URL and then we have in the address ($location variable) by the concatenator. We put it in a urlencode() function so that if the user enters spaces in the address, this is accounted for. We then create a variable called $jsoncontent. THis holds the all of the data produced in the goole maps api. Since this data is in JSON format, I call this data $jsoncontent. Next, we decode the json data with the PHP json_decode() function. This converts the JSON data into a PHP array. Lastly, we extract the zip code from this google maps API data. Since the zip code is found under the first element of results, this is located in ['results'][0]. Under results, it is found in address_components in the 8th element of address_components, which is ['address_components'][7] (this is because arrays start at the 0th element). Then the zip code is found in the long_name element. We create the PHP variable $zipcode and set them equal to this value. Be aware, though, that depending on what state you are dealing with, it may not be in the 8th element of the address_components tag in the data. For example, for California, the zip code will be found at the 7th element of address_components, which is ['address_components'][6]. So if you're just dealing with one locality, you can just tailor your code for that locality. However, if you are dealing with a variety of places, you may have to create if statements depending on the location. For example, if the $location variable has "CA" (California) to output the ['address_components'][6]. If the $location variable has "NY" (New York) to output the ['address_components'][7]. We just made this code very simple, so it doesn't have if statements checking where the location is. So if you type in a California address, you will get the postal code suffix instead of the 5-digit postal code. So it's a little tricky but you may even argue that google maps API is not the best for getting zip codes of locations. HTML Code Next we have the HTML code that we need so that we can create a form where a user can enter the address into. It's a very simple form that just has a text box for entering the address and a submit button for submitting the data through. <form action="" method="POST"> Enter An Address to Find Its Zip Code: <input type="text" name="location_entered" value='<?php echo $location; ?>'/><br> <input type="submit" name="Submit" value="Submit"/> </form> So here we have a form. Since we want the form to submit the data input into to this current page, we leave the action attribute empty. Therefore, the data entered into the form stays on this page. The method is POST, since we don't need it appended to the current page's URL. Instead we want it appended to the URL we have in the code. Using POST, therefore, is better than using GET. We then create the text box and assign it the name location_entered. We set its value equal to $location, which is the PHP variable that stores the address that the user has entered. This is so that we can see the address that the user has entered into the text box even after the submit button is clicked. We then have a submit button so that the form can be submitted to the server. This concludes the HTML code. Second Block of PHP Code We then have our last block of PHP code, which is very simple, put underneath the text box. <?php if (!empty($location)) { echo "Zip code: $zipcode"; } ?> The last block of PHP simply outputs the zip code for the address that has been entered in. And this concludes how we can use the google maps API to get data in JSON format to get the zip code of the address.

Search the Ebay API By Keywords

In this article, we go over how to access ebay's API using PHP and search ebay by keywords. So ebay is one of those important sites whose API is used by many sites. This includes many sites that find the cheapest price of items and searches many online sites, including ebay, to find out which offer the most competitive. So knowing how to use ebay's API is huge, since ebay is a high-traffic, valuable website. Ebay's API is written in XML, so you should have some basic knowledge of XML in order to work with it. But even if you don't, you may still be able to figure it out, especially if you know HTML already. We'll try to break this down as simply as possible, so hopefully you can follow. So before you can work with ebay's API, you have to sign up to be an ebay developer. You can do this at the following link: Ebay Developers Program. When you sign up, you'll get an app ID. In order to use ebay's API, you will need an app ID. So after you've signed up as an ebay developer and have an app ID, you can make ebay API calls. This means you're using ebay's API. A call just means that you're using the API. As of the current time, ebay has a maximum limit of 5000 calls a day. However, since you are just getting started now, you won't need to worry about this right away until you get very big. So now let's get to the code. If you want to see the full code, see the following link: Code for Ebay API Search by Keywords. The only thing you have to add is the form seen right below under HTML code. HTML Code Below is the HTML code needed to create the form that has the text box where a user enters in <form action="Ebay-search-by-keywords.php" method="POST"> Search for Items on Ebay <input type="text" name="search_entered"/><br> <input type="submit" name="submit" value="Submit"/><br> </form> So we create a form with the action attribute set to "Ebay-search-by-keywords.php". This is the file that we send the form data that the user has entered. So we create this separate PHP file. The method of the form is set to POST because we don't want the data attached to the URL. Instead we want it available for data processing in the code. This form simply has one text box, where a user searches any item wanted on ebay. The name attribute of the input text box is "search_entered". We will need this later in the separate PHP file that we create. We then have a submit button so that we can submit the form data to the server. We then end the form. PHP Code Below is the contents of the separate PHP file that we create which processes the request made by the user in the form. The only thing you have to change in this PHP is to put your own unique app ID in the PHP variable $appid. If you are changing the country from US to something else, you'll need to change the global ID. <?php error_reporting(E_ALL); // Turn on all errors, warnings and notices for easier debugging $search= $_POST['search_entered']; // API request variables $endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call $version = '1.0.0'; // API version supported by your application $appid = 'myAppID'; // Replace with your own AppID $globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE) $query = "$search"; // You may want to supply your own query $safequery = urlencode($query); // Make the query URL-friendly // Construct the findItemsByKeywords HTTP GET call $apicall = "$endpoint?"; $apicall .= "OPERATION-NAME=findItemsByKeywords"; $apicall .= "&SERVICE-VERSION=$version"; $apicall .= "&SECURITY-APPNAME=$appid"; $apicall .= "&GLOBAL-ID=$globalid"; $apicall .= "&keywords=$safequery"; $apicall .= "&paginationInput.entriesPerPage=10"; // Load the call and capture the document returned by eBay API $resp = simplexml_load_file($apicall); // Check to see if the request was successful, else print an error if ($resp->ack == "Success") { $results = ''; // If the response was loaded, parse it and build links foreach($resp->searchResult->item as $item) { $pic = $item->galleryURL; $link = $item->viewItemURL; $title = $item->title; $price= $item->sellingStatus->currentPrice; $shippingprice= $item->shippingInfo->shippingServiceCost; $price= (float)$price; $shippingprice= (float)$shippingprice; $shippingprice= number_format($shippingprice, 2); $totalprice= $price +$shippingprice; $totalprice= (float)$totalprice; $totalprice= number_format($totalprice, 2); // For each SearchResultItem node, build a link and append it to $results $results .= "<a href=\"$link\">$titlePrice: $$priceShipping Cost: $$shippingpriceShipping Cost: $$totalprice"; } } // If the response does not indicate 'Success,' print an error else { $results = "The request was not successful."; } ?> <?h2>eBay Search Results for <?php echo $query; ?><?/h2> <?php echo $results;?> So the code above, taken mostly from ebay's site but modified by me, is shown above. It's highly commented, so it's most self-explanatory, but I'll go through it quickly. So we create the PHP variable $search to extract the value that the user has entered into the text box of the HTML form. The next set of data is all the data needed to create the ebay URL. The complete URL you will create is shown below: http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME= findItemsByKeywords&SERVICE-VERSION=1.0.0&SECURITY-APPNAME= MyAppID&GLOBAL-ID=EBAY-US&keywords=home alone&paginationInput.entriesPerPage=3 If you put in your appID into this URL and paste this URL to the address bar of the web browser, you will get to the ebay API page for the search term 'home alone'. So all the PHP variables that you see below is used to construct the parts of the URL that gets you to the ebay API page for the search terms you are looking for. This includes the base URL, the API version being used, the app ID (unique to you), the global ID (country of use), and the query. Since we are searching for items by keywords, the operation name is set to findItemsByKeywords. Later we'll see in other pages how we can change this to finding items by ISBN or finding items by UPC. We then use all this data to construct the $apicall variable, which constructs the full URL. We then load in the XML document that is returned by our query. If the document is returned successfully, we get the data that makes up the items on the page. This includes the picture, link to the ebay page, the title of that item, the price, and the shipping price of the itme. We type cast all the numbers, the price and the shipping price, to a float, because when PHP extracts it from the XML page, it is not a number. You have to type cast it into a number. PHP initially sees it as a string, so it must be type cast into a float. We then create another variable named $totalprice, which calculates the total price of an item by adding the regular price plus the shipping price. We then create a table that has the picture, link to the ebay page, the price of the item, the shipping price of the item, and the total price of the item. Again, you can customize this according to what you want in the table. If the response is not successful, we output that it was not a success. All this above was the majority of the PHP code. We now move onto the HTML. So we create HTML tags and we output the results based on the query entered. And this all that is required to search keywords the ebay API using PHP. Related Resources How to Search the Ebay API by ISBN using PHP How to Search the Ebay API by UPC using PHP

Search the Ebay API By Keywords

In this article, we go over how to access ebay's API using PHP and search ebay by ISBN. There are many ways of searching ebay. You can search by keywords entered in to the search bar. You can search by ISBN number for books. You can search by UPC number for movies and CDs and other multimedia devices. In this article, we show specifically how to search by ISBN number. Search by ISBN number is more specific, of course if known, because it's unique to a book. Therefore, it guarantees that you are looking only for that specific book and will get only that book in the search results. It's just like the UPC number. It's a unique identifier only for one specific item. Ebay's API is written in XML, so you should have some basic knowledge of XML in order to work with it. But even if you don't, you may still be able to figure it out, especially if you know HTML already. We'll try to break this down as simply as possible, so hopefully you can follow. So before you can work with ebay's API, you have to sign up to be an ebay developer. You can do this at the following link: Ebay Developers Program. When you sign up, you'll get an app ID. In order to use ebay's API, you will need an app ID. So after you've signed up as an ebay developer and have an app ID, you can make ebay API calls. This means you're using ebay's API. A call just means that you're using the API. As of the current time, ebay has a maximum limit of 5000 calls a day. However, since you are just getting started now, you won't need to worry about this right away until you get very big. So now let's get to the code. If you want to see the full code, see the following link: Code for Ebay API Search by ISBN. The only thing you have to add is the form seen right below under HTML code. HTML Code Below is the HTML code needed to create the form that has the text box where a user enters in <form action="Ebay-search-by-ISBN.php" method="POST"> Search for Books on Ebay by ISBN <input type="text" name="ISBN_entered"/><br> <input type="submit" name="submit" value="Submit"/><br> </form> So we create a form with the action attribute set to "Ebay-search-by-ISBN.php". This is the file that we send the form data to that the user has entered. So we create this separate PHP file. The method of the form is set to POST because we don't want the data attached to the URL. Instead we want it available for data processing in the code. This form simply has one text box, where a user searches for any book by ISBN on ebay. The name attribute of the input text box is "ISBN_entered". We will need this later in the separate PHP file that we create. We then have a submit button so that we can submit the form data to the server. We then end the form. PHP Code Below is the contents of the separate PHP file that we create which processes the request made by the user in the form. The only thing you have to change in this PHP is to put your own unique app ID in the PHP variable $appid. If you are changing the country from US to something else, you'll need to change the global ID. <?php error_reporting(E_ALL); // Turn on all errors, warnings and notices for easier debugging $bookisbn= $_POST['ISBN_entered']; // API request variables $endpoint = 'http://svcs.ebay.com/services/search/FindingService/v1'; // URL to call $version = '1.0.0'; // API version supported by your application $appid = 'myAppID'; // Replace with your own AppID $globalid = 'EBAY-US'; // Global ID of the eBay site you want to search (e.g., EBAY-DE) $isbn = "$bookisbn"; // You may want to supply your own query $safeisbn = urlencode($isbn); // Make the query URL-friendly // Construct the findItemsByKeywords HTTP GET call $apicall = "$endpoint?"; $apicall .= "OPERATION-NAME=findItemsByProduct"; $apicall .= "&SERVICE-VERSION=$version"; $apicall .= "&SECURITY-APPNAME=$appid"; $apicall .= "&GLOBAL-ID=$globalid"; $apicall .= "&productId.@type=ISBN&productId=$safeisbn"; $apicall .= "&paginationInput.entriesPerPage=10"; // Load the call and capture the document returned by eBay API $resp = simplexml_load_file($apicall); // Check to see if the request was successful, else print an error if ($resp->ack == "Success") { $results = ''; // If the response was loaded, parse it and build links foreach($resp->searchResult->item as $item) { $pic = $item->galleryURL; $link = $item->viewItemURL; $title = $item->title; $price= $item->sellingStatus->currentPrice; $shippingprice= $item->shippingInfo->shippingServiceCost; $price= (float)$price; $shippingprice= (float)$shippingprice; $shippingprice= number_format($shippingprice, 2); $totalprice= $price +$shippingprice; $totalprice= (float)$totalprice; $totalprice= number_format($totalprice, 2); $results .= "<a href=\"$link\">$titlePrice: $$priceShipping price: $$shippingpriceTotal price: $$totalprice"; } } // If the response does not indicate 'Success,' print an error else { $results = "Oops! The request was not successful."; } ?> So the code above, taken mostly from ebay's site but modified by me, is shown above. It's highly commented, so it's most self-explanatory, but I'll go through it quickly. So we create the PHP variable $bookisbn to extract the value that the user has entered into the text box of the HTML form. The next set of data is all the data needed to create the ebay URL. The complete URL you will create is shown below: http://svcs.ebay.com/services/search/FindingService/v1? OPERATION-NAME=findItemsByProduct&SERVICE-VERSION=1.0.0 &SECURITY-APPNAME=myAppID&GLOBAL-ID=EBAY-US &productId.@type=ISBN&productId=9780590353403 &paginationInput.entriesPerPage=10 If you put in your appID into this URL and paste this URL to the address bar of the web browser, you will get to the ebay API page for the ISBN number 9780590353403 (this represents the Harry Potter and the Sorcerer's Stone book). So all the PHP variables that you see below is used to construct the parts of the URL that gets you to the ebay API page for the search terms you are looking for. This includes the base URL, the API version being used, the app ID (unique to you), the global ID (country of use), and the ISBN number. Since we are searching for books by ISBN, the operation name is set to findItemsByProduct. You can change this to finding items by keywords or finding items by UPC. We then use all this data to construct the $apicall variable, which constructs the full URL. We then load in the XML document that is returned by our query. If the document is returned successfully, we get the data that makes up the items on the page. This includes the picture, link to the ebay page, the title of that item, the price, and the shipping price of the itme. We type cast all the numbers, the price and the shipping price, to a float, because when PHP extracts it from the XML page, it is not a number. You have to type cast it into a number. PHP initially sees it as a string, so it must be type cast into a float. We then create another variable named $totalprice, which calculates the total price of an item by adding the regular price plus the shipping price. We then create a table that has the picture, link to the ebay page, the price of the item, the shipping price of the item, and the total price of the item. Again, you can customize this according to what you want in the table. If the response is not successful, we output that it was not a success. All this above was the majority of the PHP code. We now move onto the HTML. So we create HTML tags and we output the results based on the query entered. And this all that is required to search the ebay API by ISBN using PHP. Related Resources How to Search the Ebay API by Keywords Using PHP How to Search the Ebay API by ISBN using PHP

Search the Ebay API By UPC

In this article, we go over how to access ebay's API using PHP and search ebay by UPC. There are many ways of searching ebay. You can search by keywords entered in to the search bar. You can search by ISBN number for books. You can search by UPC number for movies and CDs and other multimedia devices. In this article, we show specifically how to search by UPC number. Searching by UPC number is more specific, of course if known, because it's unique to a product. Therefore, it guarantees that you are looking only for that specific item and will get only that item in the search results. It's just like the ISBN number. It's a unique identifier only for one specific item. Ebay's API is written in XML, so you should have some basic knowledge of XML in order to work with it. But even if you don't, you may still be able to figure it out, especially if you know HTML already. We'll try to break this down as simply as possible, so hopefully you can follow. So before you can work with ebay's API, you have to sign up to be an ebay developer. You can do this at the following link: Ebay Developers Program. When you sign up, you'll get an app ID. In order to use ebay's API, you will need an app ID. So after you've signed up as an ebay developer and have an app ID, you can make ebay API calls. This means you're using ebay's API. A call just means that you're using the API. As of the current time, ebay has a maximum limit of 5000 calls a day. However, since you are just getting started now, you won't need to worry about this right away until you get very big. So now let's get to the code. If you want to see the full code, see the following link: Code for Ebay API Search by UPC. The only thing you have to add is the form seen right below under HTML code. HTML Code Below is the HTML code needed to create the form that has the text box where a user enters in <form action="Ebay-search-by-UPC.php" method="POST"> Search for Items on Ebay by UPC <input type="text" name="UPC_entered"/><br> <input type="submit" name="submit" value="Submit"/><br> </form> So we create a form with the action attribute set to "Ebay-search-by-UPC.php". This is the file that we send the form data to that the user has entered. So we create this separate PHP file. The method of the form is set to POST because we don't want the data attached to the URL. Instead we want it available for data processing in the code. This form simply has one text box, where a user searches for any item by UPC on ebay. The name attribute of the input text box is "UPC_entered". We will need this later in the separate PHP file that we create. We then have a submit button so that we can submit the form data to the server. We then end the form. PHP Code Below is the contents of the separate PHP file that we create which processes the request made by the user in the form. The only thing you have to change in this PHP is to put your own unique app ID in the PHP variable $appid. If you are changing the country from US to something else, you'll need to change the global ID. So the code above, taken mostly from ebay's site but modified by me, is shown above. It's highly commented, so it's most self-explanatory, but I'll go through it quickly. So we create the PHP variable $itemupc to extract the value that the user has entered into the text box of the HTML form. The next set of data is all the data needed to create the ebay URL. The complete URL you will create is shown below: http://svcs.ebay.com/services/search/FindingService/v1? OPERATION-NAME=findItemsByProduct&SERVICE-VERSION=1.0.0 &SECURITY-APPNAME=myAppID&GLOBAL-ID=EBAY-US &productId.@type=UPC&productId=0024543617822 &paginationInput.entriesPerPage=10 If you put in your appID into this URL and paste this URL to the address bar of the web browser, you will get to the ebay API page for the UPC number 0024543617822 (this represents the movie Home Alone 2 on Blu ray disc). So all the PHP variables that you see below is used to construct the parts of the URL that gets you to the ebay API page for the search terms you are looking for. This includes the base URL, the API version being used, the app ID (unique to you), the global ID (country of use), and the UPC number. Since we are searching for books by UPC, the operation name is set to findItemsByProduct. We then use all this data to construct the $apicall variable, which constructs the full URL. We then load in the XML document that is returned by our query. If the document is returned successfully, we get the data that makes up the items on the page. This includes the picture, link to the ebay page, the title of that item, the price, and the shipping price of the itme. We type cast all the numbers, the price and the shipping price, to a float, because when PHP extracts it from the XML page, it is not a number. You have to type cast it into a number. PHP initially sees it as a string, so it must be type cast into a float. We then create another variable named $totalprice, which calculates the total price of an item by adding the regular price plus the shipping price. We then create a table that has the picture, link to the ebay page, the price of the item, the shipping price of the item, and the total price of the item. Again, you can customize this according to what you want in the table. If the response is not successful, we output that it was not a success. All this above was the majority of the PHP code. We now move onto the HTML. So we create HTML tags and we output the results based on the query entered. And this all that is required to search the ebay API by UPC using PHP. Related Resources How to Search the Ebay API by Keywords Using PHP How to Search the Ebay API by ISBN using PHP

Read an RSS Feed

In this article, we show how to read an RSS feed using PHP. So RSS feeds are a way that a website has of sharing information that can be used by the rest of the internet to see what new articles they have written. RSS stands for Really Simple Syndication. If you look up the definition for syndication, it means the supply or broadcast content. When a website creates an RSS feed, it puts the contents of the new articles that it publishes on the RSS feed, such as the article title, the link to the article, the publication date, and so on. Users who are subscribed to the RSS feed then get fed this new updated content. So a user doesn't have to visit the site to see if there any new articles. Instead, through subscription to the RSS feed, a user can automatically know, through the RSS feed, when there are new articles. Besides subscribiing to an RSS feed, another way to do it is to create a PHP program that reads an RSS feed. This is what we'll do in this article. PHP Code The PHP code to search an RSS feed for any keyword is shown below. <?php $rss = new DOMDocument(); $rss->load('http://rss.cnn.com/rss/cnn_tech.rss'); $list = array(); foreach ($rss->getElementsByTagName('item') as $node) { $item = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'descript' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue, ); array_push($list, $item); } $numberofresults = 12; echo "<h2>CNN Articles"; for($i=0; $i<$numberofresults; $i++) { $title = $list[$i]['title']; $link = $list[$i]['link']; $description = $list[$i]['descript']; $date = date('l F d, Y', strtotime($list[$i]['date'])); echo '<a href="'.$link.'" title="'.$title.'">'.$title.'
'; echo 'Posted on '.$date.'

'; echo $list[$i]['descript']; } ?> So the $rss variable simulates a DomDocument. The $rss variable loads the CNN tech RSS feed. This is the RSS feed for the technology section of the CNN website. We then create an array named $list. This will hold all of the items in the RSS feed (an item represents an article on that website). So next in our code, we have a loop. We loop through each item in the RSS feed for a given site through the foreach loop. This foreach loop takes the $rss variables which holds represents the entire RSS feed as a document object model. The array $list will be an associative array, that is an array composed of name/value pairs or property/value pairs. We have 4 names or properties in this associative array: title, descript, link, and date. We assign these respectively to the title of the article, the description of the article, the hyperlin to the article, and the date the article was published. We get the values of these tags through the getElementsByTagName() function. Inside of this function, we pass the tag that we want to retrieve. For each item in the RSS feed, we add it to the array $list via the array_push() function. This portion of the code ends when we've gone through each item in the RSS feed. Next, we create a variable named $numberofresults. This is the number of results we show from the RSS feed. We limit it to this number. We create a for loop just for the purpose of us being able to loop through each element that was pushed onto the array we've created, $list. We start at the first element (element 0) and go until we have gotten 10 results. After this, we echo out as a header (an h1 tag) CNN Articles. This is because the articles are from CNN. We then create a PHP variable $title, which we set equal to $list[$i]['title']. This gets the title from the $list array. We then create a variable named $link, which we set equal to $list[$i]['link']. This retrieves the link from the array. We do the same thing for $description. For the $date variable, we get the date by using the strtotime() function to convert the string in the XML RSS feed to a time value that can be formatted in PHP. Now we go on to outputting the values through the echo() function. We output the title, link, date, and description. And this is all that is required to read an RSS feed using PHP. Running the code above gives us the output seen at the following link: RSS Feed of CNN Tech. Related Resources How to Search an RSS Feed By Keywords Using PHP

Search an RSS Feed for any Keywords

In this article, we show how to search an RSS feed for any keywords using PHP. So RSS feeds are a way that a website has of sharing information that can be used by the rest of the internet to see what new articles they have written. RSS stands for Really Simple Syndication. If you look up the definition for syndication, it means the supply or broadcast content. When a website creates an RSS feed, it puts the contents of the new articles that it publishes on the RSS feed, such as the article title, the link to the article, the publication date, and so on. Users who are subscribed to the RSS feed then get fed this new updated content. So a user doesn't have to visit the site to see if there any new articles. Instead, through subscription to the RSS feed, a user can automatically know, through the RSS feed, when there are new articles. Besides subscribiing to an RSS feed, another way to do it is to create a PHP program that reads an RSS feed. This is what we'll do in this article. However, instead of just reading the RSS feed, we'll search it for a keyword. For example, say you're interested in news in Israel, you can look for articles on 'Israel.' Say if you love driverless cars and reading new updates on that, you can search 'driverless' and see which articles have new stories pertaining to that. So searching a RSS feed isn't hard. You simply read the RSS feed and then use an if statement to see if the searh term that the user enters is in any of the titles in the RSS feed. This is how you can search any RSS feed for any term. PHP Code The PHP code to search an RSS feed for any keyword is shown below. <?php $rss = new DOMDocument(); $rss->load('http://rss.cnn.com/rss/cnn_tech.rss'); $list = array(); $found=0; foreach ($rss->getElementsByTagName('item') as $node) { $item = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'descript' => $node->getElementsByTagName('description')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue, ); array_push($list, $item); } $numberofresults = 20; echo "<h2>CNN Articles"; for($i=0; $i<$numberofresults; $i++) { $title = $list[$i]['title']; $titletolower= strtolower($title); if (strpos($titletolower, "tesla") !== false) { $link = $list[$i]['link']; $description = $list[$i]['descript']; $date = date('l F d, Y', strtotime($list[$i]['date'])); echo '<a href="'.$link.'" title="'.$title.'">'.$title.'
'; echo 'Posted on '.$date.'

'; echo $list[$i]['descript']; $found++; } } if ($found == 0) { echo "No results have been found"; } ?> So the $rss variable simulates a DomDocument. The $rss variable loads the CNN tech RSS feed. This is the RSS feed for the technology section of the CNN website. We then create an array named $list. This will hold all of the items in the RSS feed (an item represents an article on that website). We also create a $found variable and initalize it to 0. Later on in the code, if the keyword we are searching for is found, we increment this variable. If it isn't found, the variable remains 0. This is so that we know whether the keyword returned any results or not. If not, we can output that no results have been found. So next in our code, we have a loop. We loop through each item in the RSS feed for a given site through the foreach loop. This foreach loop takes the $rss variables which holds represents the entire RSS feed as a document object model. The array $list will be an associative array, that is an array composed of name/value pairs or property/value pairs. We have 4 names or properties in this associative array: title, descript, link, and date. We assign these respectively to the title of the article, the description of the article, the hyperlin to the article, and the date the article was published. We get the values of these tags through the getElementsByTagName() function. Inside of this function, we pass the tag that we want to retrieve. For each item in the RSS feed, we add it to the array $list via the array_push() function. This portion of the code ends when we've gone through each item in the RSS feed. Next, we create a variable named $numberofresults. This is the number of results we show from the RSS feed. We limit it to this number. We create a for loop just for the purpose of us being able to loop through each element that was pushed onto the array we've created, $list. We start at the first element (element 0) and go until we have gotten 20 results (if there is 20 results to be gotten). After this, we echo out as a header (an h1 tag) CNN Articles. This is because the articles are from CNN. We then create a PHP variable $title, which we set equal to $list[$i]['title']. This gets the title from the $list array. Being that we want to check to see if the title has a certain keyword, we create an if statement. If the title contains the keyword "tesla", we then get the rest of the data and output the results. If it does not contain the keyword "tesla", then the if statement is skipped. Back to the if statement, we then create a variable named $link, which we set equal to $list[$i]['link']. This retrieves the link from the array. We do the same thing for $description. For the $date variable, we get the date by using the strtotime() function to convert the string in the XML RSS feed to a time value that can be formatted in PHP. Now we go on to outputting the values through the echo() function. We output the title, link, date, and description. Notice if the if statement is executed and the keyword "tesla" is in the title, the $found variable increments by 1 and, thus, is no longer 0. If "tesla" is never found in the title, the if statement is never executed and, thus, the $found variable remains 0. And this is all that is required to search an RSS feed for any keyword you are looking for using PHP. Running the code above gives us the output seen at the following link: RSS Feed Check for Tesla. Of course instead of putting the word "tesla" directly in the code, we can instead create an HTML text box and extract what a user enters into the text box and place this into a variable which we then check to see is in the title. This way, a user can look up anything he wants from the CNN news feed. Also if you want to check multiple keywords, then you would add in more strpos() statements. For example, if you want to check for "Tesla" and "Gigafactory", the if statement would look like this, if ((strpos($title2, "tesla") !== false) && (strpos($title2, "tesla") !== false)) { //code inside } So this is how you can check as many keywords as you want. If you put &&, this means both keywords must be present in title in order for it to be output. So these are some of the variations you can do when searching RSS feeds. Related Resources How to Read an RSS Feed Using PHP

Java and PHP

This article is an ongoing list of the similarities and differences between Java and PHP. If you learn any programming language, you're at a benefit over a complete newbie, because all languages are similar. If you know PHP, especially now that's it's object-oriented, you'll have little to no problems learning Java. Most programming languages are very similar. In fact, most of them are derived from the same language. PHP and Java are similar because they're both derived from the same language, which is C. Thus, if you know one, it's pretty easy to learn the other. Below proves how similar they are. This is an ongoing list, so more functions are going to added regularly.
Function Java Function Java Example PHP Function PHP Example
Break up a string based on a parameter in the string split() string.split(", "); explode() explode("," , $string);
Extracts a substring from a  string substring() string.substring(3); substr() substr($string,3);
Replaces something in a string replaceAll() string.replaceAll("m", "n"); //replaces m with n str_replace() str_replace("m", "n", $string); //replaces m with n
Finding the length of a string length() string.length(); strlen() strlen($string);
Finding the position of something in a string indexOf() string.indexOf("m"); // finds position of m strpos() strpos($string, "m");
Making a string lowercase toLowerCase() string.toLowerCase(); strtolower() strtolower($string);
Making a string uppercase toUpperCase() string.toUpperCase(); strtoupper() strtoupper($string);
So the above list is just a brief list of functions that are somewhat similar in PHP and Java. Let's not get started on object-oriented programming. I really think that PHP cloned Java's OOP, so that those already familar with Java will feel right at home with PHP and vice versa. Those familiar with OO PHP will learn OO Java really quickly. A lot of them even use the same exact name. When I get a chance, I'll go over the specifics of the similarities and differences in object-oriented programming in Java and PHP. I just wrote this to give you confidence that if you know one of these languages, you can learn the other relatively easily. And programming all ties in. If you know one programming language, you can most likely learn another. And even more than the programming language is the programming concepts that you learn. Once you learn a programming concept, you know the concept, so it's just learning how to implement in a specific language. So, in my opinion, learning a programming concept is more powerful than just knowing how to do something in a certain language. So once you know a concept, it's just figuring out how to implement it in a given language. Related Resources How to Create a Final Class in PHP

Read Individual PHP Configuration Settings

In this article, we show how to read individual PHP configuration settings. Although we can see all the settings of PHP for a given server through the phpinfo() method, for many applications it is overdoing it if all we want is to access one setting. That's not even the larger issue. A given script may operate differently based on a certain setting. So if you're writing a script that behaves one way if a setting is enabled and another way if it is disabled, then you need to be able to read the value of the setting in a script. This is why in this case, phpinfo() is of no use. PHP has a function for checking PHP configuration settings. This is the ini_get() function. Inside of this function, you pass in the specific configuration setting that you want to read. So to get the value of the memory_limit configuration setting, the following code below will get it. <?php echo "The memory limit of this script is " . ini_get('memory_limit'); ?> Actual PHP Output The memory limit of this script is 128M So you can see that we've read the PHP configuration, memory_limit above. The maximum memory that a PHP script can be on this server is 64MB (a very large value for a PHP script). And, of course, you can apply the PHP ini_get() function to any numerous other configuration settings. The configuration setting, max_execution_time, is the maximum time that a PHP script can take to be processed by the server. The configuration setting, upload_max_filesize, is the maximum file size that can be uploaded to the server with a PHP script. So if I ran the PHP ini_get function wtih the max_execution_time and upload_max_filesize configuration settings, I would get the following code below. Actual PHP Output Maximum execution time is 30
Maximum file upload size is 32M Related Resources How to Set Individual PHP Configuration Settings

Set Individual PHP Configuration Settings

In this article, we show how to set individual PHP configuration settings. One way to set individual PHP configuration settings is manually by opening up the php.ini file and changing the values of whatever configuration settings that you want. This allows you to change the PHP configuration settings permanently and systemically throughout your whole website, so that it affects all pages of your website. The other way of setting the PHP configuration settings is through PHP code in a script. This is a temporary change to the PHP configuration settings that is only valid for the script at hand. In other words, it doesn't affect the website systemically (all the pages on a site). It only changes configurations for the specific script that has the changes in code. This is for times when you don't want to change a configuration for the whole website but for simply one page on a website. There are many reasons why you would want to do this. One example is you want to increase the size of file uploads for a movie upload script but not other other pages where users can upload files (since you want those pages limited). PHP has a function for setting PHP configuration settings. This is the ini_set() function. Inside of this function, you pass in the specific configuration setting that you want to set and the value that you want to set that configuration setting to. So the first parameter is the configuration setting that you want to change and the second parameter is the value that you want to change it to. So to set the value of the max_execution_time configuration setting, the following code below is used. <?php ini_set(max_execution_time, "60"); ?> So the code above sets the configuration setting, max_execution_time, to 60. By default, most servers have this setting set to a value of 30. The maximum execution time is the maximum amount of time given to run a PHP file. If the file takes longer than the time in the max_execution_time setting, then the file times out and doesn't complete processing. So it's the maximum amount of time given to a PHP script to completely run. If it's not done completion within that time, then the server clocks out. The server clocks the file out. The beauty about using PHP code to set a configuration file is that whatever you set the value to in a PHP script is just set for that script. So, above, we set the maximum execution to 60. It's only for this PHP script that it becomes 60. After, it reverts back to its regular php.ini value. So it's not a permanent setting change. It's just for the script on hand. It's really amazing diversity that you have. In that, writing a change in a PHP script that doesn't affect the whole website. It's just for that script. There's many reasons why you may need to change a configuration setting just for a certain script. For example, say that you have a PHP script where a user uploads a very big file such as gigahertz of memory. By default, the maximum upload size for a file is about 32MB, which definitely would not suffice for large files such as video movies. So you would want to change the maximum upload size to a much larger value such as 4000MB or whatever. And the amazing thing is it's just for this script. You may not want to increase the file upload size throughout the rest of the website. You may want to keep those file upload sizes, as they are. This is the beauty of using PHP code to set PHP configuration settings. You can keep it just to one script. And there's multiple PHP configuration settings you can set in this manner. All you have to is use the PHP ini_set() function. Pass in the configuration you want to change as the first parameter and the value you want to set it to as the second parameter. And that's all there is to it. Related Resources How to Read Individual PHP Configuration Settings

Extend the Run Time of a PHP Script

In this article, we show how to extend the run time of a PHP script. The run time of a PHP script is the amount of time that it takes for a PHP script to execute. The PHP setting that correlates with the maximum run time for a PHP script is the max_execution_time setting. The max_execution_time setting is the maximum amount of run time that a PHP script can have before the script gets timed out by the server and fails to be executed. By default, on most PHP server settings, the max_execution_time is set to 30 (meaning 30 seconds). PHP is a fast-performance language, so for practically all basic scripts and most intermediate scripts, 30 seconds is more than sufficient for the amount of time it takes a server to process and execute a PHP file. However, for certain applications, such as those that are extremely data-intensive or memory-intensive, 30 seconds may not be enough. One type of script this may be the case for is a spider crawler for a relatively large site. If a spider is crawling a site to gather hyperlinks and there are thousands of files that it has to go through, this can take a substantial long time, longer than 30 seconds. If it takes longer than 30 seconds, with the default PHP max_execution_time setting, the script will clock out and fail to execute and crawl the sites. So in a case like this, you need to extend the run time of the PHP script. So there are 2 ways of doing this. One, we can manually change the setting in the php.ini file. If you do this, it applies systematically to the whole server. So it affects all pages on the your website. Second, we can change the setting in the currently running PHP script. When we do this, it applies only to the script, meaning this setting is only changed for the script that has it. All other pages on the site are not affected. To change the max_execution_time setting in a PHP script, we use the PHP ini_set() function. The ini_set() function accepts 2 parameters. The first parameter is the setting you want to change which is the max_execution_time setting. The second parameter is the value that you want to set the max_execution_time setting to. The following code converts the maximum run time to 200 seconds. <php ini_set(max_execution_time, "200"); ?> So with this code above, we've now extending the maximum run time over 6 times its default value. A PHP script can now be processed over the server for up to 200 seconds instead of just 30 seconds. If you want, you can even extend this value even more, depending on how complex your script it. And this is a quick showing how the run time of a PHP script can be extended.

Change the Maximum File Upload Size of a PHP Script

In this article, we show how to change the maximum file upload size of a PHP script. The maximum file upload size is the maximum size that a file can be when being uploaded to a site's server. There are many reasons you would want to change the maximum file upload size, whether it is to increase it or decrease it. Reasons you may want to increase it is because you may want users to be able to upload very large files such as full movies in PHP. Reasons to decrease it is because you may want to restrict the file upload size users can use. The setting that controls the file upload size in PHP is the upload_max_filesize setting. By default, on many servers, this PHP upload_max_filesize is set to a maximum value of 32M (meaning 32 megabytes). For moderately big files, this is enough. But if a user wants to upload very large files, such as hundreds of megabytes or even several gigabytes, this upload_max_filesize obviously needs to be increased. So how do we do this? So there are 2 ways really that we can do this. One, we can go to the php.ini file on the server and change this setting manually. The php.ini file is the file on a server that allows you to change configuration settings for PHP. When changes are made to this php.ini file, it applies systematically to all pages on a server. Second, you can change the configuration setting in the actual code with PHP code. When you do this, it applies only to the current PHP script that is being run. All other pages on the site do not have these affected changes. To make this change, we use the PHP ini_set() function. The ini_set() function takes in 2 parameters. The first parameter is the configuration setting that you want to change, in this case, the upload_max_filesize size. The second parameter is the value that you want to set this setting to. So in the following code below, we set the maximum file upload size to 4000 megabytes. <?php ini_set(upload_max_filesize, "4000M"); ?> So now that we've significantly increased the upload_max_filesize setting, we can increase much larger file sizes. As you can see above, putting an "M" in the value parameter means megabytes. Putting a "K" in the value parameter means we are setting the value in kilobytes. So this is how we can change the maximum upload file size in a PHP script.

PHP Header Location Error- Warning: Cannot Modify Header Information- Headers Already Sent

So sometimes when using the PHP header function to cause a redirect to another page, you will get the error: Warning: Cannot Modify Header Information- Headers Already Sent by (output started at /home/content/84/.../searchpage.php:1) This can happen such as with using the following code: <?php header('Location: http://www.google.com'); ?> This error occurs for pretty much one reason only but how it can exist can take many forms. We'll explain now. The reason this error occurs is because output is written to the browser before the redirect to another page occurs. With the PHP header function, this is forbidden. No output can be written to the browser before the redirect occurs. If this is the case, you will get the error, such as shown above. So how does output can written to the browser? And the answer is, this can take many forms. For one, you may actually have output shown before the php header function, such as an echo statement. The code below will run an error: <fieldset> <?php echo "This output causes the header function to not work"; header('Location: http://www.google.com'); ?></fieldset> The above is a more obvious blatant example. However if you have an HTML tag located before the code, it will also cause this error to occcur. This html tag may be <html> or <header>. The code below will cause an error: <fieldset> <?php <html> header('Location: http://www.google.com'); ?></fieldset> So you can't have any statements printed by PHP. You can't have any HTML tags present before the header function. You also can't even have white space present before the PHP header tag. This, too, will cause an error. The following code below will cause an error: <fieldset>        <?php header('Location: http://www.google.com'); ?> </fieldset> Only the following code, below, no white space, html tags, or statements printed to output will cause no errors. <fieldset> <?php header('Location: http://www.google.com'); ?> </fieldset> But what if you've run the code with absolute no white space, html tags, printed statements. The php code is right at the top with only the header function, and yet the same error is still occurring. Then what may be causing it? Yes, even with absolutely no space visible to us, this error can still occur. And if you have no whitespace or anything else and still getting the error, it's more than likely due to how the PHP file is saved. If you use a text editor like notepad, you can save PHP file in many different encoding formats. You can save the PHP file in either ANSI encoding, Unicode encoding, Unicode big endian encoding, or UTF-8 encoding. The format you choose can trigger this error. The best encoding to save it at is the ANSI encoding. This encoding adds no hidden whitespace or characters to the PHP file. If you use unicode, unicode big endian, or UTF-8 encoding, these encodings can actually add characters to the text in the PHP file. This is why this error can occur even when you see absolutely no whitespace at all. Some encodings can add things to the file you can't even see. The best format to save the file is in ANSI. It's the purest form that doesn't add characters to the PHP file, so what you actually can see in the text is the same behind the scenes of the binary code. The other encodings can add. So whatever you have for the PHP, copy it, and paste it to notepad. Save it with a .php extension and in ANSI encoding. Then upload this file to web and this may correct the error. So there are many reasons why this error may occur again, but these solutions should fix that problem. To see a classic example of a program that uses the header function that uses location for a redirect, see How to Create a Search Engine Using PHP. We create a search engine using the php function as the basis of the search engine. This function causes redirects to various websites based on the search query that a user enters.