Skip to content
Tutorials Center
My learning

Topics

Lesson 145 of 147 ยท Practice and Review

Practical PHP Snippets: 7 Everyday Recipes

7 practical PHP recipes with output - detect search bots, read multiple checkboxes, pass form values between pages, find where a function is defined, hide notices, short echo tags and clean URLs.

Some questions come up so often in forums and code reviews that they deserve a short, correct answer in one place. This page gathers seven of them. Each recipe explains the problem, gives code you can run, and says when not to use it. Because a command-line runner has no web server, the web-related examples simulate the request with arrays (the same arrays PHP would fill in for you on a real server), so you can see exactly what the logic does.

If any term is new, the background lessons are Superglobals, Forms, Sessions, Reflection and Routing.

1. Detect search engine bots

A visit from a crawler announces itself in the User-Agent header, which you read from $_SERVER['HTTP_USER_AGENT']. Typical reasons to check: skip analytics, avoid starting a session for crawlers, or serve a lighter page. The header can be faked, so never use it for security or access control. To verify a real Googlebot, do a reverse DNS lookup of the IP and a forward lookup of the resulting host name.

PHP Detect bots by User-Agent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

2. Read multiple checkbox values

Checkboxes that share a name become an array only when the name ends in []. Without the brackets PHP keeps just the last value. Unchecked boxes are not sent at all, so always default to an empty array.

HTML
<form method="post">
  <label><input type="checkbox" name="langs[]" value="php"> PHP</label>
  <label><input type="checkbox" name="langs[]" value="js"> JavaScript</label>
  <label><input type="checkbox" name="langs[]" value="sql"> SQL</label>
  <button>Send</button>
</form>
PHP Handle checkbox arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The whitelist with array_intersect() matters because users can send any value, not only the ones in your form.

3. Pass form values between pages

HTTP is stateless, so a value typed on page 1 reaches page 3 only if you carry it. You have three options:

  • Hidden fields in the next form: simple, but visible and editable by the user, so re-validate everything.
  • The session ($_SESSION): stays on the server; the right choice for multi-step wizards.
  • The query string: only for harmless values such as a search term or page number.
PHP A two-step wizard with the session

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

On a real site start the session with session_start() before any output, and regenerate its ID after login as covered in Sessions.

4. Find where a function is defined

When you inherit a large codebase, ReflectionFunction answers "where does this function live?" in one call. It also reports the number of parameters, the doc comment and whether it is internal. Methods have the equivalent ReflectionMethod.

PHP Locate a function definition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In an editor, "Go to definition" does the same. ReflectionFunction is for tooling and debugging scripts, not for hot paths.

5. Hide notices and warnings (the right way)

The wrong fix is error_reporting(0) or the @ operator, which hides problems instead of solving them. The right approach differs by environment:

  • Development: show everything (error_reporting(E_ALL), display_errors=1).
  • Production: never display errors to visitors, but log them (display_errors=0, log_errors=1).
PHP Error reporting levels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Production settings belong in php.ini, not in the script. See Errors and Debugging for how to find the cause instead of silencing it.

6. The short echo tag

<?= $value ?> is shorthand for <?php echo $value; ?>. Unlike the old <? ... ?> short open tag, it is always available since PHP 5.4, whatever the short_open_tag setting. It is the standard way to print in templates. Escape the value for HTML unless it is trusted markup.

PHP Echo tags in a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the alternative syntax (foreach: ... endforeach;) that keeps templates readable. Both come from PHP and HTML. Do not use the long form <? ?>: it depends on a setting that is often off.

7. Clean URLs with .htaccess and mod_rewrite

Visitors prefer /products/42 to /product.php?id=42. On Apache a .htaccess file with mod_rewrite sends every request for a non-existent file to one entry script, a "front controller", which then reads the path. (nginx does the same with try_files.) The server-specific part cannot run here, so it is shown read-only:

APACHE
# public/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
NGINX
# nginx equivalent
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

The PHP half is plain path parsing. The router below simulates what index.php receives:

PHP A tiny front controller

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The patterns accept only the characters you expect, which stops path tricks. Full routers, including method matching and parameters, are the subject of Routing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you not rely on the User-Agent header for security?

    Any client can claim to be Googlebot. To verify a crawler, check the IP with reverse and forward DNS lookups.
  2. 2. What must the name attribute of a group of checkboxes end with so PHP builds an array?

    A name like langs[] makes PHP collect all ticked values in $_POST['langs']. Unticked boxes are not sent at all.
  3. 3. Which is the correct way to deal with warnings on a production server?

    Visitors should not see internal errors, but you must still record them so you can fix the causes.
  4. 4. What does the RewriteCond !-f line in the .htaccess example check?

    The rewrite to index.php only applies when the requested path is not a real file, so images and CSS are still served directly.

Summary

  • User-Agent checks can identify well-behaved crawlers but cannot protect anything.
  • Checkbox groups need name="x[]", unticked boxes are absent, and the values must be whitelisted.
  • Carry data between pages with the session for anything the user should not edit.
  • ReflectionFunction and ReflectionMethod tell you where code is defined.
  • Hide errors from visitors in production, but log them; never use @ or error_reporting(0) to "fix" warnings.
  • <?= ... ?> is the always-available echo tag for templates; escape what you print.
  • Clean URLs need a server rewrite to a front controller plus a small router in PHP.

Next: Parsing HTML with DOMDocument and XPath