0% found this document useful (0 votes)
83 views

PHP Cheat Sheet

Uploaded by

Alex Dobrij
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
83 views

PHP Cheat Sheet

Uploaded by

Alex Dobrij
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 43
Beginner’s Essential PHP CHEAT SHEET Fast, flexible and pragmatic scripting language. U WebsiteSetup Table of Contents PHP Basics Variables and Constants PHP Arrays - Grouped Values PHP Strings PHP Operators Loops in PHP Conditional Statements Working with Forms in PHP Regular Expressions PHP Functions PHP Filters HTTP Functions in PHP Working with MySQL. Date and Time PHP Errors 13 24 23 23 24 26 28 29 34 31 36 40 PHP BASICS Including PHP in a File Writing Comments Ws Denotes comments that only span on one line # Another way of producing single-line comments Tet Everything between /* and */ is not executed, also works across several lines Outputting Data PHP Cheat Sheet"; ?> Writing PHP Functions function NameOfTheFunction() { //place PHP code here ) VARIABLES AND CONSTANTS Defining Variables Types of Data Integers Integers are non-decimal numbers between -2,147,483,648 and 2,147,483,647. They must have at least one digit and no decimal point. Can be in decimal, hexadecimal or octal. Floats This is the name for numbers with a decimal point or in exponential form. Strings This simply means text, we will talk about it in detail further below. Boolean values Meaning true/false statements. Arrays Arrays are variables that store several values. We will talk about them in detail further below. Objects Objects store both data and information on how to process it. Resources These are references to functions and resources outside of PHP NULL A variable that is NULL doesn’t have any value Variable Scope function myFunction() { global $a, $b; $b = $a - $) Websitesetup Predefined Variables $GLOBALS Used to access global variables from anywhere inside a PHP script. $_SERVER Contains information about the locations of headers, paths and scripts. $Ger can collect data that was sent in the URL or submitted in an HTML form. $_Post Used to gather data from an BTML form and to pass variables $_REQUEST Also collects data after submitting an HTML form Variable-handling Functions boolval Used to retrieve the boolean value of a variable debug_zval_dump Outputs a string representation of an internal zend value empty Checks whether a variable is empty or not floatval Get the float value of a variable (doubleval is another possibility) get_defined_vars Returns an array of all defined variables get_resource_type Returns the resource type gettype Retrieves the variable type WebsiteSetuporg - Beginner's PHP Cheat Sheet import_request_variables Import GET/POST/Cookie variables into the global scope intval Find the integer value of a variable is_array Checks whether a variable is an array is_bool Finds out if a variable is a boolean of 538 is_callable Verify whether you can call the contents of a variable as a function is_countable Check whether the contents of a variable are countable is_float Find out if the type of a variable is float, alternatives: is double and is_real is_int Check if the type of a variable is an integer, is_integer and is_long also works is_iterable Verify that a variable’s content is an iterable value is_null Checks whether a variable’s value is NULL is_numeric Find out if a variable is a number or a numeric string is_object Determines whether a variable is an object Check if a variable is a resource is_scalar Tests if a variable is a scalar WebsiteSetup.org - Beginner's PHP Cheat Sheet is_string Find out whether the type of a variable is a string isset Determine if a variable has been set and is not NULL print: Provides human-readable information about a variable serialize Generates a representation of a value that is storable settype Sets a variable’s type strval Retrieves the string value of a variable unserialize Creates a PHP value from a stored representation unset Unsets a variable var_dump Dumps information about a variable var_export Outputs or returns a string representation of a variable that can be parsed Constants define(name, value, true/false) Aside from user-defined constants, there also a number of default PHP constants: ecIneee Denotes the number of the current line in a file perieee Is the full path and filename of the file VebsiteSetup.org - Beginner's PHP Che DIR The directory of the file _FUNCTION__ Name of the function CLASS. Class name, includes the namespace it was declared in __TRATT__ The trait name, also includes the namespace _METHOD__ ‘The class method name _NAMESPACE__ Name of the current namespace PHP ARRAYS - GROUPED VALUES Indexed arrays Arrays that have a numeric index Associative arrays Arrays where the keys are named Multidimensional arrays Arrays that contain one or more other arrays Declaring an Array in PHP Array Functions array_change_key case Changes all keys in an array to uppercase or lowercase Websitesetup 3 - Beginner's PHP Cheat Sheet array_chunk Splits an array into chunks array_column Retrieves the values from a single column in an array array_combine Merges the keys from one array and the values from another into a new array array_count_values Counts all values in an array array_diff Compares arrays, returns the difference (values only array diff assoc Compares arrays, returns the difference (values and keys) array diff key Compares arrays, returns the difference (keys only) array _diff_uassoc Compares arrays (keys and values) through a user callback function array _diff_ukey Compares arrays (keys only) through a user callback function array fill Fills an array with values array_fill_keys Fills an array with values, specifying keys array_filter Filters the elements of an array via a callback function array_flip Exchanges all keys in an array with their associated values array_intersect Compare arrays and return their matches (values only) WebsiteSetup.org - Beginner's PHP Cheat Sheet array_intersect_assoc Compare arrays and return their matches (keys and values) array_intersect_key Compare arrays and return their matches (keys only) array_intersect_uassoc Compare arrays via a user-defined callback function (keys and values) array_intersect_ukey Compare arrays via a user-defined callback function (keys only) array_key exists Checks if a specified key exists in an array, alternative: key_exists array_keys Returns all keys or a subset of keys in an array array_map Applies a callback to the elements of a given array array_merge Merge one or several arrays array_merge_recursive Merge one or more arrays recursively array_multisort Sorts multiple or multi-dimensional arrays array_pad Inserts a specified number of items (with a specified value) into an array array_pop Deletes an element from the end of an array array_product Calculate the product of all values in an array array_push Push one or several elements to the end of the array WebsiteSetup.org - Beginner's PHP Cheat Sheet array_rand Pick one or more random entries out of an array array_reduce Reduce the array to a single string using a user-defined function array_replace Replaces elements in the first array with values from following arrays array_replace_recursive Recursively replaces elements from later arrays into the first array array_reverse Returns an array in reverse order array_search Searches the array for a given value and returns the first key if successful array shift Shifts an element from the beginning of an array array_slice Extracts a slice of an array array_splice Removes a portion of the array and replaces it array_sum Calculate the sum of the values in an array array_udiff Compare arrays and return the difference using a user function (values only) array_udiff_assoc Compare arrays and return the difference using a default and a user function (keys and values) array_udiff_uassoc Compare arrays and return the difference using two user functions (values and keys) array _uintersect WebsiteSetuporg - Beginner's PHP Cheat Sheet 10 Compare arrays and return the matches via user function (values only) array_uintersect_assoc Compare arrays and return the matches via a default user function (keys and values) array_uintersect_uassoc Compare arrays and return the matches via two user functions (keys and values) array_unique Removes duplicate values from an array array_unshift Adds one or more elements to the beginning of an array array_values Returns all values of an array array_walk Applies a user function to every element in an array array _walk recursive Recursively applies a user function to every element of an array arsort Sorts an associative array in descending order according to the value asort Sorts an associative array in ascending order according to the value compact, Create an array containing variables and their values count, Count all elements in an array, alternatively use sizeof current Returns the current element in an array, an alternative is pos each Return the current key and value pair from an array end WebsiteSetuporg - Beginner's PHP Cheat Sheet " Set the extract internal pointer to the last element of an array Import variables from an array into the current symbol table in_array Checks if a value exists in an arraykeyFetches a key from an array krsort Sorts an associative array by key in reverse order ksort Sorts an associative array by key list Assigns variables as if they were an array natcasesort Sorts an array using a “natural order” algorithm independent of case natsort Sorts an array using a “natural order” algorithm next Advance prev the internal pointer of an array Move the internal array pointer backwards range Creates reset Set the rsort Sort an shuffle Shuffle sort an array from a range of elements internal array pointer to its first element array in reverse order an array tuporg - Beginner's PHP Cheat Sheet 12 Sorts an indexed array in ascending order uasort Sorts an array with a user-defined comparison function uksort Arrange an array by keys using a user-defined comparison function usort Categorize an array by values using a comparison function defined by the user PHP STRINGS Defining Strings Single quotes This is the simplest way. Just wrap your text in ' markers and PHP will handle it as a string. Double quotes As an alternative you can use ". When you do, it’s possible to use the escape characters below to display special characters. heredoc Begin a string with <<< and an identifier, then put the string in a new line. Close it in another line by repeating the identifier. heredoc behaves like double-quoted strings. nowdoc Is what heredoc is for double-quoted strings but for single quotes. It works the same way and eliminates the need for escape characters. Escape Characters \n — Line feed \r - Carriage return \t — Horizontal tab \v — Vertical tab \e - Escape \f — Form feed \\ - Backsiash \g - Dollar sign WebsiteSetuporg - 8 13 \" = Single quote \" = Double quote \[0-71{1,3) — Character \x[0-9a-Fa-£]{1,2} | — Character \u{ [0-9A-Fa-£]+} - String as String Functions addcslashes () Returns a string with backslashes addslashes () Returns a string with backslashes be escaped bin2hex() in octal notation in hexadecimal notation UTF-8 representation in front of specified characters in front of characters that need to Converts a string of ASCII characters to hexadecimal values chop () Removes space or other characters chr () from the right end of a string Returns a character from a specified ASCII value chunk_split () Splits a string into a series of smaller chunks convert_cyr_string() Converts a string from a Cyrillic anotherconvert_uudecode () Decodes a uuencoded stringconvert_wuencode() Encodes a string using wuencodecount_chars () character set to Returns information about the characters in a string ere32() Calculates a 32-bit CRC for a string crypt () iteSetuporg - B ner’s PHP Cheat Sheet 14 Returns a hashed string echo() or echo '' Outputs one or several strings explode () Breaks down a string into an array Eprints () Writes a formatted string to a specified output stream get_html_translation_table() Returns the translation table used by htmlspecialchars() and htmlentities () hebrev() ‘Transforms Hebrew text to visual texthebrevc () Converts Hebrew text to visual text and implements HTML line breaks hex2bin() Translate hexadecimal values to ASCII characters html_entity_decode() Turns HTML entities to characters htmlentities () Converts characters to HTML entities htmlspecialchars decode () ‘Transforms special HTML entities to characters htmlspecialchars () Switches predefined characters to HTML entities implode () Retrieves a string from the elements of an array, same as join() lefirst () Changes a string’s first character to lowercase levenshtein() ner’s PHP Cheat Sheet 15 iteSetuporg - B Calculates the Levenshtein distance between two strings Localeconv() Returns information about numeric and monetary formatting for the locale Ltrim() Removes spaces or other characters from the left side of a string md5 () Calculates the MD5 hash of a string and returns it md5_file() Calculates the MD5 hash of a file metaphone () Provides the metaphone key of a string money_format () Returns a string as a currency string nl_langinfo() Gives specific locale information nl2br () Inserts HTML line breaks for each new line in a string number_format () Formats a number including grouped thousands ord() Returns the ASCII value of a string’s first character parse_str () Parses a string into variables print() Outputs one or several strings printé() outputs a formatted string quoted_printable_decode () ner’s PHP Cheat Sheet 16 iteSetuporg - B Converts a quoted-printable string to 8-bit binary Goes from 8-bit string to a quoted-printable string quotemeta() Returns a string with a backslash before metacharacters xtrim() Strips whitespace or other characters from the right side of a string setlocale() Sets locale information shal() calculates a string’s SHA-1 hash shal_file() Does the same for a file similar_text() Determines the similarity between two strings soundex () Calculates the soundex key of a string sprinté() Returns a formatted string sscan£() Parses input froma string according to a specified format str_getesv() Parses a CSV string into an array str_ireplace() Replaces specified characters in a string with specified replacements (case-insensitive) str_pad() Pads a string to a specified length str_repeat () ner’s PHP Cheat Sheet 7 iteSetuporg - B Repeats a string a preset number of times str_replace () Replaces specified characters in a string (case-sensitive) stx_rotl3() Performs ROT13 encoding on a string str_shuffle() Randomly shuffles the characters in a string str_split() Splits strings into arrays stx_word_count () Returns the number of words in a string strcasecmp () Case-insensitive comparison of two strings stremp () Binary safe string comparison (case sensitive) streoll() Compares two strings based on locale strespn () Returns the number of characters found in a string before the occurrence of specified characters strip_tags() Removes HTML and PHP tags from a string stripcslashes() Opposite of addeslashes() stripslashes () Opposite of addslashes () stripos() Finds the position of the first occurrence of a substring within a string (case insensitive) stristr() ner’s PHP Cheat Sheet 18 iteSetuporg - B Case-insensitive version of strstr () strien() Returns the length of a string strnatcasecmp() Case-insensitive comparison of two strings using a “natural order” algorithm strnatemp() Same as the aforementioned but case sensitive strncasecmp () String comparison of a defined number of characters (case insensitive) strnemp () Same as above but case-sensitive strpbek () Searches a string for any number of characters strpos () Returns the position of the first occurrence of a substring in a string (case sensitive) strrchr() Finds the last occurrence of a string within another string strrev() Reverses a string strripos() Finds the position of the last occurrence of a string’s substring (case insensitive) strpos () Same as strripos() but case sensitive strspn() The number of characters in a string with only characters from a specified list strstr () iteSetuporg - B ner’s PHP Cheat Sheet 19 Case-sensitive search for the first occurrence of a string inside another string strtok () Splits a string into smaller chunks strtolower () Converts all characters in a string to lowercase strtoupper () Same but for uppercase letters strtr() Translates certain characters in a string, alternative: strchr() substr() Returns a specified part of a string substr_compare () Compares two strings from a specified start position up to a certain length, optionally case sensitive substr_count () Counts the number of times a substring occurs within a string substr_replace() Replaces a substring with something else trim() Removes space or other characters from both sides of a string ucfirst () Transforms the first character of a string to uppercase ucwords () Converts the first character of every word in a string to uppercase véprinté() Writes a formatted string to a specified output stream vprinté () outputs a formatted string veprinté() WebsiteSetuporg - Beginner's PHP Cheat Sheet 20 Writes a formatted string to a variable wordwrap () Shortens a string to a given number of characters PHP OPERATORS Arithmetic Operators + Addition Subtraction Multiplication Division Modulo (the remainder of value divided by another) Exponentiation Assignment Operators = is is is ppooo voooT the the the the the same same same Comparison Operators Equal Identical Not equal Not equal Not identical Less than Greater than Less than or equal to Greater than or equal to Less than, equal to, or greater than Logical Operators and — or xor = sa Wo- and or Exclusive Not And or or ner's PH as as as voooe peooo 4 op oew eNets 2 Bitwise Operators 6 -And 1 — Or (inclusive or) . — Xor (exclusive or) ~ = Not << — Shift left >> — Shift right Error Control Operator You can use the @ sign to prevent expressions from generating error messages. This is often important for security reasons, for example to keep confidential information safe Execution Operator PHP supports one execution operator, which is ~* (backticks). These are not single-quotes! PHP will attempt to execute the contents of the backticks as a shell command. Increment/Decrement Operators +480 Increments a variable by one, then returns it Suet Returns a variable, then increments it by one --$0 Decrements the variable by one, returns it afterward $v-- Returns the variable then decrements it by one String Operators Used to concatenate (mean combine) arguments Used to append the argument on the right to the left-side argument s PHP Cheat Sheet 22 LOOPS IN PHP For Loop for (starting counter value; ending counter value; to increase) { // code to execute goes here ) Foreach Loop foreach ($InsertYourArrayName as $value) { /1 code to execute goes here y While Loop while (condition that must apply) { // code to execute goes here ) Do. .While Loop do { // code to execute goes here; } while (condition that must apply); CONDITIONAL STATEMENTS If Statement if (condition) { // code to execute if condition is met ) If. .Else if (condition) { // code to execute if condition is met } else { // code to execute if condition is not met , WebsiteSetuporg - Beginner's PHP Cheat Sheet increment by which 23 If..Elseif..Else if (condition) { // code to execute if condition is met } elseif (condition) { // code to execute if this condition is met } else { // code to execute if none of the conditions are met , Switch Statement switch (n) { case x: code to execute if n=x; break; case y: code to execute if break; code to execute if n=: break; // add more cases as needed default: code to execute if n is neither of the above; WORKING WITH FORMS IN PHP Using GET vs POST GET collects data via URL parameters. That means all variable names and their values are contained in the page address The advantage of this is that you're able to bookmark the information. Keep in mind that it also means that the information is visible to everyone. For that reason, GET is not suitable for sensitive information such as passwords. It also limits the amount of data that can be sent in ca 2000 characters. POST, on the other hand, uses the HTTP POST method to pass on variables. This makes the data invisible to third parties, as it is sent in the HTTP body. You are not able to bookmark it. WebsiteSetuporg - 8 24 With POST, there are no limits to the amount of information you can send. Aside from that, it also has advanced functionality and is therefore preferred by developers. Form Security PHP offers tools to thwart those attacks, namely: htmlspecialchars () txim() stripslashes () Required Fields, Error Messages and Data Validation Aside from that, PHP is able to define required fields (you can’t submit the form without filling them out), display error messages if some information is missing and to validate data. We have already talked about the necessary tools to do so. For example, you can simply define variables for your form fields and use the empty() function to check if they have values. After that, create a simple if/else statement to either send the submitted data or output an error message. ‘The next step is to check submitted data for validity. For that, PHP offers a number of filters such as FILTER_VALIDATE_EMAIL to make sure a submitted email address has the right format. Regular Expressions (RegEx) Syntax Sexp /w3schools/i"; RegEx Functions preg_match() Returns 1 if the pattern was found in the string and 0 if not preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0 25 preg_replace() Returns a new string where matched patterns have been replaced with another string RegEx Modifiers Performs a case-insensitive search Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line) u Enables correct matching of UTF-8 encoded patterns RegEx Patterns [abe] - Find one character from the options between the brackets [abe] - Find any character NOT between the brackets [0-9] - Find one character from the range 0 to 9 Metacharacters Find a match for any one of the patterns separated by | as in: cat|dog|fish Find just one instance of any character Finds a match as the beginning of a string as in: “Hello s Finds a match at the end of the string as in: World \a Find a digit \s Find a whitespace character tuporg - Beginner's PHP Cheat Sheet 26 \v Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b \ wane Find the Unicode character specified by the hexadecimal number xxxx Quantifiers nt Matches any string that contains at least one n Matches any string that contains zero or more occurrences of n Matches any string that contains zero or one occurrences of n n(x) Matches any string that contains a sequence of X n's n{x,y) Matches any string that contains a sequence of X to ¥ n's n{x,} Matches any string that contains a sequence of at least X n's Grouping Use parentheses ( ) to apply quantifiers to entire patterns. They cal also be used to select parts of the pattern to be used as a match. a7 WebsiteSetuporg - 8 PHP Functions * A function is a block of statements that can be used repeatedly in a program. * A function will not execute automatically when a page loads. * A function will be executed by a call to the function. syntax function functionName() { code to be executed; , functiontiane () Function Arguments "; ) > Default Argument Value "; + setHeight (350) ; setHeight(); // will use the default value of 50 setHeight (135) : setHeight (80) ; > Returning values " . sum(5, 10) . "
" sum(7, 13) . "

You might also like