Something UsefulLet us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].
To display this variable, you can simply do:
Example #1 Printing a variable (Array element)
A sample output of this script may be: Mozilla/5.0 (Linux) Firefox/112.0 There are many types of variables available in PHP. In the above example we printed an element from an Array variable. Arrays can be very useful. $_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo function used in the example in the previous section. You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Firefox you can do this:
Example #2 Example using control structures and functions
A sample output of this script may be: You are using Firefox. Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.
The second concept we introduced was the str_contains
function call. str_contains is a function built into
PHP which determines if a given string contains another string. In this case we are
looking for We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Example #3 Mixing both HTML and PHP modes
A sample output of this script may be: <h3>str_contains() returned true</h3> <p>You are using Firefox</p>
Instead of using a PHP echo statement to output something, we jumped out
of PHP mode and just sent straight HTML. The important and powerful point
to note here is that the logical flow of the script remains intact. Only
one of the HTML blocks will end up getting sent to the viewer depending on
the result of str_contains. In other words, it depends on
whether the string |