PHP

Multiple sections to prepare our PHP interview. Here we have many questions, answers and information we can read if we simply want to remember something about this amazing technology.

Core PHP questions

What is PHP?

PHP: Hypertext Preprocessor is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

What features would you add to PHP if you could?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eget leo at velit imperdiet varius.

What is the difference between $message and $$message in PHP?

They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains “var”, $$message is the same as $var.

Can you explain, when to use If-else if-else over switch statements?

If there is switching on the value of a single variable then switch is recommended every time. Otherwise, stick with multiple if-else statements. You can use OOP and the inheritance to refactor multiple if statements

When do you use define() and when do you use const. What are the main differences between those two?

PHP 5.3 there are two ways to define constants: Either using the const keyword or using the define() function:

const FOO = 'BAR';

define('FOO', 'BAR');

The fundamental difference between those two ways is that const defines constants at compile time, whereas define() defines them at runtime. As const are language constructs and defined at compile time they are a bit faster than define().

What is the use of isset in PHP?

isset() function. The isset () function is used to check whether a variable is set or not. If a variable is already unset with unset() function, it will no longer be set. The isset() function return false if testing variable contains a NULL value.

What is an array in PHP?

Arrays – An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

How you can delete an element from a PHP array?

If we want to delete just one array element you can use unset() method or alternative array_splice() method. Also if you have the value and don't know the key to delete the element you can use array_search() method to get the key.

What is the difference between require and include in PHP?

Require and include functions does the same task i.e. includes and evaluates specified file, but the difference is require will cause a fatal error when the specified file location is invalid or for any error where as include will generate a warning and continue the code execution.

What is the use of Include_once in PHP?

The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE.

What is urlencode and urldecode in PHP?

urlencode(string) — This PHP function is encodes a string to be used in a query part of a URL. URL encoding is used when placing text in a query string to avoid it being confused with the URL itself. It is normally used when the browser sends form data to a web server.
urldecode(string) – This PHP function id decodes any encoded value in the given string.

How to get IP address of a server in PHP?

Try $_SERVER['SERVER_ADDR'] . It will be the IP address that the server is listening on. You can use DNS functions (e.g., gethostbyaddr() ) to get the host name.

What are the most common errors in PHP?

  • Notices: By default, these errors don't seem to be flaunted to the user the least bit – though you'll be able to modify this default behavior. These include non-critical trivial errors. For example, accessing a variable that has not yet been outlined
  • Warnings: By default, these errors are visible to the user, however, they are doing not lead to script termination.These include a lot of serious errors. For example, making an attempt to include () a file that does not exist
  • Fatal Errors: These errors cause the termination of the script immediately, and PHP's default behavior is to show them to the user. These include critical errors

PHP Error Constants and their descriptions

  • E_ERROR: A fatal error that causes script termination
  • E_WARNING: Run-time warning that does not cause script termination
  • E_PARSE: Compile time parse error
  • E_NOTICE: Run time notice caused due to error in code
  • E_CORE_ERROR: Fatal errors that occur during PHP's initial startup (installation)
  • E_CORE_WARNING: Warnings that occur during PHP's initial startup
  • E_COMPILE_ERROR: Fatal compile-time errors indication problem with script
  • E_USER_ERROR: User-generated error message
  • E_USER_WARNING: User-generated warning message
  • E_USER_NOTICE: User-generated notice message
  • E_STRICT: Run-time notices
  • E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
  • E_ALL: Catches all errors and warnings
  • E_DEPRECATED
  • E_USER_DEPRICATED

What is Exception Handling in PHP?

With PHP 5 came a new object oriented way of dealing with errors. Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.

How do you debug PHP?

Using an IDE, you can set a breakpoint in the line of code you want to debug. Otherwise you can use a tool like XDebug, a PHP extension which provides debugging and profiling capabilities. It uses the DBGp debugging protocol.

What is Chrome logger?

Chrome Logger is a Google Chrome extension for debugging server side applications in the Chrome console. Most languages include their own logging capabilities, but sometimes it is easier to see your logs right in the browser. Chrome Logger used to be known as ChromePHP.

What is the way to get the Information about the uploaded file in the receiving script?

Once the web application server receives the file after uploading, it calls the PHP script to process it. This receiving PHP script will get the data of the uploaded file exploitation the predefined array known as $_FILES. PHP arranges this data in $_FILES as a two-dimensional array. We will retrieve it as follows:
  • $_FILES[$fieldName]['name'] – It represents the file name on the browser system.
  • $_FILES[$fieldName]['size'] – It represents the scale of the go in bytes.
  • $_FILES[$fieldName]['tmp_name'] – It offers the temporary computer file name with that the uploaded file got hold on on the server
  • $_FILES[$fieldName]['error'] – It returns the error code related to this file transfer.
  • The $fieldName is that the name utilized in the <input type=”file” name=”<?php echo $fieldName; ?>”>

What is the use of callback in PHP?

PHP callback are functions that may be called dynamically by PHP. They are used by native functions such as array_map, usort, preg_replace_callback, etc. Here is a reminder of the various ways to create a callback function in PHP, and use it with the native functions.

What is a lambda function in PHP?

A lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a lambda function that is aware of its surrounding context.

What is the use of magic function in PHP?

PHP provides a number of "magic" methods that allow you to do some pretty neat tricks in object oriented programming. These methods, identified by a two underscore prefix (__), function as interceptors that are automatically called when certain conditions are met.

What are soundex() and metaphone() functions in PHP?

soundex and metaphone can be used to find strings that sound similar when pronounced out loud.
  • soundex() function calculates the soundex key of a string. A soundex key is a four character long alphanumeric strings that represents English pronunciation of a word.
  • the metaphone() function calculates the metaphone key of a string. A metaphone key represents how a string sounds if pronounced by an English person.

What is PSR in PHP?

The PHP Standard Recommendation (PSR) is a PHP specification published by the PHP Framework Interop Group. Similar to Java Specification Request for Java, it serves the standardization of programming concepts in PHP.

PHP 7

What is PHP7?

PHP7 is the latest release in the PHP Programming language that has widened several programming avenues for PHP coders. It is considered to be the most sought-after programing language that has completely revamped the way web applications are created and developed. Released in December 2015, it offers faster performance, reduced memory consumption, anonymous class options, etc. After PHP5, it is the most important version to date.

What are the new features of PHP 7?

Among the features of PHP 7 there are:
  • Scalar type hints
  • Return type declarations
  • Anonymous classes
  • The Closure::call() method
  • Generator delegation
  • Generator return expressions
  • The null coalesce operator
  • The space ship operator
  • Throwables
  • Level support for the dirname() function
  • The Integer division function
  • Uniform variable syntax

Web servers

What is the difference between Apache and Tomcat?

Apache Tomcat is used to deploy your Java Servlets and JSPs. So in your Java project you can build your WAR (short for Web ARchive) file, and just drop it in the deploy directory in Tomcat. So basically Apache is an HTTP Server, serving HTTP. Tomcat is a Servlet and JSP Server serving Java technologies.

What is Nginx and what is it used for?

NGINX (Pronounced as Engine-X) is an open source, lightweight, high-performance web server or proxy server. Nginx used as reverse proxy server for HTTP, HTTPS, SMTP, IMAP, POP3 protocols, on the other hand, it is also used for servers load balancing and HTTP Cache.

Which is the best Web server?

There are different web servers available for different technologies.
  • LAMP: Linux, Apache, MySQL and PHP.
  • WIMP: Windows, IIS, MySQL/MS SQL Server and PHP.
  • WAMP: Windows, Apache, MySQL/MS SQL Server and PHP.
  • LEMP: Linux, NGINX, MySQL and PHP

What is the difference between Apache vs NIGINX?

The Apache HTTP server and NGINX are the two most popular open source web servers in the world today. The Apache web servers have been in use since 1995. Apache powers more websites than any other product. Because the open-source Apache web server has been available for so many years, and has so many users, lots of modules have been written to expand its functionality.

But Apache slows down under heavy load, because of the need to spawn new processes, thus consuming more computer memory. It also creates new threads that must compete with others for access to memory and CPU. Apache will also refuse new connections when traffic reaches the limit of processes configured by the administrator.

Nginx is an open source web server written to address some of the performance and scalability issues associated with Apache. The product is open source and free, but Nginx offers support if you buy its Nginx Plus version. Nginx is indeed event-based. They call their architecture “event-driven and asynchronous”. Apache relies on processes and threads.

What is .htaccess in PHP?

.htaccess is a configuration file for use on web servers running the Apache Web Server software. When a .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software.

What are advantages of .htaccess?

There are many advantages using .htaccess file in PHP:
  • URL redirecting
  • Managing error pages
  • Password Protection
  • Visitor blocking facilities by IP address
  • Setting Config variable and Environment variable

Object Oriented propgramming

What is overriding in PHP?

Overloading is defining functions that have similar signatures, yet have different parameters. Overriding is only pertinent to derived classes, where the parent class has defined a method and the derived class wishes to override that method. In PHP, you can only overload methods using the magic method __call.

What is encapsulation in PHP?

Encapsulation is an OOP (Object Oriented Programming) concept in PHP. Wrapping some data in single unit is called Encapsulation. Second advantage of encapsulation is you can make the class read only or write only by providing setter or getter method. Capsule is best example of Encapsulation.

What is polymorphism in PHP?

Polymorphism is a long word for a very simple concept. Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface.

What are PHP Traits?

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

What is the difference between php traits vs interfaces?

The main difference is that, with interfaces, you must define the actual implementation of each method within each class that implements said interface, so you can have many classes implement the same interface but with different behavior, while traits are just chunks of code injected in a class.

What is a closure in PHP?

A closure is an object representation of an anonymous function. We can see that the anonymous function in the above code actually returns an object of closure which is assigned to and called using the variable $string. You can say closure is an object oriented way to use anonymous functions.

What is the use of anonymous function in PHP?

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

What is final in PHP?

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

What is stdClass in PHP?

stdClass is a PHP generic empty class and stdClass is used to create the new Object. stdClass is a kind of Object in Java or object in Python but not actually used as universal base class.

What is self in PHP?

In PHP self keyword is used to access static properties and methods.

What is $this?

It is the way to reference an instance of a class from within itself, the same as many other object-oriented languages. $this refers to the class you are in. In PHP, the pseudo-variable $this is available when a method is called from within an object context.

When to use self over $this?

Use $this to refer to the current object. Use self to refer to the current class.

Web generics

When would you use GET versus POST? What are the major differences between the two?

There are many differences. Usally GET is used to retrieve data while POST is used to send data.

Why POST method is used in PHP?

GET can't be used to send binary data, like images or word documents, to the server. The data sent by GET method can be accessed using QUERY_STRING environment variable. The PHP provides $_GET associative array to access all the sent information using GET method. The POST method transfers information via HTTP headers.

What is a session?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests. Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor. Unlike a cookie, the information is not stored on the users computer.

How long does a session last in PHP?

The session will last for 1440 seconds (24 minutes).

What is a Cookie?

"An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data sent from a website and stored on the user's computer by the user's web browser while the user is browsing.", Wikipedia. There are different kinds of cookies for multiple pur
  • Session cookie
  • Persistent cookie
  • Secure cookie
  • Http-only cookie
  • Same-site cookie
  • Third-party cookie
  • Supercookie

How does cookies work in PHP?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

What is the use of session and cookies in PHP?

A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values. Sessions have the capacity to store relatively large data compared to cookies. The session values are automatically deleted when the browser is closed.

Database

What is the use of PHP and MySQL?

PHP is the most popular scripting language for web development. It is free, open source and server-side (the code is executed on the server). MySQL is a Relational Database Management System (RDBMS) that uses Structured Query Language (SQL).

What Is PDO in PHP?

PDO stands for PHP Data Object. It is a group of PHP extensions that give a core PDO class and database, specific drivers. It provides a vendor-neutral, lightweight, data-access abstraction layer.

What is the maximum size of a database in MySQL?

Operating SystemFile-size Limit
Win32 w/ FAT/FAT322GB/4GB
Win32 w/ NTFS 2TB(possibly larger)

What is the maximum size of a table in MySQL?

You are using a MyISAM table and the space required for the table exceeds what is permitted by the internal pointer size. MyISAM permits data and index files to grow up to 256TB by default, but this limit can be changed up to the maximum permissible size of 65,536TB (2567 − 1 bytes).

What is the capacity of MySQL database?

Database Storage Capacity. MySQL is limited by the largest file size that the operating system you run it on can handle (between 4Gb and 256Tb depending on the O/S). With the innoDB table format you can even span multiple files with one table allowing for tables in the database of up to 64Tb.

How many records can be stored in MySQL table?

In InnoDB, with a limit on table size of 64 terabytes and a MySQL row-size limit of 65,535 there can be 1,073,741,824 rows. That would be minimum number of records utilizing maximum row-size limit. However, more records can be added if the row size is smaller.

How many columns can be added in a table in MySQL?

MySQL 5.0 Column Count Limits: There is a hard limit of 4096 columns per table, but the effective maximum may be less for a given table. The exact limit depends on several interacting factors. Every table (regardless of storage engine) has a maximum row size of 65,535 bytes.

What is varchar MySQL?

MySQL 5.0 Column Count Limits: There is a hard limit of 4096 columns per table, but the effective maximum may be less for a given table. The exact limit depends on several interacting factors. Every table (regardless of storage engine) has a maximum row size of 65,535 bytes.

How big is varchar Max?

n defines the string length and can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size is the actual length of the data entered + 2 bytes. The ISO synonyms for varchar are charvarying or charactervarying.

Why triggers are used in MySQL?

The MySQL trigger is a database object that is associated with a table. It will be activated when a defined action is executed for the table. The trigger can be executed when you run one of the following MySQL statements on the table: INSERT, UPDATE and DELETE and it can be invoked before or after the event.

How you improve slow queries?

You can use the EXPLAIN.

What does a delimiter do in MySQL?

Delimiter is the marker for the end of each command you send to the MySQL command line client. delimiter is not only related to triggers, but defining triggers and stored procedures is one strong use case as you wish them to contain semicolons (;) which are otherwise the default delimiter.

What is a definer in MySQL?

All stored programs (procedures, functions, triggers, and events) and views can have a DEFINER attribute that names a MySQL account. If the DEFINER attribute is omitted from a stored program or view definition, the default account is the user who creates the object.

What is the use of limit in MySQL?

Limit Data Selections From a MySQL Database. MySQL provides a LIMIT clause that is used to specify the number of records to return. The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful on large tables. Returning a large number of records can impact on performance.

What is the use of dual table in MySQL?

The DUAL table is a special one-row, one-column table present by default in Oracle and other database installations. In Oracle, the table has a single VARCHAR2(1) column called DUMMY that has a value of 'X'. It is suitable for use in selecting a pseudo column such as SYSDATE or USER.

What is the use of inner join in MySQL?

The MySQL INNER JOIN clause matches rows in one table with rows in other tables and allows you to query rows that contain columns from both tables. The INNER JOIN clause is an optional part of the SELECT statement.

What is the difference between an INNER and OUTER JOIN?

An inner join will only select records where the joined keys are in both specified tables. A left outer join will select all records from the first table, and any records in the second table that match the joined keys.

What is the use of offset in MySQL?

Both MySQL and PostgreSQL support a really cool feature called OFFSET that is usually used with a LIMIT clause. The LIMIT clause is used to limit the number of results returned in a SQL statement.

What is SQL injection?

SQL injection (or a SQL injection attack) occurs when a user provides SQL code as user input for a Web page, and the SQL code is then executed in the database.
SQL injection is an attack technique that exploits a security vulnerability occurring in the database layer of an application . Hackers use injections to obtain unauthorized access to the underlying data, structure, and DBMS. It is one of the most common web application vulnerabilities.

What is Mysql_real_escape_string used for?

In the case of MySQL this means: mysql_real_escape_string() calls MySQL’s library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ‘, ” and \x1a.

What is input sanitization in PHP?

PHP filters are used to validate and sanitize external input. The PHP filter extension has many of the functions needed for checking user input, and is designed to make data validation easier and quicker.

What is the use of Stripslashes in PHP?

Definition and Usage. The stripslashes() function removes backslashes added by the addslashes() function. This function can be used to clean up data retrieved from a database or from an HTML form.

What is the use of Addslashes in PHP?

addslashes( string $str ) Returns a string with backslashes before characters that need to be escaped. These characters are single quote ('), double quote ("), backslash (\) and NULL (the NULL byte).

What is the use of Htmlspecialchars in PHP?

In many PHP legacy products the function htmlspecialchars($string) is used to convert characters like < and > and quotes a.s.o to HTML-entities.

What is the use of Htmlspecialchars in PHP?

In many PHP legacy products the function htmlspecialchars($string) is used to convert characters like < and > and quotes a.s.o to HTML-entities.

What is XSS in PHP?

Cross-Site Scripting (abbreviated as XSS) is a class of security vulnerability whereby an attacker manages to use a website to deliver a potentially malicious JavaScript payload to an end user. XSS vulnerabilities are very common in web applications.