PHP: How do you delete an array element by its value?

unset($array[$key]) assumes you know the key. Often you only know the value, though. Then you have to look up the key first — and there is one line in that which is easy to get wrong.

PHP: How do you determine the current URL?

PHP has no ready-made variable holding the current URL. You assemble it from several parts of $_SERVER. The snippet for it is everywhere — and it contains a security hole you cannot see just by looking at it.

PHP: How do you generate a random string?

You need a random string again and again. For a file name, for a cache key or for a token. Depending on what you use it for, though, quite different things matter.

PHP: How do you get a file's extension?

There is a built-in function for the file extension, and it is the one to use. The short home-made variants you find alongside it return something wrong in two very everyday cases.

PHP: How do you get error messages to display?

You call your script and get a blank page. No message, no hint, nothing. That is one of the most frustrating moments in PHP development, and the fix consists of exactly two settings.

PHP: How do you get the client's IP address?

You need the visitor’s IP address for statistics, for block lists or for rate limiting. The answer looks simple, but there is exactly one reliable source for it — and several that only look like one.

PHP: How do you get the current date and time?

Printing the current date is one line of code. As soon as you calculate with it or display it in another time zone, though, a few things come along that are worth knowing.

PHP: How do you get the first element of an array?

$array[0] is the obvious attempt. It only works for some arrays, though, and for the others you get either a warning or a silent null. Since PHP 7.3 there has been a function that covers every case.

PHP: How do you parse HTML properly?

You want to pull one piece of information out of an HTML page, and you reach for the first tool that comes to mind: a regular expression. That usually goes wrong. PHP ships with everything you need for this job.

PHP: How do you prevent SQL injection?

If user input goes into an SQL query unchanged, your application is vulnerable to SQL injection. The answer is prepared statements. In this article we look at how exactly they work, and why escaping is not the right fix.