Tag Archives: PHP

MySQL Prepared Statements With PHP

You may already be familliar with the problem of MySQL Injection, a common exploit that can cause irreparible damage to a database.

You may not be aware of it, but there is an alternative to the “mysql_*” function set. The mysqli functions, for “MySQL Improved” are used in much the same way as their predecessor, but they have some advantages. One such advantage is “Prepared Statements,” a method of preparing a query that separates the data from the syntax.

Prepared Statements are a little harder to use, but they are more secure, and arguably easier to write and maintain.

Prepared Statements in PHP and MySQLi

Instead of grabbing and building the query string using things like $_GET[‘username’], we have ?’s instead. These ?’s separate the SQL logic from the data. The ?’s are place holders until the next line where we bind our parameters to be the username and password. The rest of the code is pretty much just calling methods which you can read about by following some of the links at the end of the article.


WordPress has a handy function, wp_redirect(), for sending a user to a different page. It’s an easier way to handle redirects than to invoce the header() function on your own.

To do a 301 redirect, it’s as simple as this:

wp_redirect('http://www.example.com/', 301);

Just make sure that the function is called before any output is sent to the browser, otherwise you will get a “headers already sent” error.

It’s a bit easier than the normal way to go about redirecting:

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com/");

The 301-type redirect means that the URL that the request is being forwarded to is the “real” URL, and that the client should recognize that. A 302, the default for both methods, is less preferable, designating a “temporary” redirect. Generally you should use a 301.

PHP Serialize() Function

Arrays certainly are useful. If you’re dealing with associative data, there’s no better tool for the job. Sometimes, you’ll run into cases where it would be useful to store an entire array in a field in a database. It’s not something you want to do if you can avoid it, by structuring your database’s tables more efficiently for example, but there are cases where it’s unavoidable.

That’s where serialize() comes in. You can pass an array to the function, and it will return a string that is essentially the array flattened and mashed down. You can then unserialize() it to obtain the full array once again.

$the_array = array( "Lorem", "Ipsum", "Dolor" );
$serialized = serialize($the_array);
print $serialized;

This will output a:3:{i:0;s:5:"Lorem";i:1;s:5:"Ipsum";i:2;s:5:"Dolor";}. It’s the whole array in string form, suitable for insertion into a database field. It will work with more complex arrays, of course, but simple is better for examples.

PHP Str_Replace() Function

Have you ever wanted to take a string and replace every occurance of a substring with something else? Regular Expression voodoo is what first comes to mind for a lot of PHP developers. But there is an easier way that just happens to be faster.

Str_Replace() accepts up to four parameters, three of which are required. The first is the substring to look for, the second is the substring to replace it with, and the third is the input string. (The optional fourth parameter is used to set a maximum amount or times to run the replace operation.) The function returns the new string.

You’re not limited to replacing a single substring either. You can pass arrays for the search and replace parameters.

Continue reading →

WordPress Dashboard Widgets API

Starting in WordPress 2.7, the Dashboard is totally customizable. You can drag the Dashboard widgets (not to be confused with sidebar widgets) around, and hide/show them.

Now what if you want to add your own widgets? Maybe your plugin could use one, or you simply want to use the functions.php file to put a custom widget on your own blog.

There is a simple function, and accompanying hook, allowing you to add widgets to the Dashboard. It’s not exactly easy to find documentation for the functions, but it exists. You just need to look in the right place (in the WordPress Codex, of all places…).

WordPress Dashboard Widgets API

There you will find a nice overview and some code samples. Have fun. ;)

PHP Tip: Prevent SQL Injection

SQL Injection is one of the most common exploits. It’s a sneaky technique that takes advantage of unsafe database querying practices to gain access to the database.

Suppose you have a input form that asks for an email address for a newsletter subscription. The data is passed to the script, which inserts the data with the following:

$input = $_POST['email'];
mysql_query("INSERT INTO emails (email) VALUES('$input')");

Looks fine at a glance, doesn’t it? Well, it would if you’re new to the horrors of SQL injection. Note that the form field’s data is passed right along without any validation. That is not good. Some contempt-worthy person could come along and type something like this into the form:

Continue reading →

Learn Object Oriented PHP

PHP is the web programming language of choice (or scripting language, if you insist…) for many people, and my favorite as well. One thing I find interesting is when it’s taught, by many books and websites, they tend to not spend much time on Object-Oriented PHP. It’s deemed to be for “advanced” coders and left out.

As a result, I didn’t know much about how to work with classes and the like until more recently than was good. And I am still not quite comfortable with coding that way. It’s going to take some time to get used to.

The Object Oriented approach to writing in PHP isn’t too hard to grasp theory-wise, though there are some odd things about it, and it takes a bit of practice to get the hang of. If you haven’t brushed-up on it yet, now’s a good time.

Here are a few good tutorials:

Markdown in PHP

HTML isn’t exactly easy for ordinary people to comprehend and use correctly, and allowing it’s use in web forms then entails measures to be taken to prevent malicious code from being inserted.

The infamous John Gruber came up with Markdown, with the help of Aaron Swartz, and whether they intended it to be or not, they came up with the solution to our problem. Using Markdown formatting, you can make text italics by putting an *asterisk* on either side, or bold by using **two.** Blockquotes are as simple as putting a “>” before a paragraph of text. Links are a little more complicated, but they’re easier to do than with straight HTML for the average user.

Markdown is a nifty solution for allowing users of a website to format their input, and it’s gained a good measure of popularity. Reddit is one site that makes use of it for it’s comment forms.

Markdown-enabling a website isn’t too hard for someone with a bit of coding experience. You first need to find an implementation for the language of your choice, unless you want to write your own. Daring Fireball has a Perl implementation right on the Markdown homepage, but what if you’re like me and prefer PHP? Download a copy of PHP Markdown. The script functions like an ordinary PHP library, or as a WordPress plugin, enabling you to use Markdown in comments and the Post Editor.

Using Markdown in your own PHP script is as simple as including markdown.php and passing any Markdown-formatted text through a function to convert it to straight HTML.

include_once "markdown.php";
$my_html = Markdown($my_text);

I would also recommend additionally using the strip_tags PHP function to first remove any HTML tags someone may have put in.

Or you could use the WMD Editor, which applies a JavaScript formatting bar to an input form, allowing the contents to be formatted with Markdown. It then spits out full HTML for the form when it is submitted.

PHP Explode()

Explode() is a widely-used PHP string function that is also one that tends to mystify beginners looking at others’ code. It’s a nifty little function that you may find plenty of uses for once you know how it works.

Explode() takes two arguments, a delimiter and the string you wish to operate on, then returns an array. The function splits a string into multiple pieces at the delimiter, and puts each piece into a numerical array.

Have a list of comma-separated words? (A scenario increasingly common now that “tagging” has become such a popular device.) You can pass a comma-delimited string to explode() with a delimiter of “,” and voila, you have an array containing each of the items.

$string = "lorem, ipsum, dolor";
$delimiter = ", ";
$array = explode($delimiter, $string);

Now you have a single-dimension numerical array with each list item in it. $array[0] would contain “lorem” and $array[1] would be “ipsum” and so on.

Continue reading →

PHP Tip: Replace URLs With Links

I was trawling through the PHP function reference the other day, looking for some information on regular expressions, when I happened across this gem:

$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\" rel=\"nofollow\">\\0</a>", $text);

It may look like gibberish at first, but if you look at it for awhile, you might be able to guess what it does.

Suppose you’re writing a PHP script that displays data, let’s use blog comments as an example. Sometimes the data being displayed may have a URL pasted into it by the user that submitted it. Wouldn’t it be nicer for the end user if URLs like that were automatically turned into clickable links, so “http://google.com” would become “http://google.com?”

That’s exactly what this line of PHP code does. It takes the variable $text and parses through it, converting stray URLs into clickable links.