PHP 2 Flashcards
How do you obtain the IP address of a client?
$_SERVER[‘REMOTE_ADDR’];
Please note this is note safe as it can be faked by the client. It may also not be the ip of the client, rather the proxy
How do you determine the type of web browser that the user is using?
$_SERVER[‘HTTP_USER_AGENT’];
What constant in PHP stores the current file name?
__FILE__
What is one way of getting the current file name?
$current_file = basename($_SERVER[‘PHP_SELF’]);
What global variable (not constant) holds the name of the current file?
$_SERVER[‘PHP_SELF’]
In a regex expression, what does \b match?
Word boundaries. Very useful for picking the first letter in a sentence for example:
/(\b[a-z])/i
What would one way be to retrieve a web page and print the source out with line numbers?
Use ‘file’ to obtain an array of the lines, then print them out passing each line through htmlspecialchars
What is the difference between sort and usort?
usort uses a user defined comparison function
If you unset an element in an array, are the integer keys reordered?
No - it is common to use unset to remove an element out of an array, but elements after it will continue their numbering scheme. Use sort to fix this.
By default json_decode returns data in objects, how do you make it return the data in an associative array?
Set the second parameter to true.
Why use array_walk_recursive over array_walk?
In some cases an array will contain another array (i.e. nested json) - array_walk will fail in this case.
You can sort an array by key ksort - how would you sort the same array in reverse?
krsort
You can sort an array by value using asort, how would you sort the same array in reverse?
arsort
You’ve been asked to add up all the elements in an array, do you write a function or use a function in built in php
Use an inbuilt function, namely array_sum
What function can be used to make an array of arrays?
array_map - if you pass the callback function as null, it will create an array of arrays from a given set of arrays.
What does is_scalar test for?
Whether a value is scalar or not - a scalar variable is an atomic variable, whereas arrays, objects and resources are not scalars
How would you obtain an array of numbers that fit within a range. I.e. from 0-16, but in steps of 4?
range(0,16,4);
How could you create a random list of numbers in a range, without calling rand()?
$a = range(1, 10);
shuffle($a);
$a is now an array containing a random order of numbers
How would you take a string and convert it into an array of characters so they can be traversed?
$array_char = str_split($str);
How could you use substr to check each character in a string
for ($x = 0; $x < strlen($str); $x++) { if (substr($text, $x, 1) == $search_char) { // Do stuff } }
How would you tell curl to inform a server that you can recieve compressed data to your application?
$header[] = “Accept-Encoding: compress, gzip”;
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $header);
Why is it important that a webbot emulate a standard browser?
Firstly, it reduces the risk of sites from detecting the presence of a web bot - but in cases where you want compressed files, most servers check for valid web clients before sending compressed data.
What test can you do to determine if the incoming file is compressed?
if (stristr($http_header, “zip”))
$compressed = TRUE;
(This assumes you’ve extracted the header into $http_header)
What function could you use to decompress a file in PHP?
gzuncompress($filename);
I have an interface with a number of const’s, how do I access them?
interfaceName::ConstName;
What is one reason for overriding the __unset magic method?
You may wish to unset or manage associated data (i.e. a database connection) when the main variable is unset.
What is a good use for the __sleep magic method?
If an object is serialized, it may be necessary to disconnect any objects that should not be serialized along with it - including things like database connections.
If you use the __sleep magic method, what must it return?
An array of the object variables that you wish to serialised from within the object.
What has largely replaced the __sleep / __wake magic methods?
The SPL now provides an interface called Serializable
What is one advantage of the Serializable interface over the old method using magic methods?
It is now type hintable (because interfaces are type hintable)..
What is one important use for the __toString magic method?
Templating engines - being able to print out the name of the object is important in these kind of engines.
What is one purpose of the __invoke magic method?
To allow an object to be used like a function.
Name some uses of the __clone magic method?
By making it private, you can prevent an object from being copied. You can also use it to reset database connections or other resources just before the object is copied.
Given the following classes: class myClass{} class secondClass extends myClass{} class thirdClass extends secondClass{}
is the following statement true? $obj = new thirdClass(); $result = $obj instanceof myClass;
Yes - due to inheritance, the child class inherits all the attributes of the parent class, and is therefore an instance of the parent class (which allows typehinting to work with child objects)
When passing an object and using typehinting, what is one major consideration?
It is possible to pass a parent object that may not have all the methods the more specialised child has. This means you can call a method that does not exist and cause a fatal error. Using an interface (that should guarantee a method exists) will help.
Can an interface define a protected or private method?
No
Anonymous functions are also known as…
closures
Internally, is an anonymous function really a function?
No, it is an object of type Closure
What is one use for the __invoke magic method of an object?
In functions that take a callback, PHP sometimes requires an array with the object and a string defining the method to call as a callback. Using __invoke, you can pass the object directly, and the system will cause the __invoke method on the object to be called. As long as __invoke has been implemented, the correct code should be called.
Exceptions that rise to the top level are logged by PHP, what about exceptions that are caught and handled?
No - these need to be logged
Is it possible to register multiple autoload functions using spl_autoload_register?
Yes - it behaves like a queue, it will call the first registered function first and so on.
What is wrong with the following code?
foreach ($bindings as $key => $val) {
$stm->bindParam($key, $val);
}
When using bindParam, it expects to receive the reference to the $val variable.
// NOTE the ampersand foreach ($bindings as $key => &$val) { $stm->bindParam($key, $val); }
What is an alternative to using bindParam in a loop - and what would be different about the loop?
You can use PDOStatement::bindValue($key, $val). The loop would not need to pass by reference.
// Notice - no & on the $val foreach ($bindings as $key => $val) { $stm->bindValue($key, $val); }
What function would you use to remove any empty array elements?
array_filter($array);
If you are throwing an exception in one class, and the calling class doesn’t catch the exception, what is one possible reason that it doesn’t get caught?
If you are using namespaces, you will need to either use the ‘use’ clause, or explicitly use the full path to the exception class.
catch(\InvalidArgumentException($error)) { }
While you’ve probably remembered to do this in the throw statement (it will throw an error if you don’t) - it will fail silently in the catching class.
What is one reason to avoid using the .inc file extension for class files?
Some browsers display this as plain text, which (if sensitive information was stored here) would be a security risk.
What is one way to store meta data that can be used to configure the behaviour of a class?
Use PHPDoc syntax to store the meta data.
Given a function that takes a key, and deletes it, what is wrong with this code:
public function delete_key($key) { if ($key) { unset(this->data[$key]); } }
A key in an array could well be 0, and if that is the case, $key will fail - because 0 also === false. Therefore the key would never be deleted.
if (false !== $key)
Would be better.
What is YAML?
It is a markup language (YAML A’int Markup Language) - it is a human readable language, and takes concepts from C, Perl and Python and XML and uses the data format from electronic mail.
If you get the error ‘browscap ini directive not set’ when using the function get_browser(), what is that refering to?
In the php.ini configuration file you have to point the browscap.ini directive to the file (which must be downloaded as it doesn’t come with PHP by default).
What is one clean way to test whether an element exists in an array, and if it does assign it to a variable - WITHOUT using the ternary ? operator?
isset($array[‘element’]) && $this->val = $array[‘element’];
NOTE: This works because if the left hand side of the && is false, it will fail - otherwise it will attempt the right hand side. Because assignment is always true - this will work.
What method would you use to get the last element of an array?
end($myArray);
Why do you need to filter input AND escape output?
Users could use a CSRF (Cross Site Request Forgery). Basically, a user sends another user a link with a page variable already filled in - the variable with be set to a malicious script. If the other user clicks on this link while logged into the site, it will execute with their privileges, allowing the malicious user to do things like grab cookie data, or run code as that user.
What two functions in combination are useful for dealing with CSRF attacks?
filter_input
htmlspecialchars
If you are not using namespaces, but are using the composer autoloader - how would you tell composer where to look for classes?
In the composer.json file use the following { "autoload": { "classmap": ["src/"] } }
What is sso?
Single Sign On - an enterprise system that allows one sign in to access all content on a site. Also RSO - Reduced Sign On - which may have multiple layers if authentication complexity depending on what the user is trying to access.
Why should you never leave an empty catch block?
Swallowing an exception means that the error is never seen - PHP ONLY logs errors if the error is unhandled. So you either need to leave them unhandled (bad) - or handle them.
What is a good way to handle non-fatal exceptions in PHP?
Catch the error - log the error, and store an error message (possibly in the session). Then redirect to an error page that can give the user information about what the error was.
What does the ‘compact’ function do?
It takes an array of variable names, and if there is a corresponding variable name in scope, it will create an array with the variable names as keys, and the variable data as values. Works the opposite to explode.
$name = 'superman'; $hat = 'red';
$myvars = [ 'name', 'hat']; $result = compact ($myvars);
results in :
array {
‘name’ => ‘superman’
‘hat’ => ‘red’
}
What should you always set in a PHP 5.+ app?
date_default_timezone_set(‘UTC’)
(or to your location such as ‘Japan’.
This is because most functions in PHP require this information to be set.
What is the difference between && and AND
The AND operator has a different precedence than the && operator.
What would be the result of this?
$this = true;
$that = false;
$truthiness = $this AND $that;
$truthiness will equal TRUE, which may not be what is expected. The reason being - AND has a different precedence to &&.
($truthiness = $this) AND $that; $truthiness = ($this && $that);
Because ‘=’ has a higher precedence than AND, but not a higher precedence than &&.
How do you ensure your app is using UTF8 characters?
Call
mb_internal_encoding(‘UTF-8’);
At the beginning of the script.
How can you be sure you are outputting UTF-8 data to the browser?
Call
mb_http_output(‘UTF-8’);
At the beginning of the script.
If you are storing UTF8 strings in a database, what encoding / collation should the be?
utf8mb4
In a GET request, form arguments are in the query string, where are they in a POST request?
In the request body
The request needs a …………… header that tells the server the size of the content to expect in the body?
Content-Length
What CURLOPT_ define is used to specify a custom request type?
curl_setopt($c, CURLOPT_CUSTOMREQUEST, ‘PUT’);
How do you use curl_setopt to specify the HTTP header?
curl_setopt($c, CURLOPT_HTTPHEADER, array(‘Content-Type: application/json’);
Once you have sent a PUT request, how do you read it on the server side?
There is no $_PUT magic array in php - instead you can use a file stream reader, as put requests come in via stdin.
$data = file_get_contents(“php://input”);
How would you parse the input from a PUT request?
Generally, you can use:
parse_str($inputdata, $outputarray);
Don’t forget to use the $outputarray, or else the variables get written to local scope (BAD).
To upload a file with cURL, what three options are very useful?
CURLOPT_PUT - set to true
CURLOPT_INFILE - set to a file handle of that file
CURLOPT_INFILESIZE - set to size of file
What cURL option is useful for dealing with cookies?
CURLOPT_COOKIEJAR
Considering a setup where .htaccess routing is not configured - is the following a valid url?
http://localhost/books.php/mybook
Yes - books.php will be accessed - and mybook will be accessible through the $_SERVER[‘PATH_INFO’] global variable.
What is a simple PHP way to test if a string is JSON?
Call json_decode on the string. Then call json_last_error and check if there was an error.
json_decode($str); return json_last_error();
Would the following resource URL be thought of as RESTful?
/client/add
No - resources are best thought of nouns. The given example is using a URL to describe an action.
If urls should not describe actions in a RESTful system, what does describe the actions?
The HTTP request type (i.e. GET, POST, PUT, DELETE)
HTTP Verbs tell the server…
what action to take on the given url resource.
In a RESTful system, can data be modified on the server as a result of a GET request?
No - it should not be modified.
POST requests should not use the resource at the given URL, rather…
an additional ID is supplied after the resource, to indicate which resource is to be modified.
What is the difference between safe and unsafe HTTP methods?
Safe methods are those that don’t modify resources at all. Those that modify data are called unsafe methods. GET (out of POST/DELETE/GET/PUT) is the only safe method.
What is an ‘idempotent’ method?
It is a method that achieves the same result no matter how many times it is repeated. Usually the idempotent methods in HTTP are GET/PUT/DELETE.
(i.e. a GET will always return the same results (given no changes), a repeated PUT should not change the original data, no matter how many times it is called, unless the data changes. Delete can obviously not be achieved more than once on a given resource. Once deleted - it’s deleted.)
What method in HTTP is not considered idempotent?
POST
Is the nature of the idempotent/non-idempotent methods determined by the HTTP spec?
No - it is up to the programmer to make sure the methods behave in this way.
The content type of the HTTP response is configured where?
The HTTP header
What is the benefit of modifying the HTTP header to specify the content type (beyond getting the correct content type)?
You change the content type based on who is consuming it - i.e. text for a browser, json for an application.
What is one of the first things you do when you receive a request for a resource in REST?
Determine what request type it was using $_SERVER[‘REQUEST_METHOD’]
What is the second thing that we do when receiving a request for a resource in REST?
Determine what resource was requested, using $_SERVER[‘REQUEST_URI’]
What PHP function do you use to notify the requesting client about the status of their request?
header();
i.e. it could be:
header(‘HTTP/1.1 405 Method Not Allowed’);
header(‘Allow: GET, PUT, DELETE’);
Why would the following print:
“10NumberYeah?” instead of
“NumberYeah?10” ?
class foobar { protected $foobar = 10; public function chicken() { echo $this->foobar; } } $myObject = new foobar(); echo 'Number: ' . "Yeah?" . $myObject->chicken();
Because echo is being used instead of return in the method chicken. Because of the way functions are called, it is called first in the echo statement at the bottom, resulting in 10 being echoed, then the rest of the string being printed.
If it had been returned, it would be appended to the end as expected.
What will the following look like?
class object { protected $foobar = 10; }
echo json_encode(new object());
{}
The json_encode call will not access variables that are protected / private.
What is the purpose of the array_unique function?
It takes and array, and returns a new version of the array with no duplicate entries.
If you use a trait on a class, and it has a method with the same name as method on that class - which method gets called?
The class has precedence in this case, so the method on the class will be called.
If you use a trait on a class that extends another class - and that class has a method with the same name as the one on the trait, which one gets called?
The method on the trait takes precedence, therefore it is the one that is called.
In MVC, the model is actually a what?
Layer
How should the M communicate with the V and C?
Via services
If you extend from a base class that has a constructor that expects a value, and your child constructor doesn’t pass that value on, what error do you get?
No error - it allows it - but it does mean the parent will not be initialised correctly.
If you extend from a base class that has a constructor which expects a parameter, and your child class does not implement a constructor at all, what error do you get (assuming you pass the parameter when calling new)?
None - if you provide a parameter when creating the object. The child class inherits it’s parents constructor and that will be used to initialise the object.
If you extend from a base class that has a constructor that expects a parameter, and you do not pass any parameters when creating the child object, what error do you get?
Fatal error - the parent class is expecting a parameter and did not receive it.
If you extend from a base class that has a constructor that expects a parameter, but your child class has a constructor that takes no parameter, what error do you get?
None - it is up to you to pass on that value (using parent::__construct) - or else the system will just create it normally.
In order to execute a global regex search using preg_match, what do you need to do?
Use the function preg_match_all - preg_match does not take ‘g’ as a global argument.
In order to run a case insensitive search using preg_match, what do you do?
Use the ‘i’ modifier on the regex. i.e. ‘/car/i’
Regular expressions are…
eager (i.e. want to return a match as soon as possible)
The ‘.’ character in regex will match any character except…
newline
What is wrong with the following regex? /9.00/
It will match 9.00, but it is likely it was meant to match 9.00 dollars. The error is that it will also match 9500, 9-00.
The way to fix it is to escape the meta character.
/9.00/
Are quotation marks meta characters in regex?
No, it does not need to be escaped.
Why do you need to escape forward slashes in a regex when you are trying to match a file path?
Because in a language where you need to enclose the regex in forward slashes, it will read the forward slash as the end of the regex (prematurely).
/foobar/foochicken/chicke.txt
Will need the regex:
/\/foobar\/foochicken\/chicke.txt/
What character is used to search for tabs?
\t
What three possibilities would you need to search for with new lines?
\n
\r
\r\n
Will /gr[ea]t/ match the word “great”?
No - [ea] only matches on character, either e or a.
When is the ‘-‘ character a meta character?
Only when it’s in a character set. i.e. [1-9]
What is the issue with [50-99]
It wont give you 50-59, it’s still just 0-9
How do you negate a character set? Say /[abcde]/
/[^abcde]/
This will mean it will match anything but a,b,c,d,e
Will this match the word “seem”?
/see[^k]/
Yes
Will this match the word “see”? (assuming there is no space after the word see)?
/see[^k]/
No - there still must be a character in that last spot, just not the letter k.
Metacharacters inside a character set need to be escaped, true of false.
False.
[abc.ef] - The dot in this case would only match ‘.’s. It is not acting as a wildcard. Therefore it does not need to be escaped.
The exceptions are “] - ^ and " - This is because they are characters used specifically in character sets.
When trying to match a sequence like
file-1 file01 file\1 and file_1,
What is wrong with the following pattern?
/file[0-_]1/
The dash and the \ will need to be escaped, it should be:
/file[0-\_]1/
What is the difference between \d and \D
\d is a digit, \D is not a digit.
With regards to \w, word characters, what is the difference between ‘-‘ and ‘_’?
’-‘ is considered punctuation and is not a word characters, however ‘_’ is a word character.
Does \d\d\d\d match 1984?
Yes
Does \w\w\w\w match 1984?
Yes digits are considered word characters, but note: word characters are not considered digits.
When would you use \s over just a simple space?
If you wanted to also capture a tab or line return character.
Can you use shortcuts in character sets?
Yes
[\d\s] is valid