PHP interview questions

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

How can we get the IP address of the client?

$_SERVER["REMOTE_ADDR"];

Suppose that you have to implement a class named Dragonball. This class must have an attribute named ballCount (which starts from 0) and a method iFoundaBall. When iFoundaBall is called, ballCount is increased by one. If the value of ballCount is equal to seven, then the message You can ask your wish is printed, and ballCount is reset to 0. How would you implement this class?

<?php class dragonBall{ private $ballCount; public function __construct(){ $this->ballCount=0; } public function iFoundaBall(){ $this->ballCount++; if($this->ballCount===7){ echo "You can ask for your wish."; $this->ballCount=0; } } } ?>

The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?

<?php echo array_sum(explode(',', $input)); ?>

Suppose you receive a form submitted by a post to subscribe to a newsletter. This form has only one field, an input text field named email. How would you validate whether the field is empty? Print a message "The email cannot be empty" in this case.

<?php if(empty($_POST['email'])){ echo "The email cannot be empty"; } ?>

What are the __construct() and __destruct() methods in a PHP class?

All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it's used to initialize class properties. The Destructor method takes no parameters.

How can you enable error reporting in PHP?

Check if "display_errors" is equal "on" in the php.ini or declare "ini_set('display_errors', 1)" in your script. Then, include "error_reporting(E_ALL)" in your code to display all types of error messages during the script execution.

What is the difference between GET and POST?

GET displays the submitted data as part of the URL, during POST this information is not shown as it's encoded in the request. GET can handle a maximum of 2048 characters, POST has no such restrictions. GET allows only ASCII data, POST has no restrictions, binary data are also allowed. Normally GET is used to retrieve data while POST to insert and update.

What are getters and setters and why are they important?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer. Within a getter or setter one is able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user's name. If a setter is not being used and the developer is just declaring the $userName variable by hand, you could end up with results as such: "kevin", "KEVIN", "KeViN", "", etc. With a setter, the developer can not only adjust the value, for example, ucfirst($userName), but can also handle situations where the data is not valid such as the example where "" is passed. The same applies to a getter - when the data is being returned, it can be modifyed the results to include strtoupper($userName) for proper formatting further up the chain.

What are PHP sessions and how do they work?

It either creates or resumes a session based on an identifier that is sent to the server via a GET or POST request or a cookie. The most common use case scenario on the web is when a website won't let you comment or post without first prompting a login. How does it know whether you're logged in? One way would be to place a cookie in the user's browser; on every request the cookie is sent server-side, where PHP can be used to determine which information is sent back and displayed to the client. While session_start() saves session data in files by default, it is also possible to store sessions directly in the database.

What does MVC stand for and what does each component do?

MVC stands for Model View Controller. The controller handles data passed to it by the view and also passes data to the view. It's responsible for interpretation of the data sent by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller. The model's job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results. The view is passed data by the controller and is displayed to the user.

What are SQL Injections, how do you prevent them and what are the best practices?

SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server. To prevent SQL injections, one should always check & escape all user input. In PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is often forgotten by inexperienced developers. But there are also many other ways that users can manipulate variables used in a SQL query through cookies or even uploaded files (filenames). The only real protection is to use prepared statements everywhere consistently. Do not use any of the mysql_* functions which have been deprecated since PHP 5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of the box. mysqli_* are still an option, but there is no real reason nowadays not to use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine or Propel to get rid of writing SQL queries all together and use object-relational mapping which binds rows from the database to objects in the application.

How does one prevent the following Warning 'Warning: Cannot modify header information - headers already sent' and why does it occur in the first place?

The candidate should not output anything to the browser before using code that modifies the HTTP headers. Once the developer calls echo or any other code that clears the buffer, the developer can no longer set cookies or headers. That is also true for error messages, so if an error happens before using the header command and the INI directive display_errors is set, then that will also cause that error to show.

How we can get the number of elements in an array?

The count() function is used to return the number of elements in an array.

What's the difference between the include() and require() functions?

They both include a specific file but on require the process exits with a fatal error if the file can't be included, while include statement may still pass and jump to the next step in the execution.

What are traits?

Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.

What's the difference between unset() and unlink()

unset() sets a variable to "undefined" while unlink() deletes a file we pass to it from the file system.

What are the 3 scope levels available in PHP and how would you define them?

Private - Visible only in its own class Public - Visible to any other code accessing the class Protected - Visible only to classes parent(s) and classes that extend the current class

Can the value of a constant change during the script's execution?

No, the value of a constant cannot be changed once it's declared during the PHP execution.

Can you extend a Final defined class?

No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.

What are the main error types in PHP and how do they differ?

Notices - Simple, non-critical errors that are occurred during the script execution. An example of a Notice would be accessing an undefined variable. Warnings - more important errors than Notices, however the scripts continue the execution. An example would be include() a file that does not exist. Fatal - this type of error causes a termination of the script execution when it occurs. An example of a Fatal error would be accessing a property of a non-existent object or require() a non-existent file.


Ensembles d'études connexes

Chapter 2: Evidence Based Dental Hygiene Practice

View Set

Los países - Datos interesantes 2023

View Set

Chapter 12: Spatial Orientation and the Vestibular System

View Set

HWST 107 - Final Exam Study Guide

View Set

Ch. 17 (DT w/ Aminoglycosides & Fluoroquinolones)

View Set

Digital Marketing - Search Engine Optimization

View Set