Chapter 13 - Review

Output
Show all Hide all
1Toggle answer visibilityWhat are some of the inappropriate strings and characters that could be indicators of potential spam attempts?

A spam attempt would mean someone is trying to manipulate the way a contact form is submitted by including additional header information that is appended to the mail() function. Tip offs include: content-type: , mime-version: , multipart-mixed: , content-transfer-encoding: , bcc: , cc:, to: , or new line characters like: \r, \n, %0a, %0d .

2Toggle answer visibilityWhat does the stripos() function do? What is its syntax?

The stripos() function returns the index of the first instance of a substring found within a given string. It is case insensitive. If no substring is found it returns false. Use the === operator for testing the return value of this function as string position 0 will evaluate to false if use regular == comparison operator.

		$string = "I am a string.";
		$needle = "i";
		$offset = 0; //optional
		$position = stripos($string, $needle, $offset); // $position = 0;
		

3Toggle answer visibility What does the str_replace() function do? What is its syntax?

The str_replace() function searches a string or array for a substring and replaces all occurances with another defined value(can also be a string or array) Count can also be set to limit the number of replacements that occurs. Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements. This is case sensitive, use str_ireplace() for case-insensitive string replacement.

		$string = "I am a string.";
		$search = "I am";
		$replace = "You are";
		$count = 1;
		$newstring = str_replace($search, $replace, $string, $count); // $newstring = "You are a string"
		

4Toggle answer visibilityWhat does the array_map() function do? What is its syntax?

The array_map() function returns an array containing all the elements of array after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map() (Contrast the array_walk() function).

		  $array = array("a","b","c","d","e");
		  function capitalize($string) {
		  	return ucfirst($string);
		  }
		  $newArray = array_map("capitalize", $array); //$newArray = array("A","B","C","D","E")
		  

5Toggle answer visibilityWhat is typecasting? How do you typecast a variable in PHP?

Typecasting is a way to force a variable to convert to the indicated type. It is a way to force validation of data before processing. Since PHP is a loosely typed language, a variable's type is determined by the context in which the variable is used. Simply prepend the cast in parenthesis to the variable name. Allowed typecasts include

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)
		$foo = "1";
		echo gettype($foo); // outputs "string" 
		$too = (int)$foo;
		echo gettype($foo); // outputs "string"
		echo gettype($too); // outputs "integer"
		
To overwrite the type of the variable without reassignment use settype($var, $type). Typecasting is particularly important when using numbers in mysql statements!

6Toggle answer visibilityWhat function is used to move an uploaded file to its final destination on the server?

Once a file is uploaded using php, you can use the function

		move_uploaded_file($tmp_name, "$uploads_dir/$name");
		
to move the temporary upload to it's permament storage directory(given proper permissions). If the destination file already exists, it will be overwritten - so it is important to rename uploaded files properly to avoid collisions.

7Toggle answer visibilityWhat is the Fileinfo extension? How is it used?

The Fileinfo Extension was added to PHP > v5.3. It's usage allows your script to determine information about a file by by parsing the file for “magic bytes” or “magic numbers” that indicate the file's actual encoding. By passing the function predefined constants, you can retrieve that particular information about the file. This is the preferred method for retrieving file mime types, replacing the deprecated mime_content_type() function. In order to use the extension you must first initialize the resource, then pass it the filename. Once the information needed is extracted, the resource must be closed. Always test for the existence of this function before use to avoid errors.

		$file = $_FILES['upload']['tmp_name'];
		$finfo = finfo_open(FILEINFO_MIME_TYPE);
		$fileMimeType = finfo_file($finfo, $file);
		finfo_close($finfo);
		

8Toggle answer visibilityWhat does the htmlspecialchars() function do?

The htmlspecialchars() function converts specific html characters into their entity equivalents for output to a browser to display the content as plain text. The characters that are converted

  • '&' (ampersand) becomes '&'
  • '"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes ''' (or ') only when ENT_QUOTES is set.
  • '<' (less than) becomes '<'
  • '>' (greater than) becomes '>'
Use htmlspecialchars_decode() to reverse this process.

9Toggle answer visibilityWhat does the htmlentities() function do?

The htmlentities() function is a more thorough version of htmlspecialchars() in that it will check for and convert all applicable characters to HTML entities including non English language characters, such as French accents, the German umlaut, etc. Use html_entity_decode() to reverse the process.

10Toggle answer visibilityWhat does the strip_tags() function do?

The strip_tags() function removes all html (including comments) and php tags from a string. Strip_tags() assumes valid html -- so if your source is not properly formatted, results may vary. You can pass an optional parameter that would mark certain tags as allowed - these will not be removed.

11Toggle answer visibility What function converts newline characters into HTML break tags?

The nl2br() function returns the string with '<br />' or '<br>' inserted before all newlines (\r\n, \n\r, \n and \r). Very useful for maintaining format of user submitted data.

12Toggle answer visibilityWhat is the most important function in the Filter extension? How is it used?

filter_var(variable, filter[,options]); is used in the Filter Extension to filter variables using php's builtin filter type algorithms.Example To Determine if a variable is formatted as an email:

		$email = "tester@somesite.com";
		$is_email = filter_var($email,FILTER_VALIDATE_EMAIL); // $is_email = "tester@somesite.com" or FALSE on failure;
		

13Toggle answer visibility What are prepared statements? What benefits might prepared statements have over the standard method of querying a database?

A prepared statement is a more secure way to process MySql statements by sending the query and values in two steps. First the SQL statement is formulated using question marks as placeholders for actual values, then the query is "prepared" (parsed but not executed). Then the values are bound to the statement and the whole query gets executed on command. By binding parameters instead of including them directly you don't need to enclose strings in quotes or use the mysqli_escape_string(). The expected type is passed with the bound values and the function formats accordingly.

The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. For complex queries this process can take up enough time that it will noticeably slow down an application if there is a need to repeat the same query many times with different parameters. By using a prepared statement the application avoids repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster. The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions of the query are being built up with unescaped input, SQL injection is still possible).

14Toggle answer visibilityWhat is the syntax for using prepared statements?

		$e = 'email@example.com';
		$p = 'mypass';
		$q = "SELECT user_id, first_name FROM users WHERE email=? AND pass=SHA1(?)";
		$stmt = mysqli_prepare($dbc, $q);
		mysqli_stmt_bind_param($stmt, 'ss',$e, $p);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		

Source
<?php
$review = array(
	1 => array(
		'q'=>'What are some of the inappropriate strings and characters that could be indicators of potential spam attempts?',
		'a'=>'<p>A spam attempt would mean someone is trying to manipulate the way a contact form is submitted by including additional
		 header information that is appended to the mail() function. Tip offs include: content-type: , mime-version: ,
		multipart-mixed: , content-transfer-encoding: , bcc: , cc:, to: , or new line characters like: \r, \n, %0a, %0d .</p>'
	),
	2 => array(
		'q'=>'What does the stripos() function do? What is its syntax?',
		'a'=>'<p>The <b>stripos()</b> function returns the index of the first instance of a substring found within a given string. It
		is case insensitive. If no substring is found it returns false. Use the === operator for testing the return value of this function as
		string position 0 will evaluate to false if use regular == comparison operator.
		<pre>
		$string = "I am a string.";
		$needle = "i";
		$offset = 0; //optional
		$position = stripos($string, $needle, $offset); // $position = 0;
		</pre></p>'
	),
	3 => array(
		'q'=>' What does the str_replace() function do? What is its syntax?',
		'a'=>'<p>The <b>str_replace()</b> function searches a string or array for a substring and replaces all occurances with another defined value(can 
			also be a string or array) Count can also be set to limit the number of replacements that occurs. Because str_replace() replaces left to right, 
			it might replace a previously inserted value when doing multiple replacements. This is case sensitive, use str_ireplace() for 
			case-insensitive string replacement.
		<pre>
		$string = "I am a string.";
		$search = "I am";
		$replace = "You are";
		$count = 1;
		$newstring = str_replace($search, $replace, $string, $count); // $newstring = "You are a string"
		</pre></p>'
	),
	4 => array(
		'q'=>'What does the array_map() function do? What is its syntax?',
		'a'=>'<p>The <b>array_map()</b> function returns an array containing all the elements of array after applying the callback
		 function to each one. The number of parameters that the callback function accepts should match the number of arrays
		  passed to the array_map() (Contrast the array_walk() function).
		  <pre>
		  $array = array("a","b","c","d","e");
		  function capitalize($string) {
		  	return ucfirst($string);
		  }
		  $newArray = array_map("capitalize", $array); //$newArray = array("A","B","C","D","E")
		  </pre></p>'
	),
	5 => array(
		'q'=>'What is typecasting? How do you typecast a variable in PHP?',
		'a'=>'<p>Typecasting is a way to force a variable to convert to the indicated type. It is a way to force validation of 
		data before processing. Since PHP is a loosely typed language,  a variable\'s type is determined by the context in which 
		the variable is used. Simply prepend the cast in parenthesis to the variable name. Allowed typecasts include<ul>
	    <li>(int), (integer) - cast to integer</li>
	    <li>(bool), (boolean) - cast to boolean</li>
	    <li>(float), (double), (real) - cast to float</li>
	    <li>(string) - cast to string</li>
	    <li>(array) - cast to array</li>
	    <li>(object) - cast to object</li>
	    <li>(unset) - cast to NULL (PHP 5)</li></ul>
		<pre>
		$foo = "1";
		echo gettype($foo); // outputs "string" 
		$too = (int)$foo;
		echo gettype($foo); // outputs "string"
		echo gettype($too); // outputs "integer"
		</pre>
		To overwrite the type of the variable without reassignment use settype($var, $type). Typecasting is particularly important
		when using numbers in mysql statements!</p>'
	),
	6 => array(
		'q'=>'What function is used to move an uploaded file to its final destination on the server?',
		'a'=>'<p>Once a file is uploaded using php, you can use the function  
		<pre>
		move_uploaded_file($tmp_name, "$uploads_dir/$name");
		</pre>
		to move the temporary upload to it\'s permament storage directory(given proper permissions). If the destination
		file already exists, it will be overwritten - so it is important to rename uploaded files properly to avoid collisions.</p>'
	),
	7 => array(
		'q'=>'What is the Fileinfo extension? How is it used?',
		'a'=>'<p>The Fileinfo Extension was added to PHP > v5.3. It\'s usage allows your script to determine information about a file by 
		by parsing the file for “magic bytes” or “magic numbers” that indicate the file\'s actual encoding. By passing the function predefined 
		constants, you can retrieve that particular information about the file. This is the preferred method for retrieving file mime types,
		replacing the deprecated mime_content_type() function. In order to use the extension you must first initialize the resource, then pass 
		it the filename. Once the information needed is extracted, the resource must be closed. Always test for the existence of this function
		before use to avoid errors.
		<pre>
		$file = $_FILES[\'upload\'][\'tmp_name\'];
		$finfo = finfo_open(FILEINFO_MIME_TYPE);
		$fileMimeType = finfo_file($finfo, $file);
		finfo_close($finfo);
		</pre></p>'
	),
	8 => array(
		'q'=>'What does the htmlspecialchars() function do?',
		'a'=>'<p>The <b>htmlspecialchars()</b> function converts specific html characters into their entity equivalents for 
		output to a browser to display the content as plain text. The characters that are converted<ul>
		<li>\'&\' (ampersand) becomes \'&amp;\'</li>
	    <li>\'"\' (double quote) becomes \'&quot;\' when ENT_NOQUOTES is not set.</li>
	    <li>"\'" (single quote) becomes \'&#039;\' (or &apos;) only when ENT_QUOTES is set.</li>
	    <li>\'<\' (less than) becomes \'&lt;\'</li>
	    <li>\'>\' (greater than) becomes \'&gt;\'</li></ul>
	    Use htmlspecialchars_decode() to reverse this process.
	 	</p>'
	),
	9 => array(
		'q'=>'What does the htmlentities() function do?',
		'a'=>'<p>The <b>htmlentities()</b> function is a more thorough version of htmlspecialchars() in that it will check for and
		convert all applicable characters to HTML entities including non English language characters, such as French accents, the 
		German umlaut, etc. Use html_entity_decode() to reverse the process.</p>'
	),
	10 => array(
		'q'=>'What does the strip_tags() function do?',
		'a'=>'<p>The <b>strip_tags()</b> function removes all html (including comments) and php tags from a string. Strip_tags() assumes
		valid html -- so if your source is not properly formatted, results may vary. You can pass an optional parameter that would mark 
		certain tags as allowed - these will not be removed.</p>'
	),
	11 => array(
		'q'=>' What function converts newline characters into HTML break tags?',
		'a'=>'<p>The <b>nl2br()</b> function returns the string with \'&lt;br /&gt;\' or \'&lt;br&gt;\' inserted before all newlines (\r\n, \n\r, \n and \r).
		 Very useful for maintaining format of user submitted data.</p>'
	),
	12 => array(
		'q'=>'What is the most important function in the Filter extension? How is it used?',
		'a'=>'<p><b>filter_var(variable, filter[,options]);</b> is used in the Filter Extension to filter variables using php\'s builtin
		filter type algorithms.Example To Determine if a variable is formatted as an email:
		<pre>
		$email = "tester@somesite.com";
		$is_email = filter_var($email,FILTER_VALIDATE_EMAIL); // $is_email = "tester@somesite.com" or FALSE on failure;
		</pre></p>'
	),
	13 => array(
		'q'=>' What are prepared statements? What benefits might prepared statements have over the standard method
		 of querying a database?',
		'a'=>'<p>A prepared statement is a more secure way to process MySql statements by sending the query and values in two steps. 
		First the SQL statement is formulated using question marks as placeholders for actual values, then the query is "prepared" (parsed 
		but not executed). Then the values are bound to the statement and the whole query gets executed on command. By binding parameters
		instead of including them directly you don\'t need to enclose strings in quotes or use the mysqli_escape_string(). The expected type is 
		passed with the bound values and the function formats accordingly.</p>
		<p>The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. 
		When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. 
		For complex queries this process can take up enough time that it will noticeably slow down an application if there is a 
		need to repeat the same query many times with different parameters. By using a prepared statement the application avoids 
		repeating the analyze/compile/optimize cycle. This means that prepared statements use fewer resources and thus run faster.
    	The parameters to prepared statements don\'t need to be quoted; the driver automatically handles this. If an application 
    	exclusively uses prepared statements, the developer can be sure that no SQL injection will occur (however, if other portions 
    	of the query are being built up with unescaped input, SQL injection is still possible).</p>'
	),
	14 => array(
		'q'=>'What is the syntax for using prepared statements?',
		'a'=>'<p>
		<pre>
		$e = \'email@example.com\';
		$p = \'mypass\';
		$q = "SELECT user_id, first_name FROM users WHERE email=? AND pass=SHA1(?)";
		$stmt = mysqli_prepare($dbc, $q);
		mysqli_stmt_bind_param($stmt, \'ss\',$e, $p);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_close($stmt);
		</pre></p>'
	)
);
include('templates/review.php');