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.
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 isinteger
andboolean
respectively. But for type-hinting for such variables you need to useint
andbool
. Otherwise PHP won't give you a syntax error, but it will expectinteger
andboolean
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)See also: Outputting the Value of a Variable
Autoloading, as part of a framework strategy, eases the amount of boilerplate code you have to write.
E-Mail I'm sending through my script never arrives. What should I do?
Make sure you have error reporting turned on to see any errors.
If you have access to PHP's error log files, check those.
Is the mail()
command configured properly on your server? (If you are on shared hosting, you can not change anything here.)
If E-Mails are just disappearing, start an E-Mail account with a freemail service that has a spam folder (or use a mail account that does no spam filtering at all). This way, you can see whether the E-Mail is not getting sent out, or perhaps sent out but filtered as spam.
Did you check the "from:" address you used for possible "returned to sender" mails? You can also set up a separate bounce address for error mails.
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.
Note that calling session_start()
even if the session has already started will result in a PHP warning.
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 may have properties, constants and methods.
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 FooBar {
const FOO_VALUE = 'bla';
public function doAnything();
}
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.
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:
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.
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):
Option | Details |
---|---|
location | URL of SOAP server. Required in non-WSDL mode. Can be used in WSDL mode to override the URL. |
uri | Target namespace of SOAP service. Required in non-WSDL mode. |
style | Possible values are SOAP_RPC or SOAP_DOCUMENT . Only valid in non-WSDL mode. |
use | Possible values are SOAP_ENCODED or SOAP_LITERAL . Only valid in non-WSDL mode. |
soap_version | Possible values are SOAP_1_1 (default) or SOAP_1_2 . |
authentication | Enable HTTP authentication. Possible values are SOAP_AUTHENTICATION_BASIC (default) or SOAP_AUTHENTICATION_DIGEST . |
login | Username for HTTP authentication |
password | Password for HTTP authentication |
proxy_host | URL of proxy server |
proxy_port | Proxy server port |
proxy_login | Username for proxy |
proxy_password | Password for proxy |
local_cert | Path to HTTPS client cert (for authentication) |
passphrase | Passphrase for HTTPS client cert |
compression | Compress 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 . |
encoding | Internal character encoding (TODO: possible values) |
trace | Boolean, defaults to FALSE . Enables tracing of requests so faults can be backtraced. Enables use of __getLastRequest() , __getLastRequestHeaders() , __getLastResponse() and __getLastResponseHeaders() . |
classmap | Map WSDL types to PHP classes. Value should be an array with WSDL types as keys and PHP class names as values. |
exceptions | Boolean value. Should SOAP errors exceptions (of type `SoapFault). |
connection_timeout | Timeout (in seconds) for the connection to the SOAP service. |
typemap | Array 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_wsdl | How (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_agent | String to use in the User-Agent header. |
stream_context | A resource for a context. |
features | Bitmask 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 to2147483647
. To work around this, cast the strings to float before passing it in to__soapCall()
.
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'
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.
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.
root
. Packages are not to be trusted.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;
Most filenames passed to functions in this topic are:
SplFileInfo
, which is the value in the iteration of DirectoryIterator
.scheme://
to specify the protocol wrapper to manage with. For example, file_get_contents("http://example.com")
retrieves content from http://example.com.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 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:
Name | Description |
---|---|
__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 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
With
pthreads
v3pthreads
can only be loaded when using thecli
SAPI, thus it is a good practice to keep theextension=pthreads.so
directive inphp-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
Operators 'operate' or act on one (unary operators such as !$a
and ++$a
), two (binary operators such as $a + $b
or $a >> $b
) or three (the only ternary operator is $a ? $b : $c
) expressions.
Operator precedence influences how operators are grouped (as if there were parentheses). The following is a list of operators in order of there precendence (operators in the second column). If multiple operators are in one row, the grouping is determined by the code order, where the first column indicates the associativity (see examples).
Association | Operator |
---|---|
left | -> :: |
none | clone new |
left | [ |
right | ** |
right | ++ -- ~ (int) (float) (string) (array) (object) (bool) @ |
none | instanceof |
right | ! |
left | * / % |
left | + - . |
left | << >> |
none | < <= > >= |
none | == != === !== <> <=> |
left | & |
left | ^ |
left | | |
left | && |
left | || |
right | ?? |
left | ? : |
right | = += -= *= **= /= .= %= &= ` |
left | and |
left | xor |
left | or |
Full information is at Stack Overflow.
Note that functions and language constructs (e.g. print
) are always evaluated first, but any return value will be used according to the above precedence/associativity rules. Special care is needed if the parentheses after a language construct are omitted. E.g. echo 2 . print 3 + 4;
echo's 721
: the print
part evaluates 3 + 4
, prints the outcome 7
and returns 1
. After that, 2
is echoed, concatenated with the return value of print
(1
).
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.
You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring
extension.
PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring
function.
All PHP types except for resources are serializable. Resources are a unique variable type that reference "external" sources, such as database connections.
"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.
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.
Regex should be used for other uses besides getting strings out of strings or otherwise cutting strings into pieces.
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.
Serialization uses following string structures:
[..]
are placeholders.
Type | Structure |
---|---|
String | s:[size of string]:[value] |
Integer | i:[value] |
Double | d:[value] |
Boolean | b:[value (true = 1 and false = 0)] |
Null | N |
Object | O:[object name size]:[object name]:[object size]:{[property name string definition]:[property value definition];(repeated for each property)} |
Array | a:[size of array]:{[key definition];[value definition];(repeated for each key value pair)} |
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.
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.
The mysqli interface has a number of benefits, the key enhancements over the mysql extension being:
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.
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.
Unit
tests are used for testing source code to see if it contains deals with inputs as we expect. Unit
tests are supported by the majority of frameworks. There are several different PHPUnit tests and they might differ in syntax. In this example we are using PHPUnit
.
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
.
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.
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:
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.
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.
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:
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.
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.
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.
The SQLSRV driver is a Microsoft supported PHP extension that allows you to access Microsoft SQL Server and SQL Azure databases. It is an alternative for the MSSQL drivers that were deprecated as of PHP 5.3, and have been removed from PHP 7.
The SQLSRV extension can be used on the following operating systems:
The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link at the "Requirements" documentation page.
To download the latest SQLSRV drivers, go to the following: Download
A full list of system requirements for the SQLSRV Drivers can be found here: System Requirements
Those using SQLSRV 3.1+ must download the Microsoft ODBC Driver 11 for SQL Server
PHP7 users can download the latest drivers from GitHub
Microsoft® ODBC Driver 13 for SQL Server supports Microsoft SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016 (Preview), Analytics Platform System, Azure SQL Database and Azure SQL Data Warehouse.
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.
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.
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
or any other resource available via PHP's stream wrappers.
Examples of available stream wrappers (schemes
):
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.
Method | Advantage |
---|---|
foreach | The simplest method to iterate an array. |
foreach by reference | Simple method to iterate and change elements of an array. |
for with incremental index | Allows iterating the array in a free sequence, e.g. skipping or reversing multiple elements |
Internal array pointers | It is no longer necessary to use a loop (so that it can iterate once every function call, signal receive, etc.) |
/* 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);
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();
}
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 stringsprint
- Outputs a string and returns 1
(always)printf
- Outputs a formatted string and returns the length of the outputted stringsprintf
- Formats a string and returns the formatted stringprint_r
- Outputs or returns content of the argument as a human-readable stringvar_dump
- Outputs human-readable debugging information about the content of the argument(s) including its type and valuevar_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 toObject 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.
Keep the following tips in mind when deciding how to comment your code:
For all BC functions, if the scale
parameter is not set, it defaults to 0, which will make all operations integer operations.
This document assumes that docker is installed and the daemon running. You can refer to Docker installation to check on how to install the same.
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.