Home 9 Daniel Zacharias 9 11 Intermediate PHP Questions to Ace your Interview (+ Example Code)

11 Intermediate PHP Questions to Ace your Interview (+ Example Code)

Mastering the answers to these questions will surely get you closer to securing the PHP role you’re hoping for. Make sure to learn all the nuances around them to increase your chances! And if you already have these topics covered or are applying to a job that calls for higher PHP seniority, then it’s time to move forward with the third and final installment of our PHP interview series.
Daniel Zacharias

Daniel Zacharias

June 26, 2023
PHP

So, you are a software engineer, have an upcoming PHP technical interview and need some guidance. What do you need to know? What kind of questions will you face? What are some of the aspects you need to focus on to truly ace your interview? While it’s impossible to know before the interview actually happens, there are certain topics that will likely pop up.

That’s why we’ve come up with this series of articles which aims to cover everything related to PHP interviews. We’ve already gone over the most basic stuff. Now it’s time for intermediate questions, perfect for beginners that want to advance their career or for semi-seniors trying to land their next PHP job. 

1. Mastering PHP Functions and Libraries: The Toolbox for Effective PHP Career

Q1: What is a function in PHP? Can you discuss this with examples?

It’s self-explanatory, but PHP functions aren’t your regular run-out-of-mill ones. You see, a PHP function is a self-contained block of code that performs a specific task. But you can also create your own, known as “user-defined functions“. (This will be your Ace of Spades during the interview)

Here’s an example:

function welcomeMessage() {

    echo “Hello, Code Power!”;

}

welcomeMessage(); // Calls the function and outputs: Hello, Code Power!

Don’t forget to describe the purpose of the () and {}, since they are the core part of the function!

Q2: How can external files be included in PHP?

During your PHP career, you’ll perform all kinds of wizardry with files, so it’s important to show two key methods from the get-go. They are “include” and “require“.

Techy HR pays attention to: include” will emit a warning if the file can’t be found, but will continue to execute the rest of the script. Conversely, “require” will cause a fatal error and halt script execution if the file can’t be found or doesn’t exist.

Q3: What are some important PHP string functions?

PHP has an enormous library of built-in strings, but the essential ones most interviewers will hunt for are:

  • strlen() — returns the length of a string
  • str_replace() — replaces some characters in a string with some other characters
  • strpos() — finds the position of the first occurrence of a string inside another string
  • strtolower() — converts a string to lowercase
  • strtoupper() — converts a string to uppercase

Here’s how strings look in action:

echo strlen(“Hello, Code Power!”); // Outputs: 17

echo str_replace(“Hello”, “Goodbye”, “Hello, Code Power!”); // Outputs: Goodbye, Code Power!

echo strpos(“Hello, Code Power!”, “Code”); // Outputs: 7

echo strtolower(“Hello, Code Power!”); // Outputs: hello, code power!

echo strtoupper(“Hello, Code Power!”); // Outputs: HELLO, CODE POWER!

2. Describing database connectivity in PHP – How web development powerhouse works

PHP and databases are my favorite!

A big part of your PHP developer career will involve mastering the connectivity with MySQL, and how the PDO (PHP Data Objects) affects the database access.

TIP: Techy HR loves probing candidates with database questions. It’s the part of the screening where half of the candidates get brain fog and fail the interview. But don’t let this be your case. Gear up with these questions and nail it!

Q1: How does PHP connect with MySQL?

PHP’s main connection with MySQL is through the MySQLi extension or PDO.

Here’s what a basic connection looks like:

$servername = “localhost”;

$username = “username”;

$password = “password”;

$database = “database”; // Create a connection

$conn = new mysqli($servername, $username, $password, $database); // Check the connection

if ($conn->connect_error) {

    die(“Connection failed: ” . $conn->connect_error);

}

echo “Connected successfully”;


Note this: By connecting to a MySQL database, the script runs on the same server (localhost) with the connection to the real MySQL server (that’s done with the MySQL Workbench)

Q2: Could you explain the role of mysqli_connect() function in PHP?

“mysqli_connect()” function in PHP is like the magic key that opens any MySQL door. It’s mostly used for creating new connections to the MySQL server.
 

The function returns an object (think of it as feedback when cracking a lock), which represents the connection to a MySQL server. If the connection fails, the function returns “false“.

What you need to remember is the function takes four parameters:

  1. host: Specifies the host to connect (default is localhost).
  2. username: Specifies the MySQL username.
  3. password: Specifies the MySQL password.
  4. database: Specifies the default database to be used.


Q3: How do you insert, update, and delete a record from the database using PHP? 

Thanks to CRUD (Create, Read, Update, Delete) operations, the Infinity Gauntlet of PHP and SQL commands, and database management are done at the snap of a finger (literally!).

Here’s a simple example for each “snap” using MySQLi:


Inserting a record:

php

$sql = “INSERT INTO Users (firstname, lastname, email) VALUES (‘John’, ‘Doe’, ‘john@example.com’)”;

$conn->query($sql);


Updating a record:


php

$sql = “UPDATE Users SET email=’john.doe@example.com’ WHERE firstname=’John’ AND lastname=’Doe’”;

$conn->query($sql);


Deleting a record:


php

$sql = “DELETE FROM Users WHERE firstname=’John’ AND lastname=’Doe'”;

$conn->query($sql);


Q4: How would you describe PDO in PHP?

This is the hardest one in the whole PHP database section!

PDO (PHP Data Objects) are a simple way of accessing multiple databases without sacrificing security. With PDO, you have a uniform method of access that doesn’t try to rewrite SQL or mask missing features.
 

HR is on the lookout for: In practice, PDO provides an extra layer of security through prepared statements that prevent SQL injection attacks (a crucial part when creating a safe PHP development).

Here’s what it looks like:

try {

    $conn = new PDO(“mysql:host=$servername;dbname=$database”, $username, $password);

    // set the PDO error mode to exception

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    echo “Connected successfully”; 

} catch(PDOException $e) {

    echo “Connection failed: ” . $e->getMessage();

}

3. Securing your PHP applications: Interview tips and tricks to know about

If you passed the basics, well done! The junior PHP developer role is yours for the taking!

But what if climbing the PHP ladder is more your cup of tea? Don’t worry, with this set of questions, that mid level PHP role is yours.

Q1: How would you prevent a SQL Injection in PHP?

 

SQL injections are sneaky little security exploits that can wreak havoc on your website if you’re not careful. 

SQL injection occurs when an attacker slips malicious code into your database with the help of some crafty SQL statements. This leads to all sorts of problems like data theft or data loss. Luckily for us PHP fans, there’s a way to prevent this using prepared statements! These nifty little lines of code ensure that all data is treated as a string and not part of the SQL query. 

So even if an attacker tries to slip in some malicious code, it won’t work! 

If you’re using the PDO extension in PHP (which I highly recommend), then you’ll love how easy it is to implement prepared statements. 

Check out this example:

$stmt = $pdo->prepare(‘SELECT * FROM users WHERE email = ?’);

$stmt->execute([$email]);

$user = $stmt->fetch();

Q2: How would you prevent Cross-Site Scripting (XSS) in PHP?

Experiencing Cross-Site Scripting on your website is like dealing with the damage of a level 9 Earthquake. Catastrophe everywhere.

But don’t panic! 

Your future job as a PHP developer is to create a safer space for all of us. One great solution to fighting XSS is to use functions like htmlspecialchars() or strip_tags() before echoing user-submitted data on our website.

By using these functions, you’re able to effectively neutralize any malicious code the attacker might have dropped in. It’s almost like installing an impenetrable force field for your website!

Here’s what it looks like:

echo htmlspecialchars($user_input, ENT_QUOTES, ‘UTF-8’);

Simple, yet extremely powerful!

Q3: Why are data validation and sanitization in PHP so important?

For all these years of being in the software development world, there wasn’t a single time this question didn’t appear in the interview. It’s a must-ask for 95% of techy HR.

At first look, data validation sounds boring, right? 

But in reality, it’s one of the most important steps in ensuring your apps are running smoothly. And it’s your duty as a future PHP developer to create PHP apps that support clean, correct, and useful data.

Data sanitization is all about cleaning up any input that doesn’t follow the rules you’ve set out. Don’t forget, your greatest asset in this conquest is the filter_var() function! It’s like the all-mighty multi-tool of both data validation and sanitization. 

Here’s how email address validation looks like in practice (and it’s oftentimes the most picked interview test task):

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

  echo(“Email is valid”);

} else {

  echo(“Email is not valid”);

}

Q4: How would you use PHP filters for security purposes?

Here’s where they’ll stress-test your line of thinking and reasoning. 

Think of PHP filters as your very own security guards for any external input. Before any data enters the applications, they ensure it’s spotless and safe to use. 

And trust me, out in the real web dev field, where the threat of common security issues like SQL Injection or XSS attacks is constant, you’ll need all the protection you can get! 

Here’s what it looks like in the practice with string sanitization:

$dirty_string = “<script>alert(‘XSS’);</script>”;

$clean_string = filter_var($dirty_string, FILTER_SANITIZE_STRING);

echo $clean_string;

Here the FILTER_SANITIZE_STRING filter would strip out the HTML tags from the string (note this down, ’cause you’ll be doing this a lot in your PHP career), making it safe to display.

Mastering the answers to these questions will surely get you closer to securing the PHP role you’re hoping for. Make sure to learn all the nuances around them to increase your chances! And if you already have these topics covered or are applying to a job that calls for higher PHP seniority, then it’s time to move forward with the third and final installment of our PHP interview series. 

Get the best of Code Power News in your inbox every week

    You may also like

    Principles and Benefits of Reactive Programming

    Principles and Benefits of Reactive Programming

    Unlike traditional programming, reactive programming revolves around asynchronous data streams. However, code is usually written linearly, one step after another. Reactive programming offers a way for developers to deal with scenarios where events occur unpredictably...

    Get the best of Code Power News in your inbox every week