PHP

Topics related to PHP:

Getting started with PHP

enter image description here

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source programming language. It is especially suited for web development. The unique thing about PHP is that it serves both beginners as well as experienced developers. It has a low barrier to entry so it is easy to get started with, and at the same time, it provides advanced features offered in other programming languages.

Open-Source

It's an open-source project. Feel free to get involved.

Language Specification

PHP has a language specification.

Supported Versions

Currently, there are three supported versions: 5.6, 7.0 and 7.1.

Each release branch of PHP is fully supported for two years from its initial stable release. After this two year period of active support, each branch is then supported for an additional year for critical security issues only. Releases during this period are made on an as-needed basis: there may be multiple point releases, or none, depending on the number of reports.

Unsupported Versions

Once the three years of support are completed, the branch reaches its end of life and is no longer supported.

A table of end of life branches is available.

Issue Tracker

Bugs and other issues are tracked at https://bugs.php.net/.

Mailing Lists

Discussions about PHP development and usage are held on the PHP mailing lists.

Official Documentation

Please help to maintain or to translate the official PHP documentation.

You might use the editor at edit.php.net. Check out our guide for contributors.

Variables

Type checking

Some of the documentation regarding variables and types mentions that PHP does not use static typing. This is correct, but PHP does some type checking when it comes to function/method parameters and return values (especially with PHP 7).

You can enforce parameter and return value type-checking by using type-hinting in PHP 7 as follows:

<?php

/**
 * Juggle numbers and return true if juggling was
 * a great success.
 */
function numberJuggling(int $a, int $b) : bool
{
    $sum = $a + $b;

    return $sum % 2 === 0;
}

Note: PHP's gettype() for integers and booleans is integer and boolean respectively. But for type-hinting for such variables you need to use int and bool. Otherwise PHP won't give you a syntax error, but it will expect integer and boolean classes to be passed.

The above example throws an error in case non-numeric value is given as either the $a or $b parameter, and if the function returns something else than true or false. The above example is "loose", as in you can give a float value to $a or $b. If you wish to enforce strict types, meaning you can only input integers and not floats, add the following to the very beginning of your PHP file:

<?php
declare('strict_types=1');

Before PHP 7 functions and methods allowed type hinting for the following types:

  • callable (a callable function or method)
  • array (any type of array, which can contain other arrays too)
  • Interfaces (Fully-Qualified-Class-Name, or FQDN)
  • Classes (FQDN)

See also: Outputting the Value of a Variable

Arrays

Functional Programming

Types

Autoloading Primer

Autoloading, as part of a framework strategy, eases the amount of boilerplate code you have to write.

Exception Handling and Error Reporting

Working with Dates and Time

Sending Email

E-Mail I'm sending through my script never arrives. What should I do?

The E-Mail I'm sending is getting filtered as spam. What should I do?

  • Does the sender address ("From") belong to a domain that runs on the server you send the E-Mail from? If not, change that.

    Never use sender addresses like [email protected]. Use reply-to if you need replies to arrive at a different address.

  • Is your server on a blacklist? This is a possibility when you're on shared hosting when neighbours behave badly. Most blacklist providers, like Spamhaus, have tools that allow you to look up your server's IP. There's also third party tools like MX Toolbox.

  • Some installations of PHP require setting a fifth parameter to mail() to add a sender address. See whether this might be the case for you.

  • If all else fails, consider using email-as-a-service such as Mailgun, SparkPost, Amazon SES, Mailjet, SendinBlue or SendGrid—to name a few—instead. They all have APIs that can be called using PHP.

Sessions

Note that calling session_start() even if the session has already started will result in a PHP warning.

Cookies

It is worth noting that mere invoking setcookie function doesn't just put given data into $_COOKIE superglobal array.

For example there is no point in doing:

setcookie("user", "Tom", time() + 86400, "/");
var_dump(isset($_COOKIE['user'])); // yields false or the previously set value

The value is not there yet, not until next page load. The function setcookie just says "with next http connection tell the client (browser) to set this cookie". Then when the headers are sent to the browser, they contain this cookie header. The browser then checks if the cookie hasn't expired yet, and if not, then in http request it sends the cookie to the server and that's when PHP receives it and puts the contents into $_COOKIE array.

Classes and Objects

Classes and Interface components

Classes may have properties, constants and methods.

  • Properties hold variables in the scope of the object. They may be initialized on declaration, but only if they contain a primitive value.
  • Constants must be initialized on declaration and can only contain a primitive value. Constant values are fixed at compile time and may not be assigned at run time.
  • Methods must have a body, even an empty one, unless the method is declared abstract.
class Foo {
    private $foo = 'foo'; // OK
    private $baz = array(); // OK
    private $bar = new Bar(); // Error!
}

Interfaces cannot have properties, but may have constants and methods.

  • Interface constants must be initialized on declaration and can only contain a primitive value. Constant values are fixed at compile time and may not be assigned at run time.
  • Interface methods have no body.
interface FooBar {
    const FOO_VALUE = 'bla';
    public function doAnything();
}

Password Hashing Functions

Prior to PHP 5.5, you may use the compatibility pack to provide the password_* functions. It is highly recommended that you use the compatibility pack if you are able to do so.

With or without the compatibility pack, correct Bcrypt functionality through crypt() relies on PHP 5.3.7+ otherwise you must restrict passwords to ASCII-only character sets.

Note: If you use PHP 5.5 or below you're using an unsupported version of PHP which does not receive any security updates anymore. Update as soon as possible, you can update your password hashes afterwards.

Algorithm Selection

Secure algorithms

Insecure algorithms

The following hashing algorithms are insecure or unfit for purpose and therefore should not be used. They were never suited for password hashing, as they're designed for fast digests instead of slow and hard to brute force password hashes.

If you use any of them, even including salts, you should switch to one of the recommended secure algorithms as soon as possible.

Algorithms considered insecure:

Some algorithms can be safely used as message digest algorithm to prove authenticity, but never as password hashing algorithm:

  • SHA-2
  • SHA-3

Note, strong hashes such as SHA256 and SHA512 are unbroken and robust, however it is generally more secure to use bcrypt or argon2 hash functions as brute force attacks against these algorithms are much more difficult for classical computers.

Output Buffering

JSON

  • json_decode handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded, json_decode returns null for invalid input, even though null is also a perfectly valid object for JSON to decode to. To prevent such problems you should always call json_last_error every time you use it.

SOAP Client

The SoapClient class is equipped with a __call method. This is not to be called directly. Instead this allows you to do:

$soap->requestInfo(['a', 'b', 'c']);

This will call the requestInfo SOAP method.


Table of possible $options values (Array of key/value pairs):

OptionDetails
locationURL of SOAP server. Required in non-WSDL mode. Can be used in WSDL mode to override the URL.
uriTarget namespace of SOAP service. Required in non-WSDL mode.
stylePossible values are SOAP_RPC or SOAP_DOCUMENT. Only valid in non-WSDL mode.
usePossible values are SOAP_ENCODED or SOAP_LITERAL. Only valid in non-WSDL mode.
soap_versionPossible values are SOAP_1_1 (default) or SOAP_1_2.
authenticationEnable HTTP authentication. Possible values are SOAP_AUTHENTICATION_BASIC (default) or SOAP_AUTHENTICATION_DIGEST.
loginUsername for HTTP authentication
passwordPassword for HTTP authentication
proxy_hostURL of proxy server
proxy_portProxy server port
proxy_loginUsername for proxy
proxy_passwordPassword for proxy
local_certPath to HTTPS client cert (for authentication)
passphrasePassphrase for HTTPS client cert
compressionCompress request / response. Value is a bitmask of SOAP_COMPRESSION_ACCEPT with either SOAP_COMPRESSION_GZIP or SOAP_COMPRESSION_DEFLATE. For example: SOAP_COMPRESSION_ACCEPT \| SOAP_COMPRESSION_GZIP.
encodingInternal character encoding (TODO: possible values)
traceBoolean, defaults to FALSE. Enables tracing of requests so faults can be backtraced. Enables use of __getLastRequest(), __getLastRequestHeaders(), __getLastResponse() and __getLastResponseHeaders().
classmapMap WSDL types to PHP classes. Value should be an array with WSDL types as keys and PHP class names as values.
exceptionsBoolean value. Should SOAP errors exceptions (of type `SoapFault).
connection_timeoutTimeout (in seconds) for the connection to the SOAP service.
typemapArray of type mappings. Array should be key/value pairs with the following keys: type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).
cache_wsdlHow (if at all) should the WSDL file be cached. Possible values are WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.
user_agentString to use in the User-Agent header.
stream_contextA resource for a context.
featuresBitmask of SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE, SOAP_WAIT_ONE_WAY_CALLS.
keep_alive(PHP version >= 5.4 only) Boolean value. Send either Connection: Keep-Alive header (TRUE) or Connection: Close header (FALSE).
ssl_method(PHP version >= 5.5 only) Which SSL/TLS version to use. Possible values are SOAP_SSL_METHOD_TLS, SOAP_SSL_METHOD_SSLv2, SOAP_SSL_METHOD_SSLv3 or SOAP_SSL_METHOD_SSLv23.

Issue with 32 bit PHP: In 32 bit PHP, numeric strings greater than 32 bits which are automatically cast to integer by xs:long will result in it hitting the 32 bit limit, casting it to 2147483647. To work around this, cast the strings to float before passing it in to __soapCall().

Reflection

Using cURL in PHP

Dependency Injection

XML

Regular Expressions (regexp/PCRE)

PHP regular expressions follow PCRE pattern standards, which are derived from Perl regular expressions.

All PCRE strings in PHP must be enclosed with delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Popular delimiters are ~, /, % for instance.

PCRE patterns can contain groups, character classes, character groups, look-ahead/look-behind assertions and escaped characters.

It is possible to use PCRE modifiers in the $pattern string. Some common ones are i (case insensitive), m (multiline) and s (the dot metacharacter includes newlines). The g (global) modifier is not allowed, you will use the preg_match_all function instead.

Matches to PCRE strings are done with $ prefixed numbered strings:

<?php

$replaced = preg_replace('%hello ([a-z]+) world%', 'goodbye $1 world', 'hello awesome world');

echo $replaced; // 'goodbye awesome world'

Traits

Namespaces

From the PHP documentation:

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

Note that top-level namespaces PHP and php are reserved for the PHP language itself. They should not be used in any custom code.

Parsing HTML

Composer Dependency Manager

Autoloading will only work for libraries that specify autoload information. Most libraries do and will adhere to a standard such as PSR-0 or PSR-4.

Helpful Links

Few Suggestions

  1. Disable xdebug when running Composer.
  2. Do not run Composer as root. Packages are not to be trusted.

Magic Methods

Alternative Syntax for Control Structures

When mixing the alternative structure for switch with HTML, it is important to not have any whitespace between the initial switch($condition): and first case $value:. Doing this is attempting to echo something (whitespace) before a case.

All control structures follow the same general idea. Instead of using curly braces to encapsulate the code, you're using a colon and endstructure; statement: structure: /* code */ endstructure;

File handling

Filename syntax

Most filenames passed to functions in this topic are:

  1. Strings in nature.
    • File names can be passed directly. If values of other types are passed, they are cast to string. This is especially useful with SplFileInfo, which is the value in the iteration of DirectoryIterator.
  2. Relative or absolute.
    • They may be absolute. On Unix-like systems, absolute paths start with /, e.g. /home/user/file.txt, while on Windows, absolute paths start with the drive, e.g. C:/Users/user/file.txt
    • They may also be relative, which is dependent on the value of getcwd and subject to change by chdir.
  3. Accept protocols.
    • They may begin with scheme:// to specify the protocol wrapper to manage with. For example, file_get_contents("http://example.com") retrieves content from http://example.com.
  4. Slash-compatible.
    • While the DIRECTORY_SEPARATOR on Windows is a backslash, and the system returns backslashes for paths by default, the developer can still use / as the directory separator. Therefore, for compatibility, developers can use / as directory separators on all systems, but be aware that the values returned by the functions (e.g. realpath) may contain backslashes.

Magic Constants

Magic constants are distinguished by their __CONSTANTNAME__ form.

There are currently eight magical constants that change depending on where they are used. For example, the value of __LINE__depends on the line that it's used on in your script.

These special constants are case-insensitive and are as follows:

NameDescription
__LINE__The current line number of the file.
__FILE__The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__The current function name
__CLASS__The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__The class method name.
__NAMESPACE__The name of the current namespace.

Most common use case for these constants is debugging and logging

Type hinting

Type hinting or type declarations are a defensive programming practice that ensures a function's parameters are of a specified type. This is particularly useful when type hinting for an interface because it allows the function to guarantee that a provided parameter will have the same methods as are required in the interface.

Passing the incorrect type to a type hinted function will lead to a fatal error:

Fatal error: Uncaught TypeError: Argument X passed to foo() must be of the type RequiredType, ProvidedType given

Multi Threading Extension

With pthreads v3 pthreads can only be loaded when using the cli SAPI, thus it is a good practice to keep the extension=pthreads.so directive in php-cli.ini ONLY, if you are using PHP7 and Pthreads v3.

If you are using Wamp on Windows, you have to configure the extension in php.ini :

Open php\php.ini and add:

extension=php_pthreads.dll

Concerning Linux users, you have to replace .dll by .so:

extension=pthreads.so

You can directly execute this command to add it to php.ini (change /etc/php.ini with your custom path)

echo "extension=pthreads.so" >> /etc/php.ini

Filters & Filter Functions

Generators

Operators

Constants

Constants are used to store the values that are not supposed to be changed later. They also are often used to store the configuration parameters especially those which define the environment (dev/production).

Constants have types like variables but not all types can be used to initialize a constant. Objects and resources cannot be used as values for constants at all. Arrays can be used as constants starting from PHP 5.6

Some constant names are reserved by PHP. These include true, false, null as well as many module-specific constants.

Constants are usually named using uppercase letters.

UTF-8

URLs

Object Serialization

All PHP types except for resources are serializable. Resources are a unique variable type that reference "external" sources, such as database connections.

PHPDoc

"PHPDoc" is a section of documentation which provides information on aspects of a "Structural Element" — PSR-5

PHPDoc annotations are comments that provide metadata about all types of structures in PHP. Many popular IDEs are configured by default to utilize PHPDoc annotations to provide code insights and identify possible problems before they arise.

While PHPDoc annotations are not part of the PHP core, they currently hold draft status with PHP-FIG as PSR-5.

All PHPDoc annotations are contained within DocBlocks that are demonstrated by a multi-line with two asterisks:

/**
 *
 */

The full PHP-FIG standards draft is available on GitHub.

Contributing to the PHP Manual

Contributions to this topic should mainly outline the process around contributing to the PHP Manual, e.g. explain how to add pages, how to submit them for review, finding areas to contribute content, too and so on.

String Parsing

Regex should be used for other uses besides getting strings out of strings or otherwise cutting strings into pieces.

Loops

It is often useful to execute the same or similar block of code several times. Instead of copy-pasting almost equal statements loops provide a mechanism for executing code a specific number of times and walking over data structures. PHP supports the following four types of loops:

  • for
  • while
  • do..while
  • foreach

To control these loops, continue and break statements are available.

Control Structures

Serialization

Serialization uses following string structures:

[..] are placeholders.

TypeStructure
Strings:[size of string]:[value]
Integeri:[value]
Doubled:[value]
Booleanb:[value (true = 1 and false = 0)]
NullN
ObjectO:[object name size]:[object name]:[object size]:{[property name string definition]:[property value definition];(repeated for each property)}
Arraya:[size of array]:{[key definition];[value definition];(repeated for each key value pair)}

Closure

Reading Request Data

Choosing between GET and POST

GET requests, are best for providing data that's needed to render the page and may be used multiple times (search queries, data filters...). They are a part of the URL, meaning that they can be bookmarked and are often reused.

POST requests on the other hand, are meant for submitting data to the server just once (contact forms, login forms...). Unlike GET, which only accepts ASCII, POST requests also allow binary data, including file uploads.

You can find a more detailed explanation of their differences here.

Request Data Vulnerabilities

Also look at: what are the vulnerabilities in direct use of GET and POST?

Retrieving data from the $_GET and $_POST superglobals without any validation is considered bad practice, and opens up methods for users to potentially access or compromise data through code and or SQL injections. Invalid data should be checked for and rejected as to prevent such attacks.

Request data should be escaped depending on how it is being used in code, as noted here and here. A few different escape functions for common data use cases can be found in this answer.

Type juggling and Non-Strict Comparison Issues

Security

PHP MySQLi

Features

The mysqli interface has a number of benefits, the key enhancements over the mysql extension being:

  • Object-oriented interface
  • Support for Prepared Statements
  • Support for Multiple Statements
  • Support for Transactions
  • Enhanced debugging capabilities
  • Embedded server support

It features a dual interface: the older, procedural style and a new, object-oriented programming (OOP) style. The deprecated mysql had only a procedural interface, so the object-oriented style is often preferred. However, the new style is also favorable because of the power of OOP.

Alternatives

An alternative to the mysqli interface to access databases is the newer PHP Data Objects (PDO) interface. This features only OOP-style programming and can access more than only MySQL-type databases.

Command Line Interface (CLI)

Localization

Debugging

Superglobal Variables PHP

Unit Testing

Variable Scope

References

While assigning two variables by reference, both variables point to the same value. Take the following example:

$foo = 1;
$bar = &$foo;

$foo does not point to $bar. $foo and $bar both point to the same value of $foo, which is 1. To illustrate:

$baz = &$bar;
unset($bar);
$baz++;

If we had a points to relationship, this would be broken now after the unset(); instead, $foo and $baz still point to the same value, which is 2.

Compilation of Errors and Warnings

Installing a PHP environment on Windows

HTTP services normally run on port 80, but if you have some application installed like Skype which also utilizes port 80 then it won't start. In that case you need to change either its port or the port of the conflicting application. When done, restart the HTTP service.

Datetime Class

Headers Manipulation

Performance

Common Errors

Installing on Linux/Unix Environments

Contributing to the PHP Core

PHP is an open source project, and as such, anyone is able to contribute to it. Broadly speaking, there are two ways to contribute to the PHP core:

  • Bug fixing
  • Feature additions

Before contributing, however, it is important to understand how PHP versions are managed and released so that bug fixes and feature requests can target the correct PHP version. The developed changes can be submitted as a pull request to the PHP Github repository. Useful information for developers can be found on the "Get Involved" section of the PHP.net site and the #externals forum.

Contributing with Bug Fixes

For those looking to begin contributing to the core, it's generally easier to start with bug fixing. This helps to gain familiarity with PHP's internals before attempting to make more complex modifications to the core that a feature would require.

With respect to the version management process, bug fixes should target the lowest affected, whilst still supported PHP version. It's this version that bug fixing pull requests should target. From there, an internals member can merge the fix into the correct branch and then merge it upwards to later PHP versions as necessary.

For those looking to get started on resolving bugs, a list of bug reports can be found at bugs.php.net.

Contributing with Feature Additions

PHP follows an RFC process when introducing new features and making important changes to the language. RFCs are voted on by members of php.net, and must achieve either a simple majority (50% + 1) or a super majority (2/3 + 1) of the total votes. A super majority is required if the change affects the language itself (such as introducing a new syntax), otherwise only a simple majority is required.

Before RFCs can be put to vote, they must undergo a discussion period of at least 2 weeks on the official PHP mailing list. Once this period has finished, and there are no open issues with the RFC, it can then be moved into voting, which must last at least 1 week.

If a user would like to revive a previously rejected RFC, then they can do so only under one of the following two circumstances:

  • 6 months has passed from the previous vote
  • The author(s) make substantial enough changes to the RFC that would likely affect the outcome of the vote should the RFC be put to vote again.

The people who have the privilege to vote will either be contributors to PHP itself (and so have php.net accounts), or be representatives of the PHP community. These representatives are chosen by those with php.net accounts, and will either be lead developers of PHP-based projects or regular participants to internals discussions.

When submitting new ideas for proposal, it is almost always required for the proposer to write, at the very least, a proof-of-concept patch. This is because without an implementation, the suggestion simply becomes another feature request that is unlikely to be fulfilled in the near future.

A thorough how-to of this process can be found at the official How To Create an RFC page.

Releases

Major PHP versions have no set release cycle, and so they may be released at the discretion of the internals team (whenever they see fit for a new major release). Minor versions, on the other hand, are released annually.

Prior to every release in PHP (major, minor, or patch), a series of release candidates (RCs) are made available. PHP does not use an RC as other projects do (i.e. if an RC has not problems found with it, then make it as the next final release). Instead, it uses them as a form of final betas, where typically a set number of RCs are decided before the final release is made.

Versioning

PHP generally attempts to follow semantic versioning where possible. As such, backwards compatibility (BC) should be maintained in minor and patch versions of the language. Features and changes that preserve BC should target minor versions (not patch versions). If a feature or change has the potential to break BC, then they should aim to target the next major PHP version (X.y.z) instead.

Each minor PHP version (x.Y.z) has two years of general support (so-called "active support") for all types of bug fixes. An additional year on top of that is added for security support, where only security-related fixes are applied. After the three years is up, support for that version of PHP is dropped completely. A list of currently supported PHP versions can be found at php.net.

Coding Conventions

Using MongoDB

Asynchronous programming

Using SQLSRV

Unicode Support in PHP

Functions

Create PDF files in PHP

How to Detect Client IP Address

YAML in PHP

Image Processing with GD

When using header("Content-Type: $mimeType"); and image____ to generate only an image to the output, be sure to output nothing else, note even a blank line after ?>. (That can be a difficult 'bug' to track down -- you get no image and no clue as to why.) The general advice is to not include ?> at all here.

Multiprocessing

SOAP Server

Machine learning

The topic uses PHP-ML for all machine learning algorithms. The installation of the library can be done using

composer require php-ai/php-ml

The github repository for the same can be found here.

Also it is worth noting that the examples given are very small data-set only for the purpose of demonstration. The actual data-set should be more comprehensive than that.

Cache

Installation

You can install memcache using pecl

pecl install memcache

Streams

Streams are essentially a transfer of data between an origin and a destination, to paraphrase Josh Lockhart in his book Modern PHP.

The origin and the destination can be

  • a file
  • a command-line process
  • a network connection
  • a ZIP or TAR archive
  • temporary memory
  • standard input/output

or any other resource available via PHP's stream wrappers.

Examples of available stream wrappers (schemes):

  • file:// — Accessing local filesystem
  • http:// — Accessing HTTP(s) URLs
  • ftp:// — Accessing FTP(s) URLs
  • php:// — Accessing various I/O streams
  • phar:// — PHP Archive
  • ssh2:// — Secure Shell 2
  • ogg:// — Audio streams

The scheme (origin) is the identifier of the stream's wrapper. For example, for the file system this is file://. The target is the stream's data source, for example the file name.

Array iteration

Comparison of methods to iterate an array

MethodAdvantage
foreachThe simplest method to iterate an array.
foreach by referenceSimple method to iterate and change elements of an array.
for with incremental indexAllows iterating the array in a free sequence, e.g. skipping or reversing multiple elements
Internal array pointersIt is no longer necessary to use a loop (so that it can iterate once every function call, signal receive, etc.)

Cryptography

/* Base64 Encoded Encryption / $enc_data = base64_encode( openssl_encrypt($data, $method, $password, true, $iv) ); / Decode and Decrypt */ $dec_data = base64_decode( openssl_decrypt($enc_data, $method, $password, true, $iv) );

This way of doing the encryption and encoding would not work as presented as you are decrypting the code before unencoding the base 64.

You would need to do this in the opposite order.

/This way instead/ $enc_data=base64_encode(openssl_encrypt($data, $method, $pass, true, $iv)); $dec_data=openssl_decrypt(base64_decode($enc_data), $method, $pass, true, $iv);

PDO

Warning Do not miss to check for exceptions while using lastInsertId(). It can throw the following error:

SQLSTATE IM001 : Driver does not support this function

Here is how you should properly check for exceptions using this method :

// Retrieving the last inserted id
$id = null;

try {
    $id = $pdo->lastInsertId(); // return value is an integer    
}
catch( PDOException $e ) {
    echo $e->getMessage();
}

SQLite3

Sockets

Outputting the Value of a Variable

Variables in PHP come in a variety of types. Depending on the use case, you may want to output them to the browser as rendered HTML, output them for debugging, or output them to the terminal (if running an application via the command line).

Below are some of the most commonly used methods and language constructs to output variables:

  • echo - Outputs one or more strings
  • print - Outputs a string and returns 1 (always)
  • printf - Outputs a formatted string and returns the length of the outputted string
  • sprintf - Formats a string and returns the formatted string
  • print_r - Outputs or returns content of the argument as a human-readable string
  • var_dump - Outputs human-readable debugging information about the content of the argument(s) including its type and value
  • var_export - Outputs or returns a string rendering of the variable as valid PHP code, which can be used to recreate the value.

Note: When trying to output an object as a string, PHP will try to convert it into a string (by calling __toString() - if the object has such a method). If unavailable, an error similar to Object of class [CLASS] could not be converted to string will be shown. In this case, you'll have to inspect the object further, see: outputting-a-structured-view-of-arrays-and-objects.

String formatting

Compile PHP Extensions

mongo-php

Manipulating an Array

Executing Upon an Array

Processing Multiple Arrays Together

SPL data structures

Comments

IMAP

Using Redis with PHP

Imagick

SimpleXML

HTTP Authentication

Recipes

BC Math (Binary Calculator)

For all BC functions, if the scale parameter is not set, it defaults to 0, which will make all operations integer operations.

Docker deployment

WebSockets

APCu

Design Patterns

Secure Remeber Me

php mysqli affected rows returns 0 when it should return a positive integer

PHP Built in server

An example of router script is:

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
    return false;    // serve the requested resource as-is.
}  //the rest of you code goes here.

How to break down an URL

PSR