Hello world!
PHP 5.x Version ≥ 5.4 echo also has a shortcut syntax, which lets you immediately print a value. Prior to PHP 5.4.0, this short syntax only works with the short_open_tag configuration setting enabled. For example, consider the following code:= "Hello world!" ?>
Its output is identical to the output of the following: In real-world applications, all data output by PHP to an HTML page should be properly escaped to prevent XSS (Cross-site scripting) attacks or text corruption. See also: Strings and PSR-1, which describes best practices, including the proper use of short tags (= ... ?>). Section 1.2: Hello, World! The most widely used language construct to print output in PHP is echo: echo "Hello, World!\n"; Alternatively, you can also use print: print "Hello, World!\n"; Both statements perform the same function, with minor differences: echo has a void return, whereas print returns an int with a value of 1 echo can take multiple arguments (without parentheses only), whereas print only takes one argument echo is slightly faster than print Both echo and print are language constructs, not functions. That means they do not require parentheses around their arguments. For cosmetic consistency with functions, parentheses can be included. Extensive examples of the use of echo and print are available elsewhere. C-style printf and related functions are available as well, as in the following example: printf("%s\n", "Hello, World!"); See Outputting the value of a variable for a comprehensive introduction of outputting variables in PHP. Section 1.3: Non-HTML output from web server In some cases, when working with a web server, overriding the web server's default content type may be required. There may be cases where you need to send data as plain text, JSON, or XML, for example. GoalKicker.com – PHP Notes for Professionals 3 The header() function can send a raw HTTP header. You can add the Content-Type header to notify the browser of the content we are sending. Consider the following code, where we set Content-Type as text/plain: header("Content-Type: text/plain"); echo "Hello World"; This will produce a plain text document with the following content: Hello World To produce JSON content, use the application/json content type instead: header("Content-Type: application/json"); // Create a PHP data array. $data = ["response" => "Hello World"]; // json_encode will convert it to a valid JSON string. echo json_encode($data); This will produce a document of type application/json with the following content: {"response":"Hello World"} Note that the header() function must be called before PHP produces any output, or the web server will have already sent headers for the response. So, consider the following code: // Error: We cannot send any output before the headers echo "Hello"; // All headers must be sent before ANY PHP output header("Content-Type: text/plain"); echo "World"; This will produce a warning: Warning: Cannot modify header information - headers already sent by (output started at /dir/example.php:2) in /dir/example.php on line 3 When using header(), its output needs to be the first byte that's sent from the server. For this reason it's important to not have empty lines or spaces in the beginning of the file before the PHP opening tag from files that contain only PHP and from blocks of PHP code at the very end of a file. View the output buffering section to learn how to 'catch' your content into a variable to output later, for example, after outputting headers. GoalKicker.com – PHP Notes for Professionals 4 Section 1.4: PHP built-in server PHP 5.4+ comes with a built-in development server. It can be used to run applications without having to install a production HTTP server such as nginx or Apache. The built-in server is only designed to be used for development and testing purposes. It can be started by using the -S flag: php -SSome HTML code goes here
Some HTML code goes here
PHP 5.x Version ≥ 5.4 Echo Tags These tags are available in all PHP versions, and since PHP 5.4 are always enabled. In previous versions, echo tags could only be enabled in conjunction with short tags. = "Hello World" ?> Short Tags You can disable or enable these tags with the option short_open_tag. GoalKicker.com – PHP Notes for Professionals 7 echo "Hello World"; ?> Short tags: are disallowed in all major PHP coding standards are discouraged in the official documentation are disabled by default in most distributions interfere with inline XML's processing instructions are not accepted in code submissions by most open source projects PHP 5.x Version ≤ 5.6 ASP Tags By enabling the asp_tags option, ASP-style tags can be used. <% echo "Hello World"; %> These are an historic quirk and should never be used. They were removed in PHP 7.0. GoalKicker.com – PHP Notes for Professionals 8 Chapter 2: Variables Section 2.1: Accessing A Variable Dynamically By Name (Variable variables) Variables can be accessed via dynamic variable names. The name of a variable can be stored in another variable, allowing it to be accessed dynamically. Such variables are known as variable variables. To turn a variable into a variable variable, you put an extra $ put in front of your variable. $variableName = 'foo'; $foo = 'bar'; // The following are all equivalent, and all output "bar": echo $foo; echo ${$variableName}; echo $$variableName; //similarly, $variableName = 'foo'; $$variableName = 'bar'; // The following statements will also output 'bar' echo $foo; echo $$variableName; echo ${$variableName}; Variable variables are useful for mapping function/method calls: function add($a, $b) { return $a + $b; } $funcName = 'add'; echo $funcName(1, 2); // outputs 3 This becomes particularly helpful in PHP classes: class myClass { public function __construct() { $functionName = 'doSomething'; $this->$functionName('Hello World'); } private function doSomething($string) { echo $string; // Outputs "Hello World" } } It is possible, but not required to put $variableName between {}: ${$variableName} = $value; The following examples are both equivalent and output "baz": $fooBar = 'baz'; GoalKicker.com – PHP Notes for Professionals 9 $varPrefix = 'foo'; echo $fooBar; // Outputs "baz" echo ${$varPrefix . 'Bar'}; // Also outputs "baz" Using {} is only mandatory when the name of the variable is itself an expression, like this: ${$variableNamePart1 . $variableNamePart2} = $value; It is nevertheless recommended to always use {}, because it's more readable. While it is not recommended to do so, it is possible to chain this behavior: $$$$$$$$DoNotTryThisAtHomeKids = $value; It's important to note that the excessive usage of variable variables is considered a bad practice by many developers. Since they're not well-suited for static analysis by modern IDEs, large codebases with many variable variables (or dynamic method invocations) can quickly become difficult to maintain. Differences between PHP5 and PHP7 Another reason to always use {} or (), is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases. In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed. Case 1 : $$foo['bar']['baz'] PHP5 interpretation : ${$foo['bar']['baz']} PHP7 interpretation : ($$foo)['bar']['baz'] Case 2 : $foo->$bar['baz'] PHP5 interpretation : $foo->{$bar['baz']} PHP7 interpretation : ($foo->$bar)['baz'] Case 3 : $foo->$bar['baz']() PHP5 interpretation : $foo->{$bar['baz']}() PHP7 interpretation : ($foo->$bar)['baz']() Case 4 : Foo::$bar['baz']() PHP5 interpretation : Foo::{$bar['baz']}() PHP7 interpretation : (Foo::$bar)['baz']() Section 2.2: Data Types There are different data types for different purposes. PHP does not have explicit type definitions, but the type of a variable is determined by the type of the value that is assigned, or by the type that it is casted to. This is a brief overview about the types, for a detailed documentation and examples, see the PHP types topic. There are following data types in PHP: null, boolean, integer, float, string, object, resource and array. GoalKicker.com – PHP Notes for Professionals 10 Null Null can be assigned to any variable. It represents a variable with no value. $foo = null; This invalidates the variable and it's value would be undefined or void if called. The variable is cleared from memory and deleted by the garbage collector. Boolean This is the simplest type with only two possible values. $foo = true; $bar = false; Booleans can be used to control the flow of code. $foo = true; if ($foo) { echo "true"; } else { echo "false"; } Integer An integer is a whole number positive or negative. It can be in used with any number base. The size of an integer is platform-dependent. PHP does not support unsigned integers. $foo = -3; // negative $foo = 0; // zero (can also be null or false (as boolean) $foo = 123; // positive decimal $bar = 0123; // octal = 83 decimal $bar = 0xAB; // hexadecimal = 171 decimal $bar = 0b1010; // binary = 10 decimal var_dump(0123, 0xAB, 0b1010); // output: int(83) int(171) int(10) Float Floating point numbers, "doubles" or simply called "floats" are decimal numbers. $foo = 1.23; $foo = 10.0; $bar = -INF; $bar = NAN; Array An array is like a list of values. The simplest form of an array is indexed by integer, and ordered by the index, with the first element lying at index 0. $foo = array(1, 2, 3); // An array of integers $bar = ["A", true, 123 => 5]; // Short array syntax, PHP 5.4+ GoalKicker.com – PHP Notes for Professionals 11 echo $bar[0]; // Returns "A" echo $bar[1]; // Returns true echo $bar[123]; // Returns 5 echo $bar[1234]; // Returns null Arrays can also associate a key other than an integer index to a value. In PHP, all arrays are associative arrays behind the scenes, but when we refer to an 'associative array' distinctly, we usually mean one that contains one or more keys that aren't integers. $array = array(); $array["foo"] = "bar"; $array["baz"] = "quux"; $array[42] = "hello"; echo $array["foo"]; // Outputs "bar" echo $array["bar"]; // Outputs "quux" echo $array[42]; // Outputs "hello" String A string is like an array of characters. $foo = "bar"; Like an array, a string can be indexed to return its individual characters: $foo = "bar"; echo $foo[0]; // Prints 'b', the first character of the string in $foo. Object An object is an instance of a class. Its variables and methods can be accessed with the -> operator. $foo = new stdClass(); // create new object of class stdClass, which a predefined, empty class $foo->bar = "baz"; echo $foo->bar; // Outputs "baz" // Or we can cast an array to an object: $quux = (object) ["foo" => "bar"]; echo $quux->foo; // This outputs "bar". Resource Resource variables hold special handles to opened files, database connections, streams, image canvas areas and the like (as it is stated in the manual). $fp = fopen('file.ext', 'r'); // fopen() is the function to open a file on disk as a resource. var_dump($fp); // output: resource(2) of type (stream) To get the type of a variable as a string, use the gettype() function: echo gettype(1); // outputs "integer" echo gettype(true); // "boolean" GoalKicker.com – PHP Notes for Professionals 12 Section 2.3: Global variable best practices We can illustrate this problem with the following pseudo-code function foo() { global $bob; $bob->doSomething(); } Your first question here is an obvious one Where did $bob come from? Are you confused? Good. You've just learned why globals are confusing and considered a bad practice. If this were a real program, your next bit of fun is to go track down all instances of $bob and hope you find the right one (this gets worse if $bob is used everywhere). Worse, if someone else goes and defines $bob (or you forgot and reused that variable) your code can break (in the above code example, having the wrong object, or no object at all, would cause a fatal error). Since virtually all PHP programs make use of code like include('file.php'); your job maintaining code like this becomes exponentially harder the more files you add. Also, this makes the task of testing your applications very difficult. Suppose you use a global variable to hold your database connection: $dbConnector = new DBConnector(...); function doSomething() { global $dbConnector; $dbConnector->execute("..."); } In order to unit test this function, you have to override the global $dbConnector variable, run the tests and then reset it to its original value, which is very bug prone: /** * @test */ function testSomething() { global $dbConnector; $bkp = $dbConnector; // Make backup $dbConnector = Mock::create('DBConnector'); // Override assertTrue(foo()); $dbConnector = $bkp; // Restore } How do we avoid Globals? The best way to avoid globals is a philosophy called Dependency Injection. This is where we pass the tools we need into the function or class. GoalKicker.com – PHP Notes for Professionals 13 function foo(\Bar $bob) { $bob->doSomething(); } This is much easier to understand and maintain. There's no guessing where $bob was set up because the caller is responsible for knowing that (it's passing us what we need to know). Better still, we can use type declarations to restrict what's being passed. So we know that $bob is either an instance of the Bar class, or an instance of a child of Bar, meaning we know we can use the methods of that class. Combined with a standard autoloader (available since PHP 5.3), we can now go track down where Bar is defined. PHP 7.0 or later includes expanded type declarations, where you can also use scalar types (like int or string). Version = 4.1 Superglobal variables Super globals in PHP are predefined variables, which are always available, can be accessed from any scope throughout the script. There is no need to do global $variable; to access them within functions/methods, classes or files. These PHP superglobal variables are listed below: $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_ENV $_COOKIE $_SESSION Section 2.4: Default values of uninitialized variables Although not necessary in PHP however it is a very good practice to initialize variables. Uninitialized variables have a default value of their type depending on the context in which they are used: Unset AND unreferenced var_dump($unset_var); // outputs NULL Boolean echo($unset_bool ? "true\n" : "false\n"); // outputs 'false' String $unset_str .= 'abc'; var_dump($unset_str); // outputs 'string(3) "abc"' Integer GoalKicker.com – PHP Notes for Professionals 14 $unset_int += 25; // 0 + 25 => 25 var_dump($unset_int); // outputs 'int(25)' Float/double $unset_float += 1.25; var_dump($unset_float); // outputs 'float(1.25)' Array $unset_arr[3] = "def"; var_dump($unset_arr); // outputs array(1) { [3]=> string(3) "def" } Object $unset_obj->foo = 'bar'; var_dump($unset_obj); // Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" } Relying on the default value of an uninitialized variable is problematic in the case of including one file into another which uses the same variable name. Section 2.5: Variable Value Truthiness and Identical Operator In PHP, variable values have an associated "truthiness" so even non-boolean values will equate to true or false. This allows any variable to be used in a conditional block, e.g. if ($var == true) { /* explicit version */ } if ($var) { /* $var == true is implicit */ } Here are some fundamental rules for different types of variable values: Strings with non-zero length equate to true including strings containing only whitepace such as ' '. Empty strings '' equate to false. $var = ''; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true $var = ' '; $var_is_true = ($var == true); // true $var_is_false = ($var == false); // false Integers equate to true if they are nonzero, while zero equates to false. $var = -1; $var_is_true = ($var == true); // true $var = 99; $var_is_true = ($var == true); // true $var = 0; $var_is_true = ($var == true); // false null equates to false $var = null; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true GoalKicker.com – PHP Notes for Professionals 15 Empty strings '' and string zero '0' equate to false. $var = ''; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true $var = '0'; $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true Floating-point values equate to true if they are nonzero, while zero values equates to false. NAN (PHP's Not-a-Number) equates to true, i.e. NAN == true is true. This is because NAN is a nonzero floating-point value. Zero-values include both +0 and -0 as defined by IEEE 754. PHP does not distinguish between +0 and -0 in its double-precision floating-point, i.e. floatval('0') == floatval('-0') is true. In fact, floatval('0') === floatval('-0'). Additionally, both floatval('0') == false and floatval('-0') == false. $var = NAN; $var_is_true = ($var == true); // true $var_is_false = ($var == false); // false $var = floatval('-0'); $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true $var = floatval('0') == floatval('-0'); $var_is_true = ($var == true); // false $var_is_false = ($var == false); // true IDENTICAL OPERATOR In the PHP Documentation for Comparison Operators, there is an Identical Operator ===. This operator can be used to check whether a variable is identical to a reference value: $var = null; $var_is_null = $var === null; // true $var_is_true = $var === true; // false $var_is_false = $var === false; // false It has a corresponding not identical operator !==: $var = null; $var_is_null = $var !== null; // false $var_is_true = $var !== true; // true $var_is_false = $var !== false; // true The identical operator can be used as an alternative to language functions like is_null(). USE CASE WITH strpos() The strpos($haystack, $needle) language function is used to locate the index at which $needle occurs in $haystack, or whether it occurs at all. The strpos() function is case sensitive; if case-insensitive find is what you need you can go with stripos($haystack, $needle) The strpos & stripos function also contains third parameter offset (int) which if specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos and strripos, the offset cannot be GoalKicker.com – PHP Notes for Professionals 16 negative The function can return: 0 if $needle is found at the beginning of $haystack; a non-zero integer specifying the index if $needle is found somewhere other than the beginning in $haystack; and value false if $needle is not found anywhere in $haystack. Because both 0 and false have truthiness false in PHP but represent distinct situations for strpos(), it is important to distinguish between them and use the identical operator === to look exactly for false and not just a value that equates to false. $idx = substr($haystack, $needle); if ($idx === false) { // logic for when $needle not found in $haystack } else { // logic for when $needle found in $haystack } Alternatively, using the not identical operator: $idx = substr($haystack, $needle); if ($idx !== false) { // logic for when $needle found in $haystack } else { // logic for when $needle not found in $haystack } GoalKicker.com – PHP Notes for Professionals 17 Chapter 3: Variable Scope Variable scope refers to the regions of code where a variable may be accessed. This is also referred to as visibility. In PHP scope blocks are defined by functions, classes, and a global scope available throughout an application. Section 3.1: Superglobal variables Superglobal variables are defined by PHP and can always be used from anywhere without the global keyword. string 'localhost' (length=9) 'HTTP_CONNECTION' => string 'keep-alive' (length=10) 'HTTP_CACHE_CONTROL' => string 'max-age=0' (length=9) 'HTTP_UPGRADE_INSECURE_REQUESTS' => string '1' (length=1) 'HTTP_USER_AGENT' => string 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36' (length=110) 'HTTP_ACCEPT' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' (length=74) 'HTTP_ACCEPT_ENCODING' => string 'gzip, deflate, sdch, br' (length=23) 'HTTP_ACCEPT_LANGUAGE' => string 'en-US,en;q=0.8,en-GB;q=0.6' (length=26) 'HTTP_COOKIE' => string 'PHPSESSID=0gslnvgsci371ete9hg7k9ivc6' (length=36) 'PATH' => string 'C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem ;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;E:\Program Files\ATI Technologies\ATI.ACE\Core Static;E:\Program Files\AMD\ATI.ACE\Core-Static;C:\Program Files (x86)\AMD\ATI.ACE\Core Static;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\Intel(R) Managemen'... (length=1169) 'SystemRoot' => string 'C:\WINDOWS' (length=10) 'COMSPEC' => string 'C:\WINDOWS\system32\cmd.exe' (length=27) 'PATHEXT' => string '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY' (length=57) 'WINDIR' => string 'C:\WINDOWS' (length=10) 'SERVER_SIGNATURE' => string 'Apache/2.4.23 (Win64) PHP/7.0.10 Server at localhost Port 80' (length=80) 'SERVER_SOFTWARE' => string 'Apache/2.4.23 (Win64) PHP/7.0.10' (length=32) 'SERVER_NAME' => string 'localhost' (length=9) 'SERVER_ADDR' => string '::1' (length=3) 'SERVER_PORT' => string '80' (length=2) 'REMOTE_ADDR' => string '::1' (length=3) 'DOCUMENT_ROOT' => string 'C:/wamp64/www' (length=13) 'REQUEST_SCHEME' => string 'http' (length=4) 'CONTEXT_PREFIX' => string '' (length=0) 'CONTEXT_DOCUMENT_ROOT' => string 'C:/wamp64/www' (length=13) 'SERVER_ADMIN' => string '[email protected]' (length=29) 'SCRIPT_FILENAME' => string 'C:/wamp64/www/test.php' (length=26) 'REMOTE_PORT' => string '5359' (length=4) 'GATEWAY_INTERFACE' => string 'CGI/1.1' (length=7) 'SERVER_PROTOCOL' => string 'HTTP/1.1' (length=8) 'REQUEST_METHOD' => string 'GET' (length=3) 'QUERY_STRING' => string '' (length=0) 'REQUEST_URI' => string '/test.php' (length=13) 'SCRIPT_NAME' => string '/test.php' (length=13) 'PHP_SELF' => string '/test.php' (length=13) 'REQUEST_TIME_FLOAT' => float 1491068771.413 'REQUEST_TIME' => int 1491068771 There is a lot to take in there so I will pick out some important ones below. If you wish to read about them all then consult the indices section of the documentation. I might add them all below one day. Or someone can edit and add a good explanation of them below? Hint, hint;) For all explanations below, assume the URL is http://www.example.com/index.php HTTP_HOST - The host address. GoalKicker.com – PHP Notes for Professionals 23 This would return www.example.com HTTP_USER_AGENT - Contents of the user agent. This is a string which contains all the information about the client's browser, including operating system. HTTP_COOKIE - All cookies in a concatenated string, with a semi-colon delimiter. SERVER_ADDR - The IP address of the server, of which the current script is running. This would return 93.184.216.34 PHP_SELF - The file name of the currently executed script, relative to document root. This would return /index.php REQUEST_TIME_FLOAT - The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0. REQUEST_TIME - The timestamp of the start of the request. Available since PHP 5.1.0. $_GET An associative array of variables passed to the current script via the URL parameters. $_GET is an array that contains all the URL parameters; these are the whatever is after the ? in the URL. Using http://www.example.com/index.php?myVar=myVal as an example. This information from this URL can be obtained by accessing in this format $_GET["myVar"] and the result of this will be myVal. Using some code for those that don't like reading. // URL = http://www.example.com/index.php?myVar=myVal echo $_GET["myVar"] == "myVal" ? "true" : "false"; // returns "true" The above example makes use of the ternary operator. This shows how you can access the value from the URL using the $_GET superglobal. Now another example! gasp // URL = http://www.example.com/index.php?myVar=myVal&myVar2=myVal2 echo $_GET["myVar"]; // returns "myVal" echo $_GET["myVar2"]; // returns "myVal2" It is possible to send multiple variables through the URL by separating them with an ampersand (&) character. Security risk It is very important not to send any sensitive information via the URL as it will stay in history of the computer and will be visible to anyone that can access that browser. $_POST An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. Very similar to $_GET in that data is sent from one place to another. I'll start by going straight into an example. (I have omitted the action attribute as this will send the information to the page that the form is in). GoalKicker.com – PHP Notes for Professionals 24 Above is a basic form for which data can be sent. In an real environment the value attribute would not be set meaning the form would be blank. This would then send whatever information is entered by the user. echo $_POST["myVar"]); // returns "myVal" Security risk Sending data via POST is also not secure. Using HTTPS will ensure that data is kept more secure. $_FILES An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the POST method uploads section. Let's start with a basic form. Note that I omitted the action attribute (again!). Also, I added enctype="multipart/form-data", this is important to any form that will be dealing with file uploads. // ensure there isn't an error if ($_FILES["myVar"]["error"] == UPLOAD_ERR_OK) { $folderLocation = "myFiles"; // a relative path. (could be "path/to/file" for example) // if the folder doesn't exist then make it if (!file_exists($folderLocation)) mkdir($folderLocation); // move the file into the folder move_uploaded_file($_FILES["myVar"]["tmp_name"], "$folderLocation/" . basename($_FILES["myVar"]["name"])); } This is used to upload one file. Sometimes you may wish to upload more than one file. An attribute exists for that, it's called multiple. There's an attribute for just about anything. I'm sorry Below is an example of a form submitting multiple files. Note the changes made here; there are only a few. The input name has square brackets. This is because it is now an array of files and so we are telling the form GoalKicker.com – PHP Notes for Professionals 25 to make an array of the files selected. Omitting the square brackets will result in the latter most file being set to $_FILES["myVar"]. The multiple="multiple" attribute. This just tells the browser that users can select more than one file. $total = isset($_FILES["myVar"]) ? count($_FILES["myVar"]["name"]) : 0; // count how many files were sent // iterate over each of the files for ($i = 0; $i < $total; $i++) { // there isn't an error if ($_FILES["myVar"]["error"][$i] == UPLOAD_ERR_OK) { $folderLocation = "myFiles"; // a relative path. (could be "path/to/file" for example) // if the folder doesn't exist then make it if (!file_exists($folderLocation)) mkdir($folderLocation); // move the file into the folder move_uploaded_file($_FILES["myVar"]["tmp_name"][$i], "$folderLocation/" . basename($_FILES["myVar"]["name"][$i])); } // else report the error else switch ($_FILES["myVar"]["error"][$i]) { case UPLOAD_ERR_INI_SIZE: echo "Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini."; break; case UPLOAD_ERR_FORM_SIZE: echo "Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form."; break; case UPLOAD_ERR_PARTIAL: echo "Value: 3; The uploaded file was only partially uploaded."; break; case UPLOAD_ERR_NO_FILE: echo "Value: 4; No file was uploaded."; break; case UPLOAD_ERR_NO_TMP_DIR: echo "Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3."; break; case UPLOAD_ERR_CANT_WRITE: echo "Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0."; break; case UPLOAD_ERR_EXTENSION: echo "Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0."; break; default: echo "An unknown error has occurred."; break; } } This is a very simple example and doesn't handle problems such as file extensions that aren't allowed or files named with PHP code (like a PHP equivalent of an SQL injection). See the documentation. The first process is checking if there are any files, and if so, set the total number of them to $total. GoalKicker.com – PHP Notes for Professionals 26 Using the for loop allows an iteration of the $_FILES array and accessing each item one at a time. If that file doesn't encounter a problem then the if statement is true and the code from the single file upload is run. If an problem is encountered the switch block is executed and an error is presented in accordance with the error for that particular upload. $_COOKIE An associative array of variables passed to the current script via HTTP Cookies. Cookies are variables that contain data and are stored on the client's computer. Unlike the aforementioned superglobals, cookies must be created with a function (and not be assigning a value). The convention is below. setcookie("myVar", "myVal", time() + 3600); In this example a name is specified for the cookie (in this example it is "myVar"), a value is given (in this example it is "myVal", but a variable can be passed to assign its value to the cookie), and then an expiration time is given (in this example it is one hour since 3600 seconds is a minute). Despite the convention for creating a cookie being different, it is accessed in the same way as the others. echo $_COOKIE["myVar"]; // returns "myVal" To destroy a cookie, setcookie must be called again, but the expiration time is set to any time in the past. See below. setcookie("myVar", "", time() - 1); var_dump($_COOKIE["myVar"]); // returns null This will unset the cookies and remove it from the clients computer. $_SESSION An associative array containing session variables available to the current script. See the Session functions documentation for more information on how this is used. Sessions are much like cookies except they are server side. To use sessions you must include session_start() at the top of your scripts to allow sessions to be utilised. Setting a session variable is the same as setting any other variable. See example below. $_SESSION["myVar"] = "myVal"; When starting a session a random ID is set as a cookie and called "PHPSESSID" and will contain the session ID for that current session. This can be accessed by calling the session_id() function. It is possible to destroy session variables using the unset function (such that unset($_SESSION["myVar"]) would destroy that variable). The alternative is to call session_destory(). This will destroy the entire session meaning that all session variables will no longer exist. GoalKicker.com – PHP Notes for Professionals 27 $_REQUEST An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. As the PHP documentation states, this is just a collation of $_GET, $_POST, and $_COOKIE all in one variable. Since it is possible for all three of those arrays to have an index with the same name, there is a setting in the php.ini file called request_order which can specify which of the three has precedence. For instance, if it was set to "GPC", then the value of $_COOKIE will be used, as it is read from left to right meaning the $_REQUEST will set its value to $_GET, then $_POST, and then $_COOKIE and since $_COOKIE is last that is the value that is in $_REQUEST. See this question. $_ENV An associative array of variables passed to the current script via the environment method. These variables are imported into PHP's global namespace from the environment under which the PHP parser is running. Many are provided by the shell under which PHP is running and different systems are likely running different kinds of shells, a definitive list is impossible. Please see your shell's documentation for a list of defined environment variables. Other environment variables include the CGI variables, placed there regardless of whether PHP is running as a server module or CGI processor. Anything stored within $_ENV is from the environment from which PHP is running in. $_ENV is only populated if php.ini allows it. See this answer for more information on why $_ENV is not populated. Section 4.2: PHP5 SuperGlobals Below are the PHP5 SuperGlobals $GLOBALS $_REQUEST $_GET $_POST $_FILES $_SERVER $_ENV $_COOKIE $_SESSION $GLOBALS: This SuperGlobal Variable is used for accessing globals variables. $_REQUEST: This SuperGlobal Variable is used to collect data submitted by a HTML Form. $_GET: This SuperGlobal Variable is used to collect data submitted by HTML Form with get method. $_POST: This SuperGlobal Variable is used to collect data submitted by HTML Form with post method. $_FILES: This SuperGlobal Variable holds the information of uploaded files via HTTP Post method. "; print_r($_FILES['picture']); echo ""; } /** This will print details of the File with name picture uploaded via a form with method='post and with enctype='multipart/form-data' Details includes Name of file, Type of File, temporary file location, error code(if any error occurred while uploading the file) and size of file in Bytes. Eg. Array ( [picture] => Array ( [0] => Array ( [name] => 400.png [type] => image/png [tmp_name] => /tmp/php5Wx0aJ [error] => 0 [size] => 15726 ) ) ) GoalKicker.com – PHP Notes for Professionals 29 */ ?> $_SERVER: This SuperGlobal Variable holds information about Scripts, HTTP Headers and Server Paths. "; print_r($_SERVER); echo ""; /** Will print the following details on my local XAMPP Array ( [MIBDIRS] => C:/xampp/php/extras/mibs [MYSQL_HOME] => \xampp\mysql\bin [OPENSSL_CONF] => C:/xampp/apache/bin/openssl.cnf [PHP_PEAR_SYSCONF_DIR] => \xampp\php [PHPRC] => \xampp\php [TMP] => \xampp\tmp [HTTP_HOST] => localhost [HTTP_CONNECTION] => keep-alive [HTTP_CACHE_CONTROL] => max-age=0 [HTTP_UPGRADE_INSECURE_REQUESTS] => 1 [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*;q=0.8 [HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch [HTTP_ACCEPT_LANGUAGE] => en-US,en;q=0.8 [PATH] => C:\xampp\php;C:\ProgramData\ComposerSetup\bin; [SystemRoot] => C:\Windows [COMSPEC] => C:\Windows\system32\cmd.exe [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC [WINDIR] => C:\Windows [SERVER_SIGNATURE] => Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12 Server at localhost Port 80 [SERVER_SOFTWARE] => Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12 [SERVER_NAME] => localhost [SERVER_ADDR] => ::1 [SERVER_PORT] => 80 [REMOTE_ADDR] => ::1 [DOCUMENT_ROOT] => C:/xampp/htdocs [REQUEST_SCHEME] => http [CONTEXT_PREFIX] => [CONTEXT_DOCUMENT_ROOT] => C:/xampp/htdocs [SERVER_ADMIN] => postmaster@localhost [SCRIPT_FILENAME] => C:/xampp/htdocs/abcd.php [REMOTE_PORT] => 63822 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /abcd.php [SCRIPT_NAME] => /abcd.php [PHP_SELF] => /abcd.php [REQUEST_TIME_FLOAT] => 1469374173.88 [REQUEST_TIME] => 1469374173 ) */ ?> $_ENV: This SuperGlobal Variable Shell Environment Variable details under which the PHP is running. GoalKicker.com – PHP Notes for Professionals 30 $_COOKIE: This SuperGlobal Variable is used to retrieve Cookie value with given Key. "; echo "Value is: " . $_COOKIE[$cookie_name]; } /** Output Cookie 'data' is set! Value is: Foo Bar */ ?> $_SESSION: This SuperGlobal Variable is used to Set and Retrieve Session Value which is stored on Server. GoalKicker.com – PHP Notes for Professionals 31 Chapter 5: Outputting the Value of a Variable To build a dynamic and interactive PHP program, it is useful to output variables and their values. The PHP language allows for multiple methods of value output. This topic covers the standard methods of printing a value in PHP and where these methods can be used. Section 5.1: echo and print echo and print are language constructs, not functions. This means that they don't require parentheses around the argument like a function does (although one can always add parentheses around almost any PHP expression and thus echo("test") won't do any harm either). They output the string representation of a variable, constant, or expression. They can't be used to print arrays or objects. Assign the string Joel to the variable $name $name = "Joel"; Output the value of $name using echo & print echo $name; #> Joel print $name; #> Joel Parentheses are not required, but can be used echo($name); #> Joel print($name); #> Joel Using multiple parameters (only echo) echo $name, "Smith"; #> JoelSmith echo($name, " ", "Smith"); #> Joel Smith print, unlike echo, is an expression (it returns 1), and thus can be used in more places: print("hey") && print(" ") && print("you"); #> you11 The above is equivalent to: print ("hey" && (print (" " && print "you"))); #> you11 Shorthand notation for echo When outside of PHP tags, a shorthand notation for echo is available by default, using = to begin output and ?> to end it. For example:=$variable?>
= "This is also PHP" ?>
Note that there is no terminating ;. This works because the closing PHP tag acts as the terminator for the single GoalKicker.com – PHP Notes for Professionals 32 statement. So, it is conventional to omit the semicolon in this shorthand notation. Priority of print Although the print is language construction it has priority like operator. It places between = += -= *= **= /= .= %= &= and and operators and has left association. Example: echo '1' . print '2' + 3; //output 511 Same example with brackets: echo '1' . print ('2' + 3); //output 511 Differences between echo and print In short, there are two main differences: print only takes one parameter, while echo can have multiple parameters. print returns a value, so can be used as an expression. Section 5.2: Outputting a structured view of arrays and objects print_r() - Outputting Arrays and Objects for debugging print_r will output a human readable format of an array or object. You may have a variable that is an array or object. Trying to output it with an echo will throw the error: Notice: Array to string conversion. You can instead use the print_r function to dump a human readable format of this variable. You can pass true as the second parameter to return the content as a string. $myobject = new stdClass(); $myobject->myvalue = 'Hello World'; $myarray = [ "Hello", "World" ]; $mystring = "Hello World"; $myint = 42; // Using print_r we can view the data the array holds. print_r($myobject); print_r($myarray); print_r($mystring); print_r($myint); This outputs the following: stdClass Object ( [myvalue] => Hello World ) Array ( [0] => Hello [1] => World ) GoalKicker.com – PHP Notes for Professionals 33 Hello World 42 Further, the output from print_r can be captured as a string, rather than simply echoed. For instance, the following code will dump the formatted version of $myarray into a new variable: $formatted_array = print_r($myarray, true); Note that if you are viewing the output of PHP in a browser, and it is interpreted as HTML, then the line breaks will not be shown and the output will be much less legible unless you do something like echo '' . print_r($myarray, true) . ''; Opening the source code of a page will also format your variable in the same way without the use of the
tag. Alternatively you can tell the browser that what you're outputting is plain text, and not HTML: header('Content-Type: text/plain; charset=utf-8'); print_r($myarray); var_dump() - Output human-readable debugging information about content of the argument(s) including its type and value The output is more detailed as compared to print_r because it also outputs the type of the variable along with its value and other information like object IDs, array sizes, string lengths, reference markers, etc. You can use var_dump to output a more detailed version for debugging. var_dump($myobject, $myarray, $mystring, $myint); Output is more detailed: object(stdClass)#12 (1) { ["myvalue"]=> string(11) "Hello World" } array(2) { [0]=> string(5) "Hello" [1]=> string(5) "World" } string(11) "Hello World" int(42) Note: If you are using xDebug in your development environment, the output of var_dump is limited / truncated by default. See the official documentation for more info about the options to change this. var_export() - Output valid PHP Code var_export() dumps a PHP parseable representation of the item. GoalKicker.com – PHP Notes for Professionals 34 You can pass true as the second parameter to return the contents into a variable. var_export($myarray); var_export($mystring); var_export($myint); Output is valid PHP code: array ( 0 => 'Hello', 1 => 'World', ) 'Hello World' 42 To put the content into a variable, you can do this: $array_export = var_export($myarray, true); $string_export = var_export($mystring, true); $int_export = var_export($myint, 1); // any `Truthy` value After that, you can output it like this: printf('$myarray = %s; %s', $array_export, PHP_EOL); printf('$mystring = %s; %s', $string_export, PHP_EOL); printf('$myint = %s; %s', $int_export, PHP_EOL); This will produce the following output: $myarray = array ( 0 => 'Hello', 1 => 'World', ); $mystring = 'Hello World'; $myint = 42; Section 5.3: String concatenation with echo You can use concatenation to join strings "end to end" while outputting them (with echo or print for example). You can concatenate variables using a . (period/dot). // String variable $name = 'Joel'; // Concatenate multiple strings (3 in this example) into one and echo it once done. // 1. ↓ 2. ↓ 3. ↓ - Three Individual string items echo 'Hello ' . $name . ', Nice to see you.
'; // ↑ ↑ - Concatenation Operators #> "Hello Joel, Nice to see you.
" Similar to concatenation, echo (when used without parentheses) can be used to combine strings and variables together (along with other arbitrary expressions) using a comma (,). $itemCount = 1; GoalKicker.com – PHP Notes for Professionals 35 echo 'You have ordered ', $itemCount, ' item', $itemCount === 1 ? '' : 's'; // ↑ ↑ ↑ - Note the commas #> "You have ordered 1 item" String concatenation vs passing multiple arguments to echo Passing multiple arguments to the echo command is more advantageous than string concatenation in some circumstances. The arguments are written to the output in the same order as they are passed in. echo "The total is: ", $x + $y; The problem with the concatenation is that the period . takes precedence in the expression. If concatenated, the above expression needs extra parentheses for the correct behavior. The precedence of the period affects ternary operators too. echo "The total is: " . ($x + $y); Section 5.4: printf vs sprintf printf will output a formatted string using placeholders sprintf will return the formatted string $name = 'Jeff'; // The `%s` tells PHP to expect a string // ↓ `%s` is replaced by ↓ printf("Hello %s, How's it going?", $name); #> Hello Jeff, How's it going? // Instead of outputting it directly, place it into a variable ($greeting) $greeting = sprintf("Hello %s, How's it going?", $name); echo $greeting; #> Hello Jeff, How's it going? It is also possible to format a number with these 2 functions. This can be used to format a decimal value used to represent money so that it always has 2 decimal digits. $money = 25.2; printf('%01.2f', $money); #> 25.20 The two functions vprintf and vsprintf operate as printf and sprintf, but accept a format string and an array of values, instead of individual variables. Section 5.5: Outputting large integers On 32-bits systems, integers larger than PHP_INT_MAX are automatically converted to float. Outputting these as integer values (i.e. non-scientific notation) can be done with printf, using the float representation, as illustrated below: foreach ([1, 2, 3, 4, 5, 6, 9, 12] as $p) { $i = pow(1024, $p); printf("pow(1024, %d) > (%7s) %20s %38.0F", $p, gettype($i), $i, $i); GoalKicker.com – PHP Notes for Professionals 36 echo " ", $i, "\n"; } // outputs: pow(1024, 1) integer 1024 1024 1024 pow(1024, 2) integer 1048576 1048576 1048576 pow(1024, 3) integer 1073741824 1073741824 1073741824 pow(1024, 4) double 1099511627776 1099511627776 1099511627776 pow(1024, 5) double 1.1258999068426E+15 1125899906842624 1.1258999068426E+15 pow(1024, 6) double 1.1529215046068E+18 1152921504606846976 1.1529215046068E+18 pow(1024, 9) double 1.2379400392854E+27 1237940039285380274899124224 1.2379400392854E+27 pow(1024, 12) double 1.3292279957849E+36 1329227995784915872903807060280344576 1.3292279957849E+36 Note: watch out for float precision, which is not infinite! While this looks nice, in this contrived example the numbers can all be represented as a binary number since they are all powers of 1024 (and thus 2). See for example: $n = pow(10, 27); printf("%s %.0F\n", $n, $n); // 1.0E+27 1000000000000000013287555072 Section 5.6: Output a Multidimensional Array with index and value and print into the table Array ( [0] => Array ( [id] => 13 [category_id] => 7 [name] => Leaving Of Liverpool [description] => Leaving Of Liverpool [price] => 1.00 [virtual] => 1 [active] => 1 [sort_order] => 13 [created] => 2007-06-24 14:08:03 [modified] => 2007-06-24 14:08:03 [image] => NONE ) [1] => Array ( [id] => 16 [category_id] => 7 [name] => Yellow Submarine [description] => Yellow Submarine [price] => 1.00 [virtual] => 1 [active] => 1 [sort_order] => 16 [created] => 2007-06-24 14:10:02 [modified] => 2007-06-24 14:10:02 GoalKicker.com – PHP Notes for Professionals 37 [image] => NONE ) ) Output Multidimensional Array with index and value in table
$k | "; // Get index. echo "$v | "; // Get value. echo "
$output"; Note that the execute operator and shell_exec() will give the same result. Section 10.4: Incrementing (++) and Decrementing Operators (--) Variables can be incremented or decremented by 1 with ++ or --, respectively. They can either precede or succeed variables and slightly vary semantically, as shown below. GoalKicker.com – PHP Notes for Professionals 55 $i = 1; echo $i; // Prints 1 // Pre-increment operator increments $i by one, then returns $i echo ++$i; // Prints 2 // Pre-decrement operator decrements $i by one, then returns $i echo --$i; // Prints 1 // Post-increment operator returns $i, then increments $i by one echo $i++; // Prints 1 (but $i value is now 2) // Post-decrement operator returns $i, then decrements $i by one echo $i--; // Prints 2 (but $i value is now 1) More information about incrementing and decrementing operators can be found in the official documentation. Section 10.5: Ternary Operator (?:) The ternary operator can be thought of as an inline if statement. It consists of three parts. The operator, and two outcomes. The syntax is as follows: $value =