PHP - Adv

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What will NOT instantiate a DateTime object with the current timestamp?

$date = new DateTime(time()); Fatal error: Uncaught Exception: Failed to parse time *Unix Epoch* string The time() function returns the current time in the number of seconds since the Unix Epoch

Given the following DateTime object, which sample will NOT alter the date to the value'2014-02-15'? $date = new DateTime('2014-03-15');

$date->diff(new DateInterval('-P1M')); diff expects a DateTimeInterface. NOT a DateInterval

Using Namespaces

$table = new Html\Table() $row = new Html\Row();

What function can be used to retrieve an array of current options for a stream context?

*stream_context_get_options*() Retrieve options for a stream/wrapper/context. Returns an array of options on the specified stream or context. stream_context_get_options(resource $stream_or_context): array

Which one of the following XML declarations is NOT valid?

<?xml standalone="1" ?>

Which of the following is true about stream contexts?

A context can modify or enhance the behavior of a stream A context is a set of parameters and stream wrapper specific options

Which three statements about final are true?

A final class may be instantiated. A class with a final function may be derived. Static functions can be final.

Which of the following can be registered as entry points with a SoapServer instance

A single function All methods from a class

Which technique should be used to speed up joins without changing their results?

Add indices on joined columns

What is the benefit of using persistent database connections in PHP?

Allows connection settings such as character set encoding to persist Allows for resumption of transactions across multiple requests.

Session Fixation

App does not generate a new session ID. They trick the user into loggin in with compromised session ID use_strict_mode = On

Type hinting in PHP allows the identification of the following variable types

Array Any class or interface type

call_user_func_array()

Call a callback with an array of parameters call_user_func_array(callable $callback, array $args): mixed EXAMPLE: function Test(){ $args = func_get_args(); call_user_func_array("printf",$args); } Test("Candidates 2014: %s %s %s %s\n","Tom","Debbie","Harry", "Sally");

Which 3 tasks can be achieved by using magic methods?

Converting objects to string representation Processing access to undefined methods or properties Initializing or uninitializing object data

DateTime - format '03-03-2013'

DateTime::createFromDate('d-m-Y', '03-03-2013');

What statement about interfaces is correct

Interfaces can extend more than one interface

Which interfaces could class C implement in order to allow each statement in the following code to work? $obj = new C(); foreach ($obj as $x => $y) { echo $x, $y; }

IteratorAggregate Iterator

How should class MyObject be defined for the following code to work properly? Assume $array is an array and MyObject is a user-defined class. $obj = new MyObject(); array_walk($array, $obj);

MyObject should implement method __invoke The __invoke() method is called when a script tries to call an object as a function.

What statement about type declarations are NOT correct

Only methods can have type hints. That is false! Type hinting is a feature that PHP provides to declare types of class variables, function parameters and return values

The DateInterval class - how to use

P1Y2M3DT4H5M *Every string begins with P* *Time units are split from the date units by the letter T* Used to store either a fixed amount of time (in years, months, days, hours, etc.) or a relative time string in the format that DateTime's constructor supports. The DateTime class allows you to add() or sub() a DateInterval from a DateTime. It will handle leap years and other time adjustments while doing so. DateInterval::createFromDateString('P1Y2M3DT4H5M');

What statement about PDO is NOT true

Placeholders within PDO prepared statements need to be named.

Session Hijacking

Present someone elses session identifier to the server : cookies_secure = On

Which of the following is used to find all PHP files under a certain directory?

RecursiveDirectoryIterator

substr_replace

Replace text within a portion of a string substr_replace( array|string $string, array|string $replace, array|int $offset, array|int|null $length = null ): string|array echo substr_replace('john', 'jenny', 0, 0); //jennyjohn

What statements about SOAP are *NOT* true?

SOAP requires developers to use WSDL.

When move_uploaded_file() is used, what 2 actions must be taken before this code may go into production?

Sanitize the file name in $_FILES['myFile']['name'] because: 1) this value is not consistent among web browsers. 2) this value could be forged.

You work for a shared hosting provider, and your supervisor asks you do disable user scripts to dynamically load PHP extensions using the d1() function. How can you do this?

Set enable_d1 to off in the server's php.ini configuration file Add d1 to the current value of disable_functions in the server's php.ini configuration file.

Which SPL class implements fixed-size storage?

SplFixedArray The SplFixedArray class provides the main functionalities of array. The main difference between a SplFixedArray and a normal PHP array is that the SplFixedArray must be resized manually and allows only integers within the range as indexes. The advantage is that it uses less memory than a standard array.

Your application uses PHP to accept and process file uploads. It fails to upload a file that is 5 MB in size, although upload_max_filesize is set to "10M". What configurations could be responsible for this outcome?

The PHP configuration option *post_max_size* is set to a value that is too small The hidden form field *MAX_FILE_SIZE* was set to a value that is too small

How do you allow the caller to submit a variable number of arguments to a function? (2 ways)

Using a prototype like function test(...$parameters) Using a prototype like function test() and the function func_get_args() inside the function body

SimpleXML provides the ability to iterate over items in an XML document, as well as access items within it as if they were object properties. When creating your own classes to access data, implementing what would NOT achieve this goal?

__toString

Your supervisor wants you to disallow PHP scripts to open remote HTTP and FTP resources using PHP's file functions. Which php.ini setting should you change accordingly?

allow_url_fopen allow_url_fopen=off allow_url_fopen = off

What content-type is required when sending an HTTP POST using JavaScript to ensure that PHP can access the data?

application/x-www-form-urlencoded

Which function will allow identifying unique values inside an array

array_count_values() Counts all the values of an array. Returns an array using the values of array (which must be ints or strings) as keys and their frequency in array as values. print_r( array(1, "hello", 1, "world", "hello")); [1] => 2 [hello] => 2 [world] => 1

Forwarding Calls

calls introduced by late static binding of self:: parent:: static:: forward_static_call()

forward_static_call() example

class A { const NAME = 'A'; public static function test() { $args = func_get_args(); echo static::NAME, " ".join(',', $args)." \n"; } } class B extends A { const NAME = 'B'; public static function test() { echo self::NAME, "\n"; forward_static_call(array('A', 'test'), 'more', 'args'); forward_static_call( 'test', 'other', 'args'); } } B::test('foo'); function test() { $args = func_get_args(); echo "C ".join(',', $args)." \n"; } // B // B more,args // C other,args

specify strict

declare(strict_types=1); // strict requirement

Which elements does the array return by the function pathinfo()

dirname, basename, extension, filename pathinfo() returns information about path: either an associative array or a string, depending on flags.

The readfile() function reads

function reads a file and writes it to the output buffer

The preg_match() function will tell you

function will tell you whether a string contains matches of a pattern.

functions for class properties (3 functions)

get_class_vars('string'); get_object_vars($object); property_exists(

What PHP functions can be used to set the HTTP response code

header() Send a raw HTTP header http_response_code() Get or Set the HTTP response code

higher order function

if a function accepts other functions as arguments, or returns functions as results $second_art_isnt_zero = function ($func) { return function(... $args) { if($args[1] == 0) { echo "cannot divide by zero"; return null; } return $func(... $args); } };

The constructs for(), foreach(), and each() can all be used to iterate an object if the object...

implements Iterator and ArrayAccess

what can you use to display errors in a particular script?

ini_set ('display_errors', 1); should be placed at top of script.

What DOM method is used to load HTML files

loadHTMLFile()

What methods are available to limit the amount of resources available to PHP through php.ini?

max_execution_time - Limit the maximum execution time of a script memory_limit - Limit the amount of memory a script can consume

What are NOT acceptable ways to create a secure password hash in PHP?

md5() openssl_digest() These two are NOT acceptable ways to secure passwords

To use a function as a callback function

pass a string containing the name of the function as the argument of another function. Pass a callback to PHP's array_map() function. PHP can pass anonymous functions as callback function. $strings = ["apple", "orange", "banana", "coconut"]; $lengths = array_map( function($item) { return strlen($item); } , $strings); print_r($lengths);

You need to escape special characters to use user input inside a regular expression. Which functions would you use?

preg_quote() takes str and puts a backslash in front of every character that is part of the regular expression syntax quote_meta() Returns a version of str with a backslash character (\) before every character that is among meta characters

The final keyword can be used to

prevent class inheritance or to prevent method overriding.

closure on first-class function

return a function from another function $x = 42; return function() use ($x) { echo $x }

What is the name of the function that allows you register a set of functions that implement userdefined session handling

session_set_save_handler()

Which PHP function sets a cookie and URL encodes its value when sending it to the browser?

setcookie

What SimpleXML function is used to parse a file?

simplexml_load_file()

What will set a 10 seconds read timeout for a stream?

stream_set_timeout($stream, 10); Sets the timeout value on stream, expressed in the sum of seconds and optional microseconds. stream_set_timeout(resource $stream, int $seconds, int $microseconds = 0): bool

What function allows resizing of PHP's file write buffer?

stream_set_write_buffer() Sets the buffering for write operations on the given stream to size bytes.

what function can you use to find how many substrings are in a string?

the substr_count(); substr_count($_POST['email'], '@') // counts @ signs in $_POST['email']

what can substr() be used for?

to find a substring in a larger string using indices; $sub = substr($string, 2, 10) assigns $sub ten characters of $string starting at the second character of $string.

Namespace Alias

use Html as H; $table = new H\Table(); use Html\Table as T; $table = new T();

what can urlencode() be used for?

when applied, the value can be passed safely through the URL (GET).

what can urldecode() be used for?

when applied, the value is decoded from its encoded nature; firstname+last name -> firstname lastname.


Ensembles d'études connexes

NSG 312 Exam 2 Lippincott: Assessment of Pregnancy

View Set

Great Diseases of The World Final Exam Review

View Set

Acid base balance Exemplar 1.B Metabolic Alkalosis

View Set

Unit 3 Lesson 2 How do Adaptations help plants?

View Set