Хотите пройти тесты на Upwork на хороший результат?
Подавайте заявку и мы поможем Вам это сделать!

Do You want to pass tests on Upwork with good scores?
Leave the request and we will help You to do that!

PHP Test 2017 (Top 10%)

Share on RedditPin on PinterestEmail this to someoneShare on TumblrShare on LinkedInShare on Google+Tweet about this on TwitterShare on FacebookShare on VK

Мы не гарантируем правильность всех предоставленных ответов.


190 Test Questions:

1. Which of the following is true about the singleton design pattern?

Answers:

• A singleton pattern means that a class will only have a single method.
• A singleton pattern means that a class can have only one instance object.
• A singleton pattern means that a class has only a single member variable.
• Singletons cannot be implemented in PHP.

2. Which of the following is useful for method overloading?

Answers:

• __call,__get,__set
• _get,_set,_load
• __get,__set,__load
• __overload

3. What is the best practice for running MySQL queries in PHP? Consider the risk of SQL injection.

Answers:

• Use mysql_query() and variables: for example: $input = $_POST[‘user_input’]; mysql_query(«INSERT INTO table (column) VALUES (‘» . $input . «‘)»);
• Use PDO prepared statements and parameterized queries: for example: $input= $_POST[«user-input»] $stmt = $pdo->prepare(‘INSERT INTO table (column) VALUES («:input»); $stmt->execute(array(‘:input’ => $input));
• Use mysql_query() and string escaped variables: for example: $input= $_POST[«user-input»] $input_safe = mysql_real_escape_string($input); mysql_query(«INSERT INTO table (column) VALUES (‘» . $input. «‘)»);
• Use mysql_query() and variables with a blacklisting check: for example: $blacklist = array(«DROP»,»INSERT»,»DELETE»); $input= $_POST[«user-input»] if (!$array_search($blacklist))) mysql_query(«INSERT INTO table (column) VALUES (‘» . $input. «‘)»);

4. Which of the following methods should be used for sending an email using the variables $to, $subject, and $body?

Answers:

• mail($to,$subject,$body)
• sendmail($to,$subject,$body)
• mail(to,subject,body)
• sendmail(to,subject,body)

5. Which of the following will print out the PHP call stack?

Answers:

• $e = new Exception; var_dump($e->debug());
• $e = new Exception; var_dump($e->getTraceAsString());
• $e = new Exception; var_dump($e->backtrace());
• $e = new Exception; var_dump($e->getString());

6. What will be the output of the following code?

<?php
var_dump (3*4);
?>

Answers:

• int(3*4)
• int(12)
• 3*4
• 12
• None of the above

7. Which of the following will start a session?

Answers:

• session(start);
• session();
• session_start();
• login_sesion();

8. Which of the following is incorrect with respect to separating PHP code and HTML?

Answers:

• Use an MVC design pattern.
• As PHP is a scripting language, HTML and PHP cannot be separated.
• Use any PHP template engine e.g: smarty to keep the presentation separate from business logic.
• Create one script containing your (PHP) logic outputting XML and one script produce the XSL to translate the XML to views.

9. Which of the following will read an object into an array variable?

Answers:

• $array_variable = get_object_vars($object);
• $array_variable = (array)$object;
• $array_variable = array $object;
• $array_variable = get_object_vars $object;

10. Which of the following is correct about Mysqli and PDO?

Answers:

• Mysqli provides the procedural way to access the database while PDO provides the object oriented way.
• Mysqli can only be used to access MySQL database while PDO can be used to access any DBMS.
• MySQLi prevents SQL Injection whereas PDO does not.
• MySQLi is used to create prepared statements whereas PDO is not.

11. Which of the following characters are taken care of by htmlspecialchars?

Answers:

• <
• >
• single quote
• double quote
• &
• All of these

12. Which function can be used to delete a file?

Answers:

• delete()
• delete_file()
• unlink()
• fdelete()
• file_unlink()

13. What would occur if a fatal error was thrown in your PHP program?

Answers:

• The PHP program will stop executing at the point where the error occurred.
• The PHP program will show a warning message and program will continue executing.
• Since PHP is a scripting language so it does not have fatal error.
• Nothing will happen.

14. What is the correct way to send a SMTP (Simple Mail Transfer Protocol) email using PHP?

Answers:

• s.sendmail($EmailAddress, [$MessageBody], msg.as_string())
• sendmail($EmailAddress, «Subject», $MessageBody);
• mail($EmailAddress, «Subject», $MessageBody);
• <a href=»mailto:$EmailAddress»>$MessageBody</a>

15. Which of the following is not a PHP magic constant?

Answers:

• __FUNCTION__
• __TIME__
• __FILE__
• __NAMESPACE__
• __CLASS__

16. Which of the following is used to maintain the value of a variable over different pages?

Answers:

• static
• global
• session_register()
• None of these

17. Which of the following is not related to debugging in PHP?

Answers:

• watch
• PDO
• breakpoints
• call stack

18. Should assert() be used to check user input?

Answers:

• Yes
• No

19. Which function will suitably replace ‘X’ if the size of a file needs to be checked?

$size=X(filename);

Answers:

• filesize
• size
• sizeofFile
• getSize

20. Which of the following is not a predefined constant?

Answers:

• TRUE
• FALSE
• NULL
• __FILE__
• CONSTANT

21. What will be the output of the following code?

<?php
$str=»Hello»;
$test=»lo»;

echo substr_compare($str, $test, -strlen($test), strlen($test)) === 0;
?>

Answers:

• FALSE
• Syntax error
• 0
• 1

22. Which of the following functions is not used in debugging?

Answers:

• var_dump()
• fprintf()
• print_r()
• var_export()

23. Which of the following cryptographic functions in PHP returns the longest hash value?

Answers:

• md5()
• sha1()
• crc32()
• All return the same hash value length.

24. Consider the following class:

1 class Insurance
2 {
3 function clsName()
4 {
5 echo get_class($this);
6 }
7 }
8 $cl = new Insurance();
9 $cl->clsName();
10 Insurance::clsName();

Which of the following lines should be commented to print the class name without errors?

Answers:

• Line 8 and 9
• Line 10
• Line 9 and 10
• All the three lines 8,9, and 10 should be left as it is.

25. Without introducing a non-class member variable, which of the following can be used to keep an eye on the existing number of objects of a given class?

Answers:

• Adding a member variable that gets incremented in the default constructor and decremented in the destructor.
• Adding a local variable that gets incremented in each constructor and decremented in the destructor.
• Add a static member variable that gets incremented in each constructor and decremented in the destructor.
• This cannot be accomplished since the creation of objects is being done dynamically via «new.»

26. Which of these is not a valid PHP XML API?

Answers:

• a.libxml_clear_errors()
• b.libXMLError()
• c.libxml_get_errors()
• d.libxml_use_internal_errors()

27. Which of the following is not a valid API?

Answers:

• trigger_print_error()
• trigger_error()
• debug_backtrace()
• debug_print_backtrace()

28. Which of the following is true about posting data using cURL in PHP?

Answers:

• Data can be posted using only the POST method.
• Data can be posted using only the GET method.
• Data can be posted using both GET and POST methods.
• Data cannot be posted using cURL.

29. Which of the following is the correct way to check if a session has already been started?

Answers:

• if ($_SERVER[«session_id»]) echo ‘session started’;
• if (session_id()) echo ‘session started’;
• if ($_SESSION[«session_id»]) echo ‘session started’;
• if ($GLOBALS[«session_id»]) echo ‘session started’;

30. Which statement will return true?

Note: There may be more than one right answer

Answers:

• a. is_numeric («200»)
• b. is_numeric («20,0»)
• c. is_numeric («$200»)
• d. is_numeric («.25e4»)
• e. None

31. Which of the the following are PHP file upload-related functions?

Answers:

• upload_file()
• is_uploaded_file()
• move_uploaded_file()
• None of these

32. Which of the following statements regarding PHP forms, are correct?

Note: There may be more than one right answer

Answers:

• In PHP, the predefined $_POST variable is used to collect values in a form with method=»post».
• In PHP, the predefined $_GET variable is used to collect values in a form with method=»get».
• In PHP, the predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
• Information sent from a form with the POST method is invisible to others and has an 8MB limit on the amount of information to send, which cannot be changed.

33. What is the output of the following code?

<?php
$array = array(«1″,»2″,»3″,»4»);
$variable = end(array_keys($array));
echo $variable;
?>

Answers:

• 1
• 2
• 3
• 4

34. What would be the output of the following code?

<?php
$arr = array(«foo»,
«bar»,
«baz»);
for ($i = 0; $i < count($arr); $i++) {
$item = $arr[$i];
}
echo «<pre>»;
print_r($item);
echo «</pre>»;
?>

Answers:

• Array ( [0] => foo [1] => bar [2] => baz )
• foo
• bar
• baz

35. Which of the following is not a valid php.ini parameter with respect to file uploading?

Answers:

• upload_max_filesize
• allow_url_fopen
• upload_tmp_dir
• post_max_size

36. What is the correct syntax of mail() function in PHP?

Answers:

• mail($to,$subject,$message,$headers)
• mail($from,$to,$subject,$message)
• mail($to,$from,$subject,$message)
• mail($to,$from,$message,$headers)

37. What is the correct PHP command to use to catch any error messages within the code?

Answers:

• set_error(‘set_error’);
• set_error_handler(‘error_handler’);
• set_handler(‘set_handler’);
• set_exception(‘set_exception’);

38. Which of the following is not a valid xdebug configuration setting?

Answers:

• xdebug.var_display_max_depth
• xdebug.var_display_max_children
• xdebug.var_display_max_data
• xdebug.trace

39. What is wrong with the following code?

<?php
curl_setopt($ch, CURLOPT_URL, «http://www.example.com/»);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>

Answers:

• There is nothing wrong with the code.
• The cURL resource $ch has not been created using the curl_init() method.
• The $ch variable needs to be initialized as $ch=null;.
• The code will cause a parse error.

40. What is the difference between die() and exit() in PHP?

Answers:

• die() is an alias for exit().
• exit() is a function, die() is a language construct and cannot be called using variable functions.
• die() accepts a string as its optional parameter which is printed before the application terminates; exit() accepts an integer as its optional parameter which is passed to the operating system as the exit code.
• die() terminates the script immediately, exit() calls shutdown functions and object destructors first.

41. Which of the following will check if a function exists?

Answers:

• function_exists()
• has_function()
• $a = «function to check»; if ($a ()) // then function exists
• None of these

42. Which of the following is not a file-related function in PHP?

Answers:

• fclose
• fopen
• fwrite
• fgets
• fappend

43. Which of the following variable declarations within a class is invalid in PHP?

Answers:

• private $type = ‘moderate’;
• internal $term = 3;
• public $amnt = ‘500’;
• protected $name = ‘Quantas Private Limited’;

44. For the following code:

<?php

function Expenses()
{
    function Salary()
    {
    }

    function Loan()
    {
        function Balance()
        {}
    }
}

?>

Which of the following sequence will run successfully?

Answers:

• Expenses();Salary();Loan();Balance();
• Salary();Expenses();Loan();Balance();
• Expenses();Salary();Balance();Loan();
• Balance();Loan();Salary();Expenses();

45. What enctype is required for file uploads to work?

Answers:

• multipart/form-data
• multipart
• file
• application/octect-stream
• None of these

46. Which one of the following is not an encryption method in PHP?

Answers:

• crypt()
• md5()
• sha1()
• bcrypt()

47. What function should you use to join array elements with a glue string?

Answers:

• join_st
• implode
• connect
• make_array
• None of these

48. What is the string concatenation operator in PHP?

Answers:

• +
• ||
• .
• |||
• None of these

49. Which of the following will store order number (34) in an ‘OrderCookie’?

Answers:

• setcookie(«OrderCookie»,34);
• makeCookie(«OrderCookie»,34);
• Cookie(«OrderCookie»,34);
• OrderCookie(34);

50. What is the correct line to use within the php.ini file, to specify that 128MB would be the maximum amount of memory that a script may use?

Answers:

• memory_limit = 128M
• limit_memory = 128M
• memory_limit: 128M
• limit_memory: 128M

51. What is the best way to change the key without changing the value of a PHP array element?

Answers:

• $arr[$newkey] = $oldkey; unset($arr[$oldkey]);
• $arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]);
• $newkey = $arr[$oldkey]; unset($arr[$oldkey]);
• $arr[$newkey] = $oldkey.GetValue(); unset($arr[$oldkey]);

52. What will be the output of the following code?

<?
echo 5 * 6 / 2 + 2 * 3;
?>

Answers:

• 1
• 20
• 21
• 23
• 34

53. Does PHP 5 support exceptions?

Answers:

• Yes
• No

54. What will be the output of the following code?

<?php
echo 30 * 5 . 7;
?>

Answers:

• 150 . 7
• 1507
• 150.7
• Integers can’t be concatenated.
• An error will be thrown.

55. Which of these is not a valid SimpleXML Parser method?

Answers:

• simplexml_import_dom()
• simplexml_import_sax()
• simplexml_load_file()
• simplexml_load_string()

56. Which of the following environment variables is used to fetch the IP address of the user in a PHP application?

Answers:

• $IP_ADDR
• $REMOTE_ADDR_USER
• $REMOTE_ADDR
• $IP_ADDR_USER

57. Given the following array:

$array = array(0 => ‘blue’, 1 => ‘red’, 2 => ‘green’, 3 => ‘red’);

Which one of the following will print 2?

Answers:

• echo array_search(‘green’, $array);
• echo in_array(‘green’, $array);
• echo array_key_exists(2, $array);
• echo array_search(‘red’,$array);

58. Which of the following will not give the correct date and time in PHP?

Answers:

• date(«Y-m-d H:i:s»)
• date(«y-m-d H:i:s»)
• date(«f, j Y H:i:s»)
• date(«F, j Y H:i:s»)

59. Which of the following is the right MIME to use as a Content Type for JSON data?

Answers:

• text/x-json
• text/javascript
• application/json
• application/x-javascript

60. With what encoding does chr() work?

Answers:

• ASCII
• UTF-8
• UTF-16
• Implementation dependent
• None of these

61. What is the output of the following code?

<?php
echo 0x500;
?>
Answers:

• 500
• 0x500
• 0500
• 1280
• 320

62. Which of the following statements is true about the «new» operator in PHP?

Answers:

• It is used to define a new variable.
• It creates and allocates memory for a new object
• It is used to call the constructor
• The “new” operator does not exist in PHP

63. Which of the following regular expressions can be used to check the validity of an e-mail address?

Answers:

• ^[^@ ]+@[^@ ]+\.[^@ ]+$
• ^[^@ ]+@[^@ ]+.[^@ ]+$
•  $[^@ ]+@[^@ ]+\.[^@ ]+^
•  $[^@ ]+@[^@ ]+.[^@ ]+^

64. Which of the following is not a valid DOM method in PHP?

Answers:

• loadXMLFile()
• loadXML()
• loadHTMLFile()
• loadHTML()

65. What is the fastest way to insert an item $item into the specified position $position of the array $array?

Answers:

• array_insert()
• array_splice()
• array_merge() and array_slice()
• PHP does not have any built-in function that can do this: the source array will have to be copied, and $item inserted in to the required position:
    $n = 0;
    foreach ($array as $key => $val) {
    if ($n == $position) {
    $target[] = $item;
    }
    ++$n;
    $target[$key] = $val;
   }

66. Consider the following 2D array in PHP:

$array = array(array(141,151,161), 2, 3, array(101, 202, 303));

Which of the following will display all values in the array?

Answers:

• function DisplayArray($array) {
foreach ($array as $value) {
if (array_valid($value)) {
DisplayArray($value);
} else {
echo $value. “ ”;
}
}
}
DisplayArray($array);
• function DisplayArray($array) {
for ($array as $value) {
if (valid_array($value)) {
DisplayArray($value);
} else {
echo $value. “ ”;
}
}
}
DisplayArray($array);

• function DisplayArray($array) {
for ($array as $value) {
if (is_array($value)) {
DisplayArray($value);
} else {
echo $value. “ ”;
}
}
}
DisplayArray($array);

• function DisplayArray($array) {
foreach ($array as $value) {
if (is_array($value)) {
DisplayArray($value);
} else {
echo $value “ ”;
}
}
}
DisplayArray($array);

67. Why is it not recommended to use $_REQUEST when handling form submissions in PHP?

Answers:

• It’s difficult to determine whether it is a $_POST or $_GET request.
• $_REQUEST is deprecated
• $_REQUEST includes $_COOKIE by default, and parameters from $_COOKIE with the same name may be overriden with parameters from $_GET or $_POST.
• $_REQUEST does not handle HTTP rquests, it handles database requests.

68. How should a variable be declared in a function, if the value has to be retained over multiple calls?

Answers:

• local
• global
• static
• None of these

69. Which is the best way to automatically deploy a PHP website using git push?

Answers:

• It is not possible.
• You should have two copies on your server. A bare copy, that you can push/pull from, to which you would push your changes to when you are done. Then you would clone this into your web directory and set up a cronjob to update git pull from your web directory every day or couple of days.
• Developing from scratch a custom deployment script to manage all the aspects.
• Copy over your git directory to your web server. On your local copy, modify your .git/config file and add your web server as a remote. On the server, replace .git/hooks/post-update with an existing script to process the rest of the workflow.
Make the script executable.

70. With what encoding does chr () work?

Answers:

a. ASCII
b. UTF-8
c. UTF-16
d. Implementation dependent
e. None of the above

71. Which of the following file modes is used to write into a file at the end of the existing content, and create the file if the file does not exist?

Answers:

• r+
• w+
• a
• x

72. What is the output of the following code?

<?php
function abc()
{
return __FUNCTION__;
}
function xyz()
{
return abc();
}
echo xyz();
?>

Answers:

• abc
• __FUNCTION__
• xyz
• <empty output>

73. Which of the following is the operator with the highest precedence?

Answers:

• +
• instanceof
• new
• =
• None of the above

74. Which function is used to remove the first element of an array?

Answers:

• array_remove_first_element
• array_shift
• array_ltrim
• a[0] = nil
• None of these

75. Which of the following functions output text?

Note: There may be more than one right answer.

Answers:

• echo()
• print()
• println()
• display()

76. What is the best way to load a file that contains necessary functions and classes?

Answers:

• include($filename);
• require($filename);
• include_once($filename);
• require_once($filename);

77. With regard to abstract classes, which of the following statements is false?

Answers:

• Abstract classes are not available in PHP.
• A class with a single abstract method must be declared abstract.
• An abstract class can contain non-abstract methods.
• An abstract method must have a method definition and can have optional empty braces following it.

78. What is the output of the following code?

<?php

function
vec_add (&amp;$a, $b)
{
$a[‘x’] += $b[‘x’];
$a[‘y’] += $b[‘y’];
$a[‘z’] += $b[‘z’];
}

$a = array (x =&gt; 3, y =&gt; 2, z =&gt; 5);
$b = array (x =&gt; 9, y =&gt; 3, z =&gt; -7);

vec_add (&amp;$a, $b);

print_r ($a);

?>

Answers:

• Array
(
[x] =&gt; 9
[y] =&gt; 3
[z] =&gt; -7
)
• Array
(
[x] =&gt; 3
[y] =&gt; 2
[z] =&gt; 5
)
• Array
(
[x] =&gt; 12
[y] =&gt; 5
[z] =&gt; -2
)
• Error
• None of the above

79. Which of the following are not considered as Boolean false?

Answers:

• FALSE
• 0
• «0»
• «FALSE»
• 4
• -4
• NULL

80. Which of the following code snippets has the most appropriate headers to force the browser to download a CSV file?

Answers:

• header(«Content-type: text/csv»);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);
• header(‘Content-Type: application/download’);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);
• header(‘Content-Type: application/csv’);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);
• header(‘Content-Type: application/octet-stream’);
header(«Content-Disposition: attachment; filename=file.csv»);
header(«Pragma: no-cache»);
header(«Expires: 0»);

81.What is the output of the following code?

<?php
echo «<pre>»;
$array = array(«red»,»green»,»blue»);
$last_key = end(array_keys($array));
foreach ($array as $key => $value) {
if ($key == $last_key) {
echo «a<br>»;
} else {
echo «b<br>»;
}
}
?>

Answers:

• b
a
b
• b
a
a
• b
a
a
• b
b
b

82. With regards to the «static» keyword in PHP, which of the following statements is false?

Answers:

• The $this variable can be used inside any static method.
• Static properties may only be initialized using a literal or a constant.
• A property declared as static can not be accessed with an instantiated class object.
• A static variable or method can be accessed without requiring instantiation of the class.

83. What is «empty()»?

Answers:

• A function
• A language construct
• A variable
• A reference
• None of these

84. Which of the following is not a valid cURL parameter in PHP?

Answers:

• CURLOPT_RETURNTRANSFER
• CURLOPT_GET
• CURLOPT_POST
• CURLOPT_POSTFIELDS

85. What is the output of the following code?

<?
$a = 0;
echo ~$a;
?>

Answers:

• -1
• 0
• 1
• 10
• Syntax error

86.When comparing two arrays, what is the difference between «==» and «===»?

Answers:

• «==» compares keys while «===» compares keys and values.
• «===» also compares the order and types of the objects.
• «===» compares the array references.
• They are identical.
• None of these.

87. With the following code, will the word Hello be printed?
<?
//?>Hello

Answers:

• yes
• no

88. Which of the following features are supported in PHP5?
Note: There may be more than one right answer.

Answers:

• Multiple Inheritance
• Embedded Database with SQLite
• Exceptions and Iterators
• Interoperable XML Tools

89. Consider the following statements:
I : while (expr) statement
II : while (expr): statement … endwhile;

Answers:

• I is correct and II is wrong.
• I is wrong and II is correct.
• Both I and II are wrong.
• Both I and II are correct.

90. Which of the following type cast is not correct?

<?php
$fig = 23;
$varb1 = (real) $fig;
$varb2 = (double) $fig;
$varb3 = (decimal) $fig;
$varb4 = (bool) $fig;
?>

Answers:

• real
• double
• decimal
• boolean

91. Which of the following printing construct/function accepts multiple parameters?
Note: There may be more than one right answer.

Answers:

• echo
• print
• printf
• All of these

92. Which of the following is false about cURL?

Answers:

• cURL can be used to send plain text data to a remote server.
• cURL can be used to send both text as well as files using a single request.
• cURL can be used to send files to a remote server.
• Files cannot be sent using cURL.

93. What is the proper definition of stdClass?

Answers:

• stdClass is php’s generic base class, kind of like Object in Java or object in Python
• stdClass is a generic ’empty’ class that’s used when casting other types to objects.
• stdClass is a C++ construct used in the std:: libraries
• stdClass the base class which must be used to create anonymous classes.

94. Which of the following are valid PHP data types?

Answers:

• resource
• null
• boolean
• string
• All of these

95. Which of the following variables are supported by ‘str_replace()’ function?

Answers:

• Integer
• String
• Boolean
• Array

96. Which of the following methods is used to check if an array is associative or numeric?

Answers:

• is_Assoc().
• isAssoc().
• is_assoc()
• None of the above.

97. What will be the output of the following code?

<?php
$xmlFile = «<root><css><element><csstag><title>background-color</title><value>#FFF</value></csstag><csstag><title>color</title><value>#333</value></csstag><csstag><title>font-family</title><value>Verdana, Geneva, sans-serif</value></csstag></element></css></root>»;
$xml = simplexml_load_string($xmlFile);
foreach($xml->css as $css) {
echo (string) $css->element[‘id’].»{«;
foreach($xml->css->element->csstag as $tag) {
$temp = $tag->title.»: «.$tag->value.»;»;
echo $temp;
}
echo «}»;
}
?>

Answers:

• syntax error
• background-color: #FFF;color: #333;font-family: Verdana, Geneva, sans-serif;
• parse error;
• {background-color: #FFF;color: #333;font-family: Verdana, Geneva, sans-serif;}

98. Which of the following statements is incorrect, with regards to inheritance in PHP?

Answers:

• A class can only have a single parent, i.e. it cannot extend more than one class.
• A class can both extend another class as well as implement an interface.
• A class can implement more than one interface.
• A class can extend more than one class.

99. Which of the following is the correct way to convert a variable from a string to an integer?

Answers:

• $number_variable = int_val $string_variable;
• $number_variable = (int_val)$string_variable;
• $number_variable = int($string_variable);
• $number_variable = (int)$string_variable;

100. What is the correct way to read-in multiple values from an array?

Answers:

• $x,$y,$z = array(7,8,9);
• ($x,$y,$z) = array(7,8,9);
• array($x,$y,$z) = array(7,8,9);
• list($x,$y,$z) = array(7,8,9);

101. Which MIME type need to be used to send attachment in mail?

Answers:

• text/html
• text/plain
• application/mixed
• multipart/mixed

102. Which of the following data type can not be directly manipulated by the Client?

Answers:

• Cookie Data
• referrer
• User Agent
• Session data

103. What is the output of the following code?

<?php
$a = 123;
$b = «123»;
if ($a == $b) echo ‘A’;
if ($a === $b) echo ‘B’;
?>

Answers:

• <empty output>
• A
• B
• AB

104. Which of the following will return the complete URL of the requested PHP page?

Answers:

• apache_getenv(«HTTP_HOST»)
• $_SERVER[‘HTTP_HOST’]
• $_SERVER[‘HTTP_HOST’].$_SERVER[‘REQUEST_URI’];
• $_SERVER[‘REQUEST_URI’];

105. Which of the following is false about foreach loop in PHP?

Answers:

• The foreach construct provides an easy way to iterate over arrays.
• foreach works only on arrays and objects.
• foreach loop can be used with a variable of any type.
• foreach does not support the ability to suppress error messages using ‘@’.

106. What is the output of the following code?

<?php
function y($v) {
echo $v;
}
$w = «y»;
$w(«z»);
$w = «x»;
?>

Answers:

• x
• y
• z
• <error>

107. Which of the following statement is correct?

Answers:

• Interfaces can extend more than one interface
• Interfaces can extend only one interface
• Interfaces can inherit a method from different interfaces
• Interfaces can re-declare inherited methods

108. Which of the following is true regarding the str_replace() function in PHP?

Answers:

• It requires a minimum of 2 parameters.
• The first argument is the string or array being searched and replaced.
• The second argument is the the replacement value that replaces found search values.
• It will replace only the first matched string.

109. Which of the following is incorrect way to take a PHP variable named $name and reassign it to a javascript variable var name?

Answers:

• <script>
var name = «<?php echo $name;?>»;
</script>
• <script>
var name =<?php echo $name;?>;
</script>
• <script>
var name = <?php echo json_encode($name);?>;
</script>
• <script>
var name = «<?php echo addslashes($name);?>»;
</script>

110. Which is true about the curl_setopt() API?

Answers:

• PHP does not provide such an API.
• It sets multiple options for a cURL transfer.
• It executes the curl command.
• It sets one option for a cURL transfer.

111. Which of the following is the best way to convert one date format into another; portable for all PHP versions?

Answers:

• $myDateTime = DateTime::createFromFormat(‘Y-m-d’, $dateString);
$newDateString = $myDateTime->format(‘m/d/Y’);
• $old_date = date(‘l, F d y h:i:s’);
$old_date_timestamp = strtotime($old_date);
$new_date = date(‘Y-m-d H:i:s’, $old_date_timestamp);
• implode(‘-‘, array_reverse(explode(‘-‘, $date)));
• $old_date = date(‘y-m-d-h-i-s’);
preg_match_all(‘/(\.+)-(\d+)-(\w+)-(\d+)-(\w+)-(\w+)/’, $old_date, $out);
$out = $out[0];
$time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);
$new_date = date(‘Y-m-d H:i:s’, $time);

112. In mail($param1, $param2, $param3, $param4); the $param2 contains:

Answers:

• The message
• The subject
• The header
• The recipient

113. Which code snippet outputs a random string?

Answers:

• <?php
Function RandomString()
{
$characters = ’0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
$randstring = »;
for ($i = 0; $i < 10; $i++)
{
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring; ?>
• function generateRandomString($length = 10) {
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
$randomString = »;
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) — 1)];
}
return $randomString;
}
• function generateRandomString($length = 15)
{
return substr(sha1(rand()), 0, 0);
}
•function RandomString($length) {
$keys = array_merge(range(0,9), range(‘a’, ‘z’));
for($i=0; $i < $length; $i++) {
$key = $keys[array_rand($keys)];
}
return $key;
}

114. Which is the best approach to parse HTML and extract structured information from it?

Answers:

• Use an existing LibXML based library like DOM or phpQuery.
• String searching and extraction.
• Use an XML parser (as simpleXML) and XPath queries if available.
• Use specific regular expressions.

115. Which of the following is incorrect about empty()?

Answers:

• empty() checks if a variable is empty.
• empty() can check expressions.
• empty() can only check variables.
• empty() returns false if a variable exists and has a non-empty value.

116. Which of the following is incorrect about the Common Gateway Interface (CGI)?

Answers:

• CGI is a standard method for web server software to delegate the generation of web content to executable files.
• CGI is the part of the Web server that can communicate with other programs running on the server.
• A CGI program is any program designed to accept and return data that conforms to the CGI specification. The program can only be written in PHP.
• A CGI program is any program designed to accept and return data that conforms to the CGI specification. The program could be written in any programming language C, Perl, Java etc.

117. What will be the output of the following code?

<?php
$x = 10;
if ($x == 10):
?>
<p>Hi!</p>
<?php else:?>
<p>Bye!</p>
<?php endif; ?>

Answers:

• Hi!
• Bye!
• The code will throw an error, as there is no curly brace after the if statement, and it has a misplaced colon(:).
• The code will throw an error, as there is no curly brace after the else statement, and it has a misplaced colon(:).

118. What is the output of the following code?

<?php
echo «<pre>»;
$array1 = array(
«1»=>»a»,
«2»=>»b»,
«3»=>»c»
);
$array = array_flip($array1);
print_r($array);
echo «</pre>»;
?>

Answers:

• Array
(
[1] => a
[2] => b
[3] => c
)
• Array
(
[a] => 1
[b] => 2
[c] => 3
)
• Array
(
[0] => c
[1] => b
[2] => a
)
• Array
(
[0] => 1
[1] => 2
[2] => 3
)

119. Given a statement
«While sending a long string in PHP mail() a special character (!) is automatically inserted»
Which one of the following is true with respect to above statement?

Answers:

• There is a limit to the number of characters in a line of an email.
• The statement given is false and this never happens.
• This in a well known problem of PHP’s mail() function and can not be solved.
• None of the above.

120. What will be the output of the following code?

<?php
$numbers=array();
$numbers[1] = 1;
$numbers[2] = 2;
$numbers[3] = 3;
$numbers[4] = 4;
$key= array_search(3,$numbers);
unset($numbers[$key]);
print_r($numbers);
?>

Answers:

• Array ( [1] => 1 [2] => 2 [3] => 4 )
• Array ( [1] => 1 [2] => 2 [4] => 4 )
• Array ( [0] => 1 [1] => 2 [2] => 4 )
• Array ( [0] => 1 [2] => 2 [3] => 4 )

121. Which of the following options may be a reason for the error — «Call to undefined function curl_init()»?

Answers:

• cURL is not enabled.
• curl_init() is not a valid API.
• cURL only works on Linux.
• All of these.

122. What is the use of memory_get_peak_usage()?

Answers:

• Returns the available memory on RAM
• Returns the peak of memory allocated by PHP
• Returns the peak of memory allocated by OS
• No such function exist

123. What is true about ini_set(‘memory_limit’,’-1′)?

Answers:

• The script will have no memory limit.
• The script will have 1 MB memory
• The script will have 1 KB memory
• parse error

124. What is the correct way to read the result of a variable dump into a string?

Answers:

• $string = explode($variable);
• $string = print_r($variable);
• $string = serialize($variable);
• $string = var_dump($variable);

125. Which of the following is a possible way to prevent Session Hijacking?

Answers:

• Use enough random input for generating the session ID
• Use HTTPS to protect the session ID during transmission
• Set the cookie with the HttpOnly and Secure attributes to forbid access via JavaScript
• Regenerating the session ID after successful login

126. What is the use of the CDATA section in XML?

Answers:

• CDATA is used to store the content of an XML node.
• CDATA is used to skip invalid characters.
• XML does not have any CDATA section.
• CDATA is used when PHP is used to update the content of an XML file.

127. Which of the following is not a valid PHP debugger?

Answers:

• PHPTracer
• Zend Debugger
• APD
• Xdebug

128. Why simple mail() function should not be used to send bulk mails in PHP?

Answers:

• There is a limit to number of mails can be send using mail() function.
• mail() function can not be used in a loop.
• mail() function opens and closes an SMTP socket for each email, which is not very efficient.
• There is no problem in using mail() function to send bulk mails.

129. Given the following code:-

Class Registry {
private $vars = array();
public function __set($key, $val) {
$this->vars($key) = $val;
}
public function __get($key) {
return $this->vars($key);
}
}
$registry = new Registry;
$registry->foo = “foo”;
echo $registry->foo;

What will be the output of the following code?

Answers:

• fatal error : undefined property foo
• foo
• nothing
• can not access the property foo outside the class Registry

130. Which method is used to sort multidimensional arrays in PHP?

Answers:

• krsort
• rsort
• array_multisort
• usort

131. Suppose after successful login following values are stored in session as per the given code:-
session_start();

$_SESSION[‘logged’] = 1;
$_SESSION[‘id’] = $id;
$_SESSION[‘name’] = $contact_name;
$_SESSION[’email’] = $email;

Now how will you remove the email value from the session?

Answers:

• unset($_SESSION)
• unset($_SESSION[’email’])
• session_destory($_SESSION)
• All of the above.

132. Some databases support the LIMIT clause. It is a method to ensure that:

Answers:

• Only certain rows are deleted in DELETE queries.
• Only a defined subset of rows are read in SELECT queries.
• Only certain users can access the database.

133. Which of the following is false with respect to Bridge pattern in PHP?

Answers:

• Bridge is designed up-front to let the abstraction and the implementation vary independently.
• Decouple an abstraction from its implementation so that the two can vary independently.
• Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy.
• Use bridge when you do not want to share an implementation among multiple objects.

134. You can extend the exception base class, but you can not override any of the preceding methods because they are declared as:

Answers:

• protected
• final
• static
• private

135. Which one of the following is not a valid argument to error_reporting?

Answers:

• E_STRICT
• E_ALL
• E_STRICT
• E_PARSE_ERROR

136. Suppose $var=1;
Which of the following will produce a Boolean value of true?

Answers:

• var_dump(isset($var))
• var_dump(is_null($var))
• var_dump(empty($var))
• var_dump(defined($var))

137. What will be the output of the following code?

<?php
class FormBuilder
{
private $elements = array();
public function label($text) {
$this->elements[] = «<label>$text</label>»;
return $this;
}
public function input($type, $name, $value = ») {
$this->elements[] = «<input type=\»$type\» name=\»$name\» value=\»$value\» />»;
return $this;
}
public function textarea($name, $value = ») {
$this->elements[] = «<textarea name=\»$name\»>$value</textarea>»;
return $this;
}
public function __toString() {
return join(«\n», $this->elements);
}
}
$b = new FormBuilder();
echo $b->label(‘Name’)->input(‘text’, ‘name’)->textarea(‘message’, ‘My message’);

Answers:

• <label>Name</label>
• <label>Name</label>
<input type=»text» name=»name»/>
<textarea name=»message»>My message</textarea>
• <label>Name</label>
<input type=»text» name=»name» value=»» />
<textarea name=»message»>My message</textarea>
• Fatar error on the last line since calling of class methods can not be nested.

138. How to get information from a form that is submitted using the “get” method?

Answers:

• Request.Form;
• $_GET();
• Request.Get;
• $_GET[];

139. Which of the following is the correct way to create an array in PHP?

Answers:

• $animals = array (Cat, Dog, Horse);
• $animals = array (“Cat”, “Dog”, “Horse”);
• $animals = array [Cat, Dog, Horse];
• $animals = “Cat”, “Dog”, “Horse”;

140. Which of the following magic constant of PHP returns function name?

Answers:

• __LINE__
• __FILE__
• __FUNCTION__
• __CLASS__

141. By which delimiters are PHP scripts enclosed?

Answers:

• <script…/script>
• <?php>…</?>
• <?php…?>
• <&>…</&>

142. What of the listed below are correct magic methods?

Answers:

• __construct(), __destruct(), __put(), __post()
• __construct(), __destruct(), __get(), __set()
• __init(), __final(), __get(), __set()
• __init(), __final(), __put(), __post()

143. How do you create a connection to MySQL database in PHP?

Answers:

• mysqliconnect()
• mysqli-connect()
• mysqli_connect()
• sql_connect()

144. Which of the following is used to execute a prepared statement in PHP-MySQL?

Answers:

• mysqli_stmt_execute()
• mysqli_execute_stmt()
• mysqli_query()
• mysqli_stmt_bind_param()

145. What is the output of the following code?

$a = “b”;
$b = 22;
echo $$a + 40

Answers:

• 22
• 40
• 62
• 0

146. How to get client IP address in a PHP script?

Answers:

• $_DOMAIN[‘REMOTE_ADDR’]
• $_SERVER[‘REMOTE_ADDR’]
• $_SERVER[‘REMOTE_IP_ADRESS’]
• $_ENV

147. What is the output of the following code?

try {
$a = 10/0;
echo $a;
} catch (Exception $e) {
echo ‘You cannot divide by ZERO!!’ ;
}

Answers:

• You cannot divide by ZERO!!
• 10
• Warning: Division by zero
• 0

148. What is the output of the following code run using PHP 5.6.0 or higher?

const ONE = 1;
class foo {
const TWO = ONE * 2;
const THREE = ONE + self::TWO;
const SENTENCE = ‘The value of THREE is ’.self::THREE;
}
echo foo::SENTENCE . “\n”;

Answers:

• The value of THREE is 1
• The value of THREE is 12
• The value of THREE is 3
• The value of THREE is 13

149. Which of these are not a valid data type?

Answers:

• String
• Bool
• Char
• Integer
• UInt

150. Pick the correct PHP function to rewind the internal array pointer

Answers:

• last()
• before()
• prev()
• previous()

151. Which of the following is the correct keyword in SQL?

Answers:

• SELECT
• Select
• select
• SeLeCt
• All of the above

152. Which function is used to read a file removing the HTML and PHP tags in it?

Answers:

• fgetss()
• fgets()
• fopen()
• file_strip_tags()

153. Which of the following is the correct way to open the file «sample.txt» as read only?

Answers:

• open(«sample.txt»);
• open(«sample.txt», «read»);
• fopen(«sample.txt», «r+»);
• fopen(«sample.txt», «r»);

154. Which of the following will return true keeping in view the following code?

function validateDate($date, $format = ‘Y-m-d H:i:s’)
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}

Answers:

• validateDate(‘2012-02-30 12:12:12’)
• validateDate(’30/02/2012′, ‘d/m/Y’)
• validateDate(’14:77′, ‘H:i’)
• validateDate(‘2012-02-28 12:12:12’)

155. Which function can be used to determine if a file exists?
Note: There may be more than one right answer.

Answers:

• is_readable()
• file_exists()
• feof()
• is_file_exists()

156. What is the output of the following code?

class foo {
public $bar = <<<‘EOT’
bar
line1
line2
EOT;
public function printbar(){
echo $this->bar;
}
}
$myobj = new foo;
$myobj->printbar();

Answers:

• bar
• bar
line1
line2
• bar line1 line2
• Error

157. Which function is used to delete a file from the server using PHP?

Answers:

• unlink()
• unset()
• delete()
• remove_file()

158. What is the output of the following code?

session_start();
$_SESSION[‘logged_in’] = true;
$_SESSION[‘name’] = ‘Jane’;
$_SESSION[‘level’] = 4;
echo session_encode();

Answers:

• logged_in|b:1;name|s:4:»Jane»;level|i:4;
• Array ( [logged_in] => 1 [name] => Jane [level] => 4
• {«logged_in»:true,»name»:»Jane»,»level»:4}
• You cannot encode session variables.

159. Which of the following PHP predefined constant is not related to Fatal errors?

Answers:

• E_PARSE
• E_CORE_ERROR
• E_ERROR
• E_RECOVERABLE_ERROR

160. What the operator «instanceof» is used for?

Answers:

• to determine how many instances a PHP variable has
• to determine whether a PHP variable is an instantiated object of a certain class
• to make a copy of a PHP variable
• none of all listed above

161. Mysqli::autocommit does not work with which of the following table types?

Answers:

• InnoDB
• BDB
• NDB Cluster
• MyISAM

162. How do you throw an exception in PHP?

Answers:

• throw new Exception(message);
• throw Exception(message);
• throws new Exception(message);
• None of these

163. What is the correct way to add 1 to the $a variable?
Note: There may be more than one right answer.

Answers:

• $a=+1
• $a++
• ++$a
• a++

164. What is the output of the following code?

$sentence = «ThiS iS a SenTEnCe»;
echo ucwords($sentence);

Answers:

• This Is A Sentence
• THIS IS A SENTENCE
• this is a sentence
• ThiS IS A SenTEnCe

165. Which of the following is true when mail() function returns true?

Answers:

• The email is reached to the client’s mail server.
• The local mail server (or the SMTP configured in php.ini) accepted the outgoing email for delivery.
• The local mail server (or the SMTP configured in php.ini) has sent the email.
• None of the above.

166. If you do not want to serialize any of the properties of an object, which PHP function is used to accomplish this task?

Answers:

• unserialize()
• __wakeup
• __sleep

167. What is the problem with the following code?

<?php
$size =$_POST[‘size’];
$query = «SELECT id, name, inserted, size FROM products WHERE size = ‘$size'»;
$result = pg_query($conn, $query);
?>

Answers:

• SQL query syntax is not correct as a result database error will be thrown
• Variable $size is not validated and escaped therefore SQL Injection can be executed
• «pg_query» is not a PHP operator
• $_POST is not correct a Superglobal variable

168. Which of the following statements invoke the exception class?

Answers:

• throws new Exception();
• throw new Exception();
• new Exception();
• new throws Exception();

169. Which directive determines how the session information will be stored?

Answers:

• save_data
• session_save
• session.save_data
• session.save_handler

170. Which Content Type header need to be set to send an HTML mail in PHP?

Answers:

• ‘Content-type: html; charset=iso-8859-1’ . «\r\n»;
• ‘MIME-Version: 1.0’ . «\r\n» — пока это
• ‘Content-type: text/html; charset=iso-8859-1’ . «\r\n»
• ‘Content-type: application/html; charset=iso-8859-1’ . «\r\n»

171. What does the following statement do with respect to the errors that will get displayed?
error_reporting(E_ALL & ~E_NOTICE);

Answers:

• Report all errors
• Report only NOTICE messages
• Report all errors other than NOTICE messages

172. What will be the output of executing the following code?

<?php
class Foo {
private function printName($name) {
print_r($name);
}
}
$a = new Foo();
$a->printName(‘James’);
?>

Answers:

• James
• Fatal error: Call to private method Foo::printName() from context …
• Notice: Undefined variable: a
• Fatal error: Call to undefined method Foo::printName()

173. Which of the following has Object Oriented and Procedural support as well as supports prepared statements?

Answers:

• PDO
• MYSQLi
• MYSQL

174. Which of the following is used to pick one or more random entries out of an array?

Answers:

• array_random()
• array_rand()
• shuffle()
• rand()

175. Which of the following function is used to read the content of a file?

Answers:

• fopen()
• fread()
• filesize()
• file_exists()

176. Which function is used to get the number of arguments passed to the function?

Answers:

• func_num_args()
• $_GET
• func_get_args_num()
• func_get_arg()

177. Which of the following is not a valid keyword with respect to exception handling in PHP?

Answers:

• try
• catch
• throw
• throws

178. What is the output of the following code?

$foo = 10;
$bar = ’10’;
if ($foo === $bar){
echo ‘I ran’;
}

Answers:

• I ran
• Nothing is output
• TRUE
• Error

179. What piece of code would you use to obtain an array of response headers for a given URL, indexed by their respective names?

Answers:

• get_headers($url);
• get_header($url);
• get_headers($url,1);

180. Which of the following is true with respect to Flyweight design pattern in PHP?

Answers:

• All the methods of the class should be private.
• This pattern is used when you need only a small number of instances of same type.
• Using this pattern consumes a lot of memory.
• Instances of a class which are identical are shared in an implementation instead of creating a new instance of that class for every instance.

181. What is true about get_defined_vars() function?

Answers:

• It returns the array of all the defined variables.
• It returns the array of all the defined variables of a function.
• It returns all the $_POST variables only.
• It returns all the $_GET variables only

182. How many elements are in the array created by the following line of code:
$array = array (true => ‘5’, 1 => ‘6’);

Answers:

• 1
• 2
• 3
• 4

183. Which function can convert a comma separated string into an array using a single call?

Answers:

• strtoarray
• explode
• extract
• substr

184. Which is the correct way to profile a PHP function (without relying on 3rd party libraries and/or PHP extensions)?

Answers:

• $start = microtime();
functionToProfile();
$end = microtime();
$duration = $end — start;

• $start = time();
functionToProfile();
$end = time();
$duration = $end — start;

• $start = microtime(true);
functionToProfile();
$end = microtime(true);
$duration = $end — start;

• $start = date(‘U’);
functionToProfile();
$end = date(‘U’);
$duration = $end — start;

185. Which of the following are valid in PHP?
Note: There may be more than one right answer.

Answers:

• $_23
• ${«foobar»}
• &$foo
• $23_foobar
• $foobar

186. What will be the output of the following code?

$time = strtotime (‘2016-01-01’);
echo date (‘d-m-y H:i:s:u’, $time);

Answers:

• 16-01-01 00:00:00:00
• 01-01-16 00:00:00:000000
• 01-01-2016 00:00:00:000000
• 01-01-16 00:00:00:00

187. Which of the following is not related with respect to calculating the size of a file?

Answers:

• filesize()
• cURL
• file_exists()
• stat()

188. After the following query is executed using PHP, which function can be used to count the number of rows returned?
SELECT * from students
Note: There may be more than one right answer.

Answers:

• mysqli_affected_rows()
• mysqli_num_rows()
• mysqli_use_result()
• mysqli_fetch_lengths()

189. Which of the following is not correct with respect to Authentication using CURL?

Answers:

• CURL can be used to authenticate a user.
• CURL can be used to send form data using both GET and POST methods.
• CURL can not be used to authenticate a user as it can only be used to access and read webpage data.
• CURL can be used for HTTP Basic Authentication.

190. Which of the following method of Exception class returns source filename ?

Answers:

• getMessage()
• getCode()
• getFile()
• getLine()

  • Marc J

    All the answers are not provided yet.
    Could you possibly do all the questions ?
    thx

  • Rahul Pal

    Find your own answers dude 😡

  • Mahboob Alam

    Hi Wee Hong Koh,
    I am looking for the answers of PHP upwork test. As i can see your comment they have removed your comment regarding answers, can you please send me the answer or link of blog or website where you have posted all the answer on the email address mab_alam@hotmail.co.uk.
    Many thanks

  • Vicky

    Hi Wee Hong can you please provide me answer sheet for upwork PHP test
    http://upworktestru.com/php-test-2016_upwork_answers_questions/

  • Matt Bell

    No, they are here to sell their service for taking your test. There are many wrong answers in their answers above.

    • Upworktestru

      We just publish here answers that we not check and find on the internet.
      When we pass tests instead of our clients we spend our time, check and prepare each question.
      That is the reason why here are not correct answers.
      We pick and update all questions very often. If you not want to take test with us — you can find answers yourself.

  • Dmitry Sidorov

    I am looking for a someone to pass upwork php test.

  • Антон

    bullshit you are lier