PHP: Tips and Tricks

There are numerous styles and guides on PHP; such as learning PHP, working with PHP, having sex with PHP…er, OK, maybe not the last one. What makes this “article” all sorts of different is random tips and tricks that have not been mentioned, or if they have, haven’t been mentioned enough.

What You Need

Attentive reading. You can be at a beginner or intermediate level, it doesn’t matter. If you are a beginner, I’d recommend reading some more about PHP, such as the PHP manual » or perhaps take a gander at Jem’s PHP Beginner’s Guide » series.

Echo: ‘ and “

You can echo a variable or or a block of text by one of two ways: use the quotation mark (“) or the apostrophe (‘). I’m going to start with the former:

<?php
echo "I am God. Bow down to me.";
?>

By this method, we’re using quotation marks (“) to echo our statement. What is different about apostrophes (‘) is we can echo a variable inside the quotation marks. Let’s say I want to add the variable $now (which would read “now or die”) at the end of the second sentence:

<?php
$now = "now or die";
echo "I am God. Bow down to me $now.";
?>

We can also use brackets around the variable, as well, which would look like:

<?php
$now = "now or die";
echo "I am God. Bow down to me {$now}.";
?>

If we were to echo it, it would appear as “I am God. Bow down to me now or die.” As mentioned before, apostrophes can be a bit different from quotation marks, and cannot include a variable.

<?php
echo 'I am God. Bow down to me.';
?>

The statement will of course echo in the same way the previous one did. To add the same variable as before, we have to close the statement at “me”, include the variable, and then open up another apostrophe to add the period. Whether you’re using quotations or apostrophes, a variable must always be surrounded by a period (.) if it is outside the quotation or apostrophe. If the statement ends at the variable, a period is not needed.

<?php
$now = 'now or die';
echo 'I am God. Bow down to me ' . $now . '.';
?>

Instead of using the period at the end of the statement, we can include it in the variable, and end the echo at the variable:

<?php
$now = 'now or die.';
echo 'I am God. Bow down to me ' . $now;
?>

Like said before, a period is not needed if the statement ends at the variable. In the same echo, we can have a quotation and apostrophe inside the same statement:

<?php
$now = 'now or die';
echo "I am God. Bow down to me ' . $now . ".";
?>

Another note: you cannot use quotations inside quotations unless it has a back slash before the quotation. This also goes for apostrophes inside apostrophes. An example:

<?php
echo "I am God. Bow down to me "now or die".";
echo 'I am God. Bow down to me 'now or die'.';
?>

To avoid any confusion, you can use HTML entities instead (you can find a full list of them W3Schools »):

<?php
echo "I am God. Bow down to me "now or die".";
echo 'I am God. Bow down to me 'now or die'.';
?>

Functions: global and require()

This isn’t strictly necessary, but is something that I haven’t seen anywhere and was what I found out on my own. With functions, if you need to use variables outside of the function, you have to either a) make variables in another file global or b) include the file into the function to call on aforementioned variables.

For example, we’re going to call on the $_OPT variables, which is in our imaginary “config.php”; there are two variables, $_OPT[‘name’] and $_OPT[‘url’]. I’m going to create a function that calls onto the user’s name and URL.

<?php
function getUser() {
 if(empty($_OPT['url'])) {
  $user = '<strong>' . $_OPT['name'] . "</strong>n";
 } else {
  $user = '<a href="' . $_OPT['url'] . '">' . $_OPT['name'] . "</a>n";
 }
return $user;
}
?>

If we were to issue that function, we’d get an error, as inside this function the $_OPT variables do not exist. To fix this, comes in the global keyword:

<?php
function getUser() {
 global $_OPT;
  if(empty($_OPT['url'])) {
  $user = '<strong>' . $_OPT['name'] . "</strong>n";
 } else {
  $user = '<a href="' . $_OPT['url'] . '">' . $_OPT['name'] . "</a>n";
 }
return $user;
}
?>

By including global $_OPT;, the function makes the variables global, which enables the function to use it without directly pulling them from a file. This method helps, especially if the functions file is included in the config file. To learn more about global, you can read more about it at PHP.net ».

Another method is including a file, which we will do through the more preferable version of this method, require() – it works in the same way include() does, except with better error processing (in which you can learn more about that at PHP.net »).

<?php
function getUser() {
 require("config.php");
 if(empty($_OPT['url'])) {
  $user = '<strong>' . $_OPT['name'] . "</strong>n";
 } else {
  $user = '<a href="' . $_OPT['url'] . '">' . $_OPT['name'] . "</a>n";
 }
return $user;
}
?>

As config.php is the file containing the $_OPT variables, we’re able to pull them directly from the file. Despite the fact that it’s not needed or necessary to include global and require() together, it can be done.

Keep Errors Clean

Most developers and coders are told (and sometimes tell themselves) to keep any PHP (or more specifically, MySQL) errors clean, and away from any revealing information, such as paths. Most beginners will often use something along the line of:

<?php
mysql_connect($databasehost, $databaseuser, $databasepass)
 or die(mysql_error());
?>

If in development stage, the errors can be very informative, however, if the script is public and at some point goes down, anybody can see the errors, and possibly paths, which can sometimes be dangerous.

I’ve done (and found it was successful) two ways of displaying errors “cleanly” and without giving too much information to the browser. The first is simply a paragraph (<p>) stating an error has occured:

<?php
$connect = mysql_connect($databasehost, $databaseuser, $databasepass)
 or die("<p>Error: The MySQL connection to the database failed.</p>n");
?>

Another way is through a function (what I would call, and for this example’s sake, displayError()), that can also help the script creator choose to make the errors public or not.

<?php
$connect = mysql_connect($databasehost, $databaseuser, $databasepass)
 or die(displayError('Database Error', 'Unable to connect to the database.', false));
?>

There are three parameters for this function: the title, the text and last, the true/false statement of the choice to display the MySQL errors.

<?php
function displayError($title, $body, $admin = true) {
 global $connect;

 echo "<h2>$title</h2>n";

 $bodies = explode('|', $body);
 foreach($bodies as $b) {
  echo "<p class="tb">" . $b . "</p>n");
 }

 if($admin) {
  echo "<h3>Debug Mode</h3>\n<p>There seems to be a few (hopefully minor) issues with the" .

  "script:</p>\n<p><span class=\"mysql\">MySQL Errors:</span>" . mysql_error($connect);
 }
}
?>

The function echoes the title and error text, and then provides the MySQL error if $admin (the third parameter) is set to true. I’ve also set $connect globally (global $connect;), as it’ll globally set $connect, allowing the MySQL errors to echo from the most recent MySQL query from any page in the script. You can read more about error handling and certain functions associated with it at PHP.net ».

In Conclusion

Like » Understanding PHP, this is a work-in-progress, and will be updated if/when I think of more tips, as a lot has been covered from different webmasters.

Posted by Austin

Posted on March 16th, 2023

Posted under

  • Articles
  • PHP: Tips and Tricks
  • Understanding PHP
  • Search

    Back to Top ↑