PHP Basic
The echo() statement operates similarly to print(), except for two differences. First, it cannot be used as part of a complex expression because it returns void, whereas print() returns a Boolean. Second, echo() is capable of outputting multiple strings. echo() function is a tad faster, because it returns nothing, whereas print() returns a Boolean value informing the caller whether or not the statement was successfully output.
$sentence = "This is a sentence";
echo (int) $sentence; // returns 0
$model = "Toyota";
$new_obj = (object) $model;
The value can then be referenced as follows:
print $new_obj->scalar; // returns "Toyota"
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print "<br>";
}
keep_track();
keep_track();
keep_track();
The outputs:
1
2
3
If return() is called from the global scope, script execution ends immediately.
There are two important differences between require() and include(). First, the file will be included in the script in which the require() construct appears, regardless of where require() is located. For instance, if require() were placed within an if statement that evaluated to false, the file would be included anyway!
PHP supports the practice of nesting functions, you could still call convert_pound() outside of salestax()
function salestax($price,$tax) {
function convert_pound($dollars, $conversion=1.6) {
return $dollars * $conversion;
}
$total = $price + ($price * $tax);
echo "Total cost in dollars: $total. Cost in British pounds: "
.convert_pound($total);
}
Arrays
$stateCapitals = print_r($states, TRUE);
$die = range(0,6);
// Same as specifying $die = array(0,1,2,3,4,5,6)
Object-oriented PHP
__set and __get methods are invoked if you attempt to reference a member variable that does not exist within the class definition.
class Staff
{
var $name;
function __set($propName, $propValue)
{
$this->$propName = $propValue;
}
}
the interface is to define a set of guidelines
Strings
<?php
$entities = get_html_translation_table(HTML_ENTITIES);
$translate = array_flip($entities);
$string = "La pasta é il piatto piú amato in Italia";
echo strtr($string, $translate);
?>
This returns the following:
La pasta é il piatto piú amato in italia
Files
array fstat (resource filepointer), array stat (string filename). the only difference is that stat() requires an actual file name and path rather than a resource handle.
$file = "/usr/local/apache2/htdocs/book/chapter10/stat.php";
$fh = fopen($file, "r");
$fileinfo = fstat($fh);
$fileinfo2 = stat($file);
isexecutable (string filename) is not available on the Windows platform.
socsecurity.txt:
123-45-6789
234-56-7890
345-67-8901
<?php
$fh = fopen("socsecurity.txt", "r");
/* Parse each SSN in accordance with
integer-integer-integer format. */
while ($user = fscanf($fh, "%d-%d-%d")) {
list ($part1,$part2,$part3) = $user;
...
}
fclose($fh);
?>
PHP and LDAP
ldap_modify(), for making changes on the attribute level, and ldap_rename(), for making changes on the object level.
Session handlers
session_unset() will not completely remove the session from the storage mechanism.
session_destroy() will not destroy any cookies on the user’s browser. session_close() does not destroy the session.
Each session variable reference is separated by a semicolon, and consists of three components: the name, length, and value. The general syntax follows:
name|s:length:"value";
PHP handles the session encoding and decoding autonomously. However, sometimes you might wish to execute these tasks manually. Two functions are available for doing so: session_encode() and session_decode(), respectively
Web services
The SOAP and SimpleXML extensions are also introduced, both of which are new to PHP 5
Secure PHP programming
When safe mode is enabled, PHP always verifies that the executing script’s owner matches the owner of the file that the script is attempting to open.
Once safe mode is enabled, if using the MySQL database server, the username used to connect to a MySQL server must be the same as the username of the owner of the file calling mysql_connect().
Note that specifying a particular path without a tailing slash will cause all directories falling under that path to also be ignored by the safe mode setting. For example, setting this directive to /home/configuration means that /home/configuration/templates/ and /home/configuration/passwords/ are also exempt from safe mode restrictions. Therefore, if you’d like to exclude just a single directory or set of directories from the safe mode settings, be sure to conclude each with the trailing slash.
The escapeshellcmd() function operates under the same premise as escapeshellarg(), but it sanitizes potentially dangerous input program names rather than program arguments. The escapeshellcmd() function operates by escaping any shell metacharacters found in command. These metacharacters include: # & ; ` , | * ? ~ < > ^ ( ) [ ] { } $ \\.
PHP Basic
Outputting a newline character before all of the headers have been written to the output can cause some rather unpleasant (and unintended) consequences. To mitigate this problem, the first newline directly after a closing tag (?> only) is stripped by the parser. An easy way to prevent spurious output from an include file is to omit the closing tag at the end, which the parser considers this perfectly legal.
Both types of single line comments, // and #, can be ended using a newline (\r, \n or \r\n) or by ending the current PHP block using the PHP closing tag—?>. Because the closing tag ?> will end a comment, code like // Do not show this ?>
or this will output
or this, which is not the intended behaviour.
PHP' string is ordered collections of binary data, this could be text, but it could also be the contents of an image file, a spreadsheet, or even a music recording.
$name = ’123’;
/* 123 is your variable name, this would normally be invalid. */
$$name = ’456’;
// Again, you assign a value
echo ${’123’};
// Finally, using curly braces you can output ’456’
$x = 1;
echo $x << 32;//The second line of this example actually outputs zero
echo $x * pow (2, 32);//return the correct value of 4,294,967,296—which, incidentally, will now be a float because such a number can-not be represented using a signed 32-bit integer
Error reporting can also be changed dynamically from within a script by calling the error_reporting() function.
As of PHP 5, set_error_handler() supports a second parameter that allows you to specify the types of errors that a particular handler is responsible for trapping. This parameter takes the same constant values as the error_reporting() function.
Functions can also be declared so that they return by reference; but cannot return an expression by reference, or use an empty return statement to force a NULL return value.
Functions
function f ($optional = "null", $required)
{
}
You will never be able to omit the first parameter ($optional) if you want to specify the second, and you can’t omit the second because PHP will emit a warning.
Unlike PHP 4, PHP 5 allows default values to be specified for parameters even when they are declared as by-reference:
function cmdExists($cmd, &$output = null)
Arrays
only var_dump() is capable of outputting the value of more than one variable at the same time.
$a = array (1, 2, 3);
$b = array (1 => 2, 2 => 3, 0 => 1);
$c = array (’a’ => 1, ’b’ => 2, ’c’ => 3);
var_dump ($a == $b); // True
var_dump ($a === $b); // False
var_dump ($a == $c); // False
var_dump ($a === $c); // False
$c=1;
echo count ($c); // Outputs 1
array_flip — Exchanges all keys with their associated values in an array
$a = array (’a’, ’b’, ’c’);
var_dump (array_flip ($a));
This outputs:
array(3) {
["a"]=>
int(0)
["b"]=>
int(1)
["c"]=>
int(2)
}
reset() to rewind the internal array pointer.
$a = array (’zero’,’one’,’two’);
foreach ($a as &$v) {
}
foreach ($a as $v) {
}
print_r ($a);
outputs:
Array
(
[0] => zero
[1] => one
[2] => one
)
$type = array(’internal’, ’custom’);
$output_formats[] = array(’rss’, ’html’, ’xml’);
$output_formats[] = array(’csv’, ’json’);
$map = array_combine($type, $output_formats);
var_dump($map);
output:
array(2) {
["internal"]=>
&array(3) {
[0]=>
string(3) "RSS"
[1]=>
string(4) "HTML"
[2]=>
string(3) "XML"
}
["custom"]=>
&array(2) {
[0]=>
string(3) "CSV"
[1]=>
string(4) "JSON"
}
}
shuffle() function randomizes the order of the elements of the array, the key-value association is lost.
array_diff(), array_diff_assoc(), array_diff_key(),
Strings And Patterns
$haystack = ’123456’;
$needle = ’34’;
echo strstr ($haystack, $needle); // outputs 3456
strstr() is lower than strpos();
strspn() strcspn()
str_replace("World", "Reader", "Hello World");
$user = "davey@php.net";
$name = substr_replace($user, "", strpos($user, ’@’);
echo "Hello " . $name;
$data = ’123 456 789’;
$format = ’%d %d %d’;
var_dump (sscanf ($data, $format));
outputs:
array(3) {
[0]=>
int(123)
[1]=>
int(456)
[2]=>
int(789)
}
Web Programming
post_max_size, max_input_time and upload_max_filesize.
You should not think of cookies as a secure storage mechanism. Although you can transmit a cookie so that it is exchanged only when an HTTP transaction takes place securely (e.g.: under HTTPS),
There is no way to “delete” a cookie, You can, however, call setcookie() with an empty string and a negative timestamp, which will effectively empty the cookie and in most cases the browser will remove it.
Object Oriented Programming in PHP
The final visibility level only applies to methods and classes.
PHP is very strict about the use of static properties; calling
static properties using object notation (i.e. $obj->property) will result in both a “strict standards” message and a notice.
This is not the case with static methods, however
calling a non-static method statically will also emit a “strict standards” message.
You
must declare a class as abstract so long as it has (or inherits without providing a body) at least one abstract method.
Database Programming
The mysqli extension also provides the simpler mysqli::query() and mysqli_query() methods, which will immediately return a result set. With mysqli::real_query() or mysqli_real_query() the result set is not returned until mysqli::store_result(), mysql_store_result(), mysqli::use_result(), or mysql_use_result() are called.
Elements of Object-oriented Design
interface ArrayAccess {
function offsetSet($offset, $value);
function offsetGet($offset);
function offsetUnset($offset);
function offsetExists($offset);
}
XML and Web Services
If a file with the same path already exists, a call to asXML() will overwrite it without warning (provided that the user account under which PHP is running has the proper permissions).
While SimpleXML provides the functionality for adding children and attributes, it does not provide the means to remove them. It is possible to remove child elements, though, using the following method.
$library->book[0] = NULL;
$dom = new DomDocument();
$dom->load("my.xml");
$xpath = new DomXPath($dom);
$xpath->registerNamespace("lib", "http://example.org/library");
$result = $xpath->query("//lib:book");
$result->item(1)->parentNode->appendChild($result->item(0));
DomNode::removeAttribute(), DomNode::removeChild() and DomCharacterData::deleteData().
$sxml = simplexml_load_file(’library.xml’);
$node = dom_import_simplexml($sxml);
$dom = new DomDocument();
$dom->importNode($node, true);
Security
user form input, the query string, or even an RSS feed, the $_SERVER array, it cannot be trusted. It is tainted data. The one exception to this rule is the $_SESSION superglobal array, which is persisted on the server and never over the Internet.
server-side filtering is important for security, while client-side validation is important for usability.
escapeshellcmd() and escapeshellarg()
Streams and Network Programming
The fread() function is used to read arbitrary data from a file; unlike fgets(), it does not concern itself with newline characters—it only stops reading data when either the number of bytes specified in its argument have been transferred, or the pointer reaches the end of the file.
To find the current position of the pointer, you should use ftell().
getcwd(),
stream_context_create(), stream_filter_prepend(), stream_filter_append()
$socket = stream_socket_server("tcp://0.0.0.0:1037");
while ($conn = stream_socket_accept($socket)) {
stream_filter_append($conn, ’string.toupper’);
stream_filter_append($conn, ’zlib.deflate’);
fwrite($conn, "Hello World\n");
fclose($conn);
}
fclose($socket);
Differences Between PHP 4 and 5
Magic Methods
A multitude of new “magic” methods has been introduced in PHP 5:
• __get() and __set() are called when accessing or assigning an undefined ob-
ject property, while __call() is executed when calling a non-existent method
of a class.
Differences Between PHP 4 and 5 ” 255
• __isset() is called when passing an undefined property to the isset() con-
struct.
• __unset() is called when passing an undefined property to unset().
• __toString() is called when trying to directly echo or print() an object.
• __set_state() is inserted dynamically by var_export() to allow for re-
initialization on execution of var_export()’s output.
Selected New Extensions
• SimpleXML allows easy access to XML data using object and array notation.
• PHP 5 also introduces a DOMXML, DOMXSL and Sablotron replacement in
the form of the libxml2-based DOM and XSL extensions.
• The PHP Data Objects (PDO) extension provides a unified database access ex-
tension that allows access to many different types of database systems by us-
ing a common interface. PDO is not an abstraction layer—except for prepared
queries, it does nothing to abstract the actual database code (SQL), itself.
• The hash extension is a new replacement for the GPLed libmhash; it was added
to the PHP core starting with version 5.1.2. It can produce hashes using many
algorithms, including the familiar MD5 and SHA1, as well as some more secure
(albeit slower) algorithms, such as snefru.
• The Standard PHP Library (SPL) provides numerous interfaces that enhance
the way classes interact with the PHP language, including the new Iterator
interfaces.
• The new Reflection extension allows for runtime introspection of executing
PHP code.
Error Management
• Classes now support exceptions; the new set_exception_handler() function
allows you to define a script-wide exception handler.
• The E_STRICT error reporting level has been added to the language to emit no-
tices when legacy or deprecated code is encountered.