Editor's note: This post was originally published in 2015 and has been corrected and updated.
PHP is a widely used server-side scripting language that powers a large share of websites, including WordPress. It's popular because it's free, relatively easy to learn, and very capable. Here are some basics and tips to help you on your way. For interview prep, see our CakePHP interview questions.
How PHP Works
PHP lets you embed code directly in HTML. When a page is requested, the web server (such as Apache or Nginx) passes the PHP code to the PHP interpreter, which runs it and replaces it with its output. The server then sends the resulting HTML to the browser. Anything outside the <?php ... ?> tags is passed through as-is.
Syntax Basics
- Statements end with a semicolon. The semicolon can be omitted on the last line before a closing
?>tag, but it's good practice to always include it. - Comments: PHP supports single-line (
//or#) and multi-line (/* ... */) comments.
Variables
- Variables start with
$, followed by a letter or underscore — for example,$name. - Variable names are case-sensitive:
$Nameand$nameare different. - Assign values with
=. You can chain assignments:$a = $b = 5; - PHP is dynamically typed: it determines a variable's type automatically, so you don't have to declare it. (Modern PHP also supports type declarations for function parameters, return values, and properties.)
Data Types
PHP supports strings, integers, floats (numbers with decimals, like 25.5), booleans, arrays, objects, and null.
Strings are enclosed in single or double quotes. Use a backslash to escape quotes inside a string: "She said \"hi\"".
Operators
PHP includes arithmetic, comparison, string, logical, and assignment operators. The concatenation operator is a period: "Hello, " . $name. Use .= to append to a string.
Setting Up a Local Environment
For learning, install a local development stack: MAMP (Mac or Windows), XAMPP (cross-platform), or WAMP (Windows). These bundle PHP with a web server and MySQL database. Docker-based setups are also popular.
Why Use PHP?
PHP shines when you need dynamic output — content generated from a database, user input, or logic — which static HTML can't provide.
Security
Security is essential. Never trust user input:
- Escape output to prevent cross-site scripting (XSS), for example with
htmlspecialchars(). - Use prepared statements (PDO or MySQLi) to prevent SQL injection.
- Protect forms against cross-site request forgery (CSRF).
- Keep PHP and your libraries updated.
Need help with a PHP application or website? I.T. For Less can help — contact us.