Php Cheat Sheet



Published on April 6, 2017
  1. Php Commands
  2. Php Cheat Sheet Pdf Download
  3. Mysql Cheat Sheet Commands
  4. Php Injection Cheat Sheet

A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set, and hence does not offer native Unicode support. Array: An array in PHP is actually an ordered map. A map is a type that associates values to keys. Object: callable: iterable: Iterable is a pseudo-type introduced in. This PHP cheat sheet collection is inspired by the Blueshoes cheat sheet and licensed under the GPLv3 software license. You can view and fork the source on GitHub. Pull requests welcome. PHP PCRE Cheat Sheet Functions pregmatch(pattern, subject, submatches) pregmatchall(pattern, subject, submatches) pregreplace(pattern, replacement, subject) pregreplacecallback(pattern.

PHP is perhaps the most popular general purpose scripting language for web developers, but its capabilities extend well beyond building websites. Of course, immense capabilities often come with a steep learning curve. Fortunately, PHP is straightforward enough for coding novices yet powerful enough for professional programmers.

Its massive list of features may seem intimidating at first; however, anyone with even very little knowledge of coding should be able to write simple PHP scripts. That said, no one can expect to become an expert overnight, so this PHP cheat sheet can help beginners and experts out in a pinch.

Authentication Cheat Sheet¶ Introduction¶. Authentication is the process of verifying that an individual, entity or website is whom it claims to be. Authentication in the context of web applications is commonly performed by submitting a username or ID and one or more items of private information that only a given user should know.

1. PHP basics

In case you need a quick crash course, this section will cover the very basics of PHP.

Unlike client side JavaScript, PHP code is executed on the server, which generates HTML to send to the client. Therefore, the client sees the results of the script but not the underlying code. It is possible to configure your server to process all HTML files with PHP so that users have no way of knowing what lies beneath.

PHP code is embedded into HTML and must be set off by the start and end processing instructions, <?php and ?>, as illustrated in the example below. The following code would output PHP goes here!:

The echo statement allows you to output strings, which are written within quotation marks and terminated with a semicolon.

According to W3Techs, more than 75% of web servers deploy PHP. However, because PHP is an open source language that has evolved naturally rather than being deliberately engineered, it's easy to design applications with security vulnerabilities. OWASP has a fantastic PHP security cheat sheet to ensure that your PHP-based application remains secure.

2. PHP modes

PHP scripts execute in multiple modes including the Apache module, CGI, and FastCGI. If you're using PHP for a project, this section can help you figure out where to start. There are alternatives, but these are the main ones:

I. mod_php (Apache module)

Using mod_php embeds the PHP interpreter in each Apache process when it spawns. Therefore, no external processes are need because Apache workers execute PHP scripts themselves. This comes in handy for websites that receive requests heavy with PHP code like WordPress, Drupal, or Joomla. The interpreter caches information so that the same tasks don't have to be repeated every time a script executes. The trade off is that Apache processes leave a bigger footprint as they eat up more memory.

mod_php benefits

  • No external processes needed
  • High performance for websites with a lot of PHP
  • Settings may be configured and customized within .htaccess directives

mod_php drawbacks

  • PHP interpreter gets loaded even with non-PHP content
  • Since files containing PHP scripts are often owned by the web server, you can't always edit them through FTP later on

II. CGI

Using a CGI application to execute PHP scripts is considered archaic, but it is still practical for a few purposes. The biggest benefit to using CGI is that code execution is kept separate from your server. Since the PHP interpreter only gets called when needed, static content remains secure on the server side; however, because a new process must be created wherever PHP code is used, this mode can get very resource intensive very fast. Therefore, CGI is not recommended for projects that rely heavily on PHP.

CGI benefits

  • More secure than mod_php

CGI drawbacks

  • Outdated performance

III. FastCGI

FastCGI offers a compromise between the security of CGI and the performance of mod_php. Scripts are executed by the interpreter outside of the server, and each request passes from the server to FastCGI through a network socket. The server and the PHP interpreter may then be split into separate environments, which improves scalability. The same goal can also be accomplished by using nginx in conjunction with mod_php so that nginx takes care of most non-dynamic requests.

The major limitation of running PHP with FastCGI is the inability to use PHP directives that have been defined in a .htaccess file, which many popular scripts require. If you are using a Plesk Panel server, you can work around this issue by setting PHP directives on a per domain basis using a custom php.ini file.

FastCGI benefits

  • Offers greater security than mod_php
  • Static content isn't processed by the PHP interpreter
  • Files may be managed by FTP users without the need for changing permissions afterwards

FastCGI drawbacks

  • PHP directives defined in .htaccess files cannot be used without a workaround
  • PHP requests are passed from the server

If you're working on a smaller project, feel free to use whichever mode you prefer. FastCGI is best suited for running CMS applications like WordPress while mod_php might be better if you rely on directives in .htaccess files, so long as you take extra security precautions.

3. PHP functions

Functions stand in for commonly used chunks of code so that you don't have to keep copying and pasting the same snippets over and over again. It would be impossible to comprehensively cover the long list of PHP functions in one article. Indeed, you can likely find a PHP cheat sheet geared toward any specific purpose you need. This section will provide in-depth explanations of commonly used functions.

I. String manipulation

strlen()

The strlen() function passes a string or variable and returns the number of characters including spaces. For example:

substr($string, $start, $length)

The substr() function returns a specified part of a string. There are three parameters that you can pass along.

  1. The first parameter, $string, is the name of the string or the variable containing the string.
  2. The second parameter, $start, designates which character you want to start from; entering 0 will indicate to start from the first character, 1 will start from the second character and so on. Entering a negative value will start counting backward from the end of the string.
  3. The third and final parameter, $length, indicates how many characters to return after $start. If a $length parameter isn't provided, the function returns the entire remainder of the string. When $length is less than or the same as the $start value, it simply returns false.
Mysql for dummies

Therefore, the function works as follows:

strtoupper()

The strtoupper() function converts strings to all uppercase while strtolower() converts strings to all lowercase, which comes in handy for case sensitive operations. For example:

strpos($haystack,$needle,$offset)

The strpos() function helps you determine the location of a substring within a larger string. There are three parameters.

  1. The first, $haystack, is the main string you wish to search.
  2. The second, $needle, is the specific cluster of characters you are seeking. These parameters alone will return the position of $needle expressed as a number.
  3. The third parameter, $offset, is optional. It must be a number indicating where to start the search from, so the value cannot be negative.

Notice how in the following example the last line returns false because the function is case sensitive:

The strpos() function can be used along with if statements as demonstrated below:

The above would echo Sorry! 'PHP' cannot be found in 'I am a string.'.

II. Arithmetic functions

round($val, $precision, $mode)

The round() function, as its name implies, rounds numbers that contain decimal points. You may round up or down to a whole number or a specified decimal place. Once again, there are three parameters.

  1. The first one, $val, is the value that you want to round.
  2. The next one, $precision, is optional as it indicates the number of decimal places to round to.
  3. The final one, $mode, indicates the type of rounding.

There are four options: PHP_ROUND_HALF_UP, PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, and PHP_ROUND_HALF_ODD. You can find more information about rounding and other functions in the PHP manual.

Two other math functions that have to do with rounding, ceil() and floor(), round up and down respectively. They provide an easier way to round to the nearest integer. For example:

III. Random number generation

rand($min, $max)

The rand() function returns a random number between two specified numbers. Its two parameters are both optional. The first, $min, sets the lowest value while the second, $max, sets the maximum. If no values are provided, $min defaults to 0 and $max returns getrandmax(). For example:

For some reason, some Windows systems set getrandmax() at 32767, but you can designate a larger $max value.

IV. Fun with array functions

The array() function obviously lets you store multiple values in one single variable, but there are plenty of additional array functions that you should keep in mind.

array_push($array, $value1, $value2)

The array_push() function adds new elements to the end of an array. You must choose the array and at least one value. There is no limit to how many values you can push.

An even easier way to do this is by listing each element in a single call. For example:

The two previous examples produce the same outcome. Now, if you echo array_push(), it returns the number of variables to be pushed into the array. If you then use the var_dump() function, it will return the following:

sort($array, $sort_flags)

sort() is another array function that does exactly what you think it does. After designating the array to be sorted, you have the option to set filters by entering a value for $sort_flags. The developer's manual has its own cheat sheet for $sort_flags. The function sorts alphabetically or numerically by default. For example:

join(glue, array) or implode(glue, array)

You must use the join() function to echo sorted arrays. The implode() function allows you to do the exact same thing, so the same rules reply to both functions.

The first parameter, glue, is actually optional; it indicates what to put between the variables. In the above example, glue is a comma. The second parameter is obviously the array you wish to sort.

rsort($array, $sort_flags)

The rsort() function does the same thing as sort() but in reverse. For example:

V. Advanced PHP functions

For information about more advanced PHP functions, Envato has a useful list of some lesser known capabilities of PHP.

4. PHP commands

PHP has all of the commands you'd expect in a scripting language, which are too numerous to cover in-depth here. Fortunately, 1Keydata has an excellent tutorial on PHP commands in addition to other information about how to use PHP to its full potential.

5. More PHP cheat sheet resources

You can find dozens of PHP cheat sheets for all types of specific purposes floating around online. Prophet Hacker has a large but by no means exhaustive list of the most popular guides. Here are a couple notable charts:

If you don't use PHP for all of your projects, it's easy to forget some of the ins-and-outs of the language. This article aimed to provide a quick reference for the most frequently used PHP functions and features. Feel free to come back whenever you need a refresher.

Regular expressions are a very useful tool for developers. They allow to find, identify or replace a word, character or any kind of string. This tutorial will teach you how to master PHP regexp and show you extremely useful, ready-to-use PHP regular expressions that any web developer should have in his toolkit.

Getting Started With Regular Expressions

For many beginners, regular expressions seem to be hard to learn and use. In fact, they’re far less hard than you may think. Before we dive deep inside regexp with useful and reusable codes, let’s quickly see the basics of PCRE regex patterns:

Regular Expressions Syntax

A regular expression (regex or regexp for short) is a special text string for describing a search pattern. A regex pattern matches a target string. The following table describes most common regex:

Regular ExpressionWill match…
fooThe string “foo”
^foo“foo” at the start of a string
foo$“foo” at the end of a string
^foo$“foo” when it is alone on a string
[abc]a, b, or c
[a-z]Any lowercase letter
[^A-Z]Any character that is not a uppercase letter
(gif|jpg)Matches either “gif” or “jpg”
[a-z]+One or more lowercase letters
[0-9.-]Any number, dot, or minus sign
^[a-zA-Z0-9_]{1,}$Any word of at least one letter, number or _
([wx])([yz])wy, wz, xy, or xz
[^A-Za-z0-9]Any symbol (not a number or a letter)
([A-Z]{3}|[0-9]{4})Matches three letters or four numbers

Php Commands

PHP Regular Expression Functions

PHP has many useful functions to work with regular expressions. Here is a quick cheat sheet of the main PHP regex functions. Remember that all of them are case sensitive.

For more information about the native functions for PHP regular expressions, have a look at the manual.

FunctionDescription
preg_match()The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all()The preg_match_all() function matches all occurrences of pattern in string. Useful for search and replace.
preg_replace()The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and replacement input parameters.
preg_split()Preg Split (preg_split()) operates exactly like the split() function, except that regular expressions are accepted as input parameters.
preg_grep()The preg_grep() function searches all elements of input_array, returning all elements matching the regex pattern within a string.
preg_ quote()Quote regular expression characters

Validate a Domain Name

Case sensitive regex to verify if a string is a valid domain name. This is very useful when validating web forms.

» Source

Enlight a Word From a Text

This very useful regular expression will find a specific word in a string and enlight it. Extremely useful for search results. Remember that it’s case sensitive.

» Source

Enlight Search Results in Your WordPress Blog

The previous code snippet can be very handy when it comes to displaying search results. If your website is powered by WordPress, here is a more specific snippet that will search and replace a text by the same text within an HTML tag that you can style later, using CSS.

Open your search.php file and find the the_title() function. Replace it with the following:

Now, just before the modified line, add this code:

Save the search.php file and open style.css. Append the following line to it:

» Source

Get All Images From a HTML Document

If you ever wanted to be able to get all images form a webpage, this code is a must have for you. You should easily create an image downloader using the power of cURL.

» Source

Remove Repeated Words (Case Insensitive)

Often repeating words while typing? This handy case insensitive PCRE regex will be very helpful.

» Source

Remove Repeated Punctuation

Same php regex as above, but this one will look for repeated punctuation within a string. Goodbye multiple commas!

» Source

Match a XML/HTML Tag

This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML. Once again, this can be very powerful used along with cURL.

Match an HTML/XML Tag With a Specific Attribute Value

This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match <div>.

Match Hexadecimal Color Values

Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.

Find Page Title

Php Cheat Sheet Pdf Download

This handy code snippet will find and print the text within the <title> and </title> tags of a HTML page.

Parse Apache Logs

Most websites are running on the Apache webserver. If your website does, you can easily use PHP and regular expressions to parse Apache logs.

» Source

Replace Double Quotes by Smart Quotes

If you’re a typography lover, you’ll probably love this regex pattern which allow you to replace double quotes by smart quotes. A similar regular expression is used by WordPress to make the content more beautiful.

» Source

Check Password Complexity

This regular expression will tests if the input consists of 6 or more letters, digits, underscores, and hyphens.
The input must contain at least one uppercase letter, one lowercase letter and one digit.

» Source

Mysql Cheat Sheet Commands

WordPress: Using Regexp to Retrieve Images From a Post

As I know many of you are WordPress users, you’ll probably enjoy that code which allows you to retrieve all images from post content and display it.

To use this code on your blog, simply paste the following code on one of your theme files.

Generate Emoticons Automatically

Php Injection Cheat Sheet

Another function used by WordPress. This one allow you to automatically replace an emoticon symbol by an image.





Comments are closed.