Useful Code Snippets / Tutorials – PHP

  • Remove or replace a block of text with definable starting and ending pattern.

    $temp = preg_replace(“‘

    ]*?>.*?

    ‘si”, “”, $temp);

  • Modify group of links.
    This could be useful, for example, if you have links to multiple articles on a website that then redesigns and thus all its URLs change.

    $temp = preg_replace(“/(.*)/i”, “3“, $temp);

  • What’s the easiest way to remove characters from the end of a

… [ Read more ]

Upload Images with PHP

Web developers who are just getting started often ask, “How can I upload images using PHP” The Web Developer How To – Upload Images Using PHP tutorial looks at the basics and shows you how you can install such a script on your website.

Bad Behavior / Bad Behaviour

Bad Behavior is a PHP-based solution for blocking link spam and the robots which deliver it. It complements other link spam solutions by acting as a gatekeeper, preventing spammers from ever delivering their junk, and in many cases, from ever reading your site in the first place. This keeps your site’s load down, makes your site logs cleaner, and can … [ Read more ]

Single Line If…Else Statement

You undoubtedly are familiar with using if…else (if else) statements in your PHP programming. Are you also aware that for simple if…else needs (e.g., only needing to set one variable) you can get by using only one line of code?

The basic format of the one line if…else statement is:

$variable = (if statement) ? if true code : if false code;

Let’s illustrate with an example. … [ Read more ]

Running PHP Scripts in Command Mode

Most of the time, we write PHP scripts with the idea that they will be run directly in a browser (HTTP). Occasionally, we want to run a script directly from the command line (e.g., in a SSH environment or via a cron job). Unfortunately, running these scripts from the command line can cause problems since most HTTP environment variables are either not available in the … [ Read more ]

AJAX Select Box (Other) Form Element

If you’re like me, you have certain form fields that need to allow users to add an option. For example, if you wanted to ask a user filling out a form for their university, you can’t realistically expect to have a table with all the possibilities from around the world. Instead, you can have what I call a select box other field (a.k.a. list box), … [ Read more ]

Functions and Passing by Reference

A function can be written to accept parameters (variable) or not. A parameter name is local to a function unless you tell it otherwise by using the global statement. Thus, you can pass a parameter called $string and name the accepted parameter $string also and they won’t interfere with each other. For example

In the function above, $string outside of the function will remain “car” … [ Read more ]