Web Features – PHP Certification Exam Series [10]


PHP Web - PHP Certification Exam

Introduction: This is the last part of my study notes for the Zend PHP Certification Exam. You can read more about my PHP Certification exam journey here.

Zend PHP Certification Exam: Web Basics

  • When an HTTP request is made to the PHP server, the intended PHP script will run, producing a set of response headers (type of contents, encoding, data needed to maintain stateful exchange (e.g. PHPSESSID) between the two) and the content HTML codes
  • The headers are in key:value pairs delimited by a newline character, the header is separated from the contents by an extra newline

EGPCS

  • Environment ($_ENV) – These variables are imported into PHP’s global namespace from the environment under which the PHP parser is running
  • Get
  • Post
  • Cookie
  • Server and Built-in variables ($_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server, e.g. the URL is contained in $_SERVER[‘script_name’].)
  • the normal order specified in php.ini by variables_order is EGPCS, $_REQUEST[‘hello’] is assigned $_GET[‘hello’], $_POST[‘hello’] and then $_COOKIE[‘hello’] in turns if these exist (will not be parsed into super global if not included in variables_order)

Forms

  • POST vs GET: post is NOT more secure
  • GET: used to retrieve information, more limited in content length as the request is sent through query string (url encoded);
  • GET: http://example.com/index.php?order[by]=column&order[dir]=asc to create an array for the the $_GET[‘order’]
  • POST: used to modify data, can also upload files
  • POST: in the form … <input type=”checkbox” name=”languages[ ]” value=”PHP” /> … , when checked and posted, the result is $_POST[‘languages’][ ]=’PHP’
  • The name foo.x in the form resolve to $_GET[‘foo_x‘]
  • Use htmlspecialchars($_GET[‘foo_x’]) to encode special characters for security

File uploads

<form enctype="multipart/form-data" action="index.php" method="post">
   <input type="hidden" name="MAX_FILE_SIZE" value="50000" /> // must precede input
   <input name="filedata[]" type="file" />
   <input name="filedata[]" type="file" />
   <select multiple> // for multiple select
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
   </select>
   <input type="submit" value="Send file" />
</form>
  • MAX_FILE_SIZE is NEVER used in practice
  • controlled by post_max_size, upload_max_filesize and max_input_time in php.ini (post_max_size must be larger than upload_max_filesize to be effective)
  • max_file_uploads dictate the maximum number of file to be uploaded per request
  • Once uploaded the file is stored in a temporary location in the server with the information populated in the $_FILES superglobal, always check the ‘error’ is UPLOAD_ERR_OK, ‘size’ > 0 and ‘tmp_name’ not empty for legit uploads.
  • $_FILES[‘example’][‘name’] – The original name of the file; $_FILES[‘example’][‘name’][0] – for multiple file uploads
  • $_FILES[‘example’][‘type’] – The MIME type of the file provided by the browser
  • $_FILES[‘example’][‘size’] – The size (in bytes) of the file
  • $_FILES[‘example’][‘tmp_name‘] – The name of the file’s temporary location
  • $_FILES[‘example’][‘error’] – The error code associated with this file. A value of UPLOAD_ERR_OK indicates a successful transfer, while any other error indicates that something went wrong (for example, the file was bigger than the maximum allowed size)
  • is_uploaded_file() to check file  is uploaded successfully
  • move_uploaded_file($filename, $destination) to move file to the right location (will also check is_uploaded_file() first), returns true on success, at least a 6-0-0 privilege on the destination directory is required

HTTP Headers

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
  • header( ) must be called before any other output, including whitespaces, otherwise the header will not be interpreted or an error will be thrown
  • may use output buffering to avoid the error: ob_start() … $a=ob_get_contents() … ob_end_flush()/ob_end_clean();
  • Redirection header(“Location: http://phparch.com“);exit; // exit is added in case the browser doesn’t observe the redirect request, for SEO, if to be redirected permanently use: header(“HTTP/1.1 301 Moved Permanently”); header(“Location: X”); exit; otherwise PHP will issue a 302 Temporary status.
  • Caching header(“Cache-Control: no-cache, must-revalidate“); header(“Expires: Thu, 31 May 1984 04:35:00 GMT”); // not to cache the contents
  • Caching $date = gmdate(“D, j M Y H:i:s, time()+2592000); header(“Expires: “.$date. “UTC“); header(“Cache-Control: Public“); header(“Pragma: Public”); // cache for 1 month (2592000s)
  • Compression either use: ob_start(“ob_gzhandler“) … or in php.ini set zlib.output_compression = on, zlib.output_compression_level = 9 (the highest compression level, most CPU intensive)
  • to check whether header is already sent in the script, use headers_sent($file,$line); // returns true if sent, false if not sent, $file is the script name when $line is the line number where the header is sent
  • Cookie is also sent in the header
  • headers_list();// returns a list of response headers sent (or ready to send)
  • headers_remove($name);// remove a previously registered header, if $name is not set, removes all
  • http_response_code();// 2XX : success; 4XX, 5XX : error

Cookies

  • Client side data store, allow your applications to store a small amount of textual data (typically, 4-6kB) on a Web client
  • Cookie values must be scalar, however, cookies can be set into an array of values, e.g. name[0]=’a’; name[1]=’b’; when accessing $_COOKIE[‘name’], the array of values will be returned
  • Cookies are only available in the next page load
  • If time is not set, the cookie becomes temporary cookie and will be destroyed after the browser session (temporary cookies). This method is more secure as no other scripts will be able to view the cookies.
  • setcookie($name,$value,$time,$path,$domain,$secure,$httponly) – returns TRUE if succeed; $time usually time() + time_to_keep in seconds, if not set, will expire after the browsing session; $path: the relative path the cookies are relevant; $domain: specifies the domain the cookies are relevant, e.g. www.example.com, mail.example.com; $secure: if true, only send when using HTTPS connection; $httponly: if true, only accessible through http but not by scripts like javascript
  • setrawcookie($name,$value,$time,$path,$domain,$secure,$httponly) – NOT urlencod() automatically
  • setcookie($name,””,time()-3600) – delete the cookie (may also use FALSE in the place of “”)
  • $_COOKIE[]// access the cookie value

Sessions

  • HTTP is a stateless protocol (i.e. the server doesn’t know which request comes from who)
  • Sessions by default use a cookie that contains a Session ID (PHPSESSID), may need to be changed with session_name(‘newName’);
  • The default timeout of a PHP session is 24 minutes (1440 seconds) after which the session will be expired, set by session.gc_maxlifetime
  • sessoin_start() must be called before any output in the script
  • PHP handles sessions transparently using cookies or URL rewriting if session.use_trans_sid=on in php.ini (off by default in PHP 5)
  • session_start(); session_regenerate_id(); or session.auto_start=1 in php.ini
  • use session_regenerate_id() after session_start() to prevent session fixation attack
  • session.use_only_cookies=1 for data protection, however, if cookie is not enabled in the client side, the session will not work
  • use $_SESSION[] to retrieve the session values
  • use session_name() to use a different name for the session cookie (instead of PHPSESSID)
  • session_cache_expire() returns the current setting of session.cache_expire (time for the page to retrieve the session cookie again, default: 180min), if an $arg is set, the cache_expire will be set to the new $arg, NOT the session length, which is default to the whole browsing session before the browser is closed
  • unset($_SESSION[‘name’]) to unset the session variable
  • session_destroy() destroys all of the data associated with the current session, but doesn’t unset the session cookie
  • session_id() return the sid of the current section or to replace the session_id($replace);
  • session_set_save_handler ( callback $open , callback $close , callback $read , callback $write , callback $destroy , callback $gc ) sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database
  • session_set_cookie_params() set information about the session cookie, including the duration,  need to call for every request and before session_start() is called (or can be set in php.ini), e.g. session_set_cookie_params($time,$path,’.example.com‘,$http_only); // declare *.example.com as within the session
  • session_get_cookie_params() get the current cookie parameters for the session in an array
  • session_register();session_unregister(); e.g. $test=’here’; session_register(‘test’); better user $_SESSION[‘test’]=’here’; depreciated in PHP 5.3
  • session_is_registered($name) check whether a global variable is registered in the session, depreciated in PHP 5.3
  • Use session_register() to store objects as data for use in a subsequent page. However, the session_register() is removed since PHP 5.4.0.

HTTP authentication with PHP

  • specific hooks only available when running the apache module
  • ask the user to enter username and password through HTTP authentication
  • PHP_AUTH variables will not be set if external authentication is enabled for that particular page and safe mode is enabled, use $_SERVER[‘REMOTE_USER’] instead
  • username is appended with colon “:”, both username and password are base64 encoded before transmission
if (!isset($_SERVER['PHP_AUTH_USER'])) {
   header('WWW-Authenticate: Basic realm="Secret Area"');
   header('HTTP/1.1 401 Unauthorized'); // this will show the log in box
   echo 'Text to send if user hits Cancel button'; // this will show if the user click cancel in the box
   exit;
} else {
   echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
   echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
  • PHP_AUTH_USER : user name
  • PHP_AUTH_PW : password
  • AUTH_TYPE : authentication type

 

 

You can read more about my PHP Certification exam journey here.

Support website running for FREE, thanks!

If you find this post helpful and if you are thinking of buying from Amazon, please support the running cost of this website at no extra cost to you by searching and buying through the search box below. Thank you very much for your help!

Edward Chung

Edward Chung aspires to become a full-stack web developer and project manager. In the quest to become a more competent professional, Edward studied for and passed the PMP Certification, ITIL v3 Foundation Certification, PMI-ACP Certification and Zend PHP Certification. Edward shares his certification experience and resources here in the hope of helping others who are pursuing these certification exams to achieve exam success.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *