250+ PHP Programming Interview Questions with Answers

PHP Programming Interview questions answers techhyme

This article is geared toward individuals who possess a general understanding of the concepts of working in a web-based development environment, be it Linux/UNIX, Windows, or Mac OS X.

The below mentioned questions that delve into programming with PHP assume no previous knowledge of the language. However, if you have experience with other programming languages, such as ASP (Active Server Pages), JSP (JavaServer Pages), Ruby, or Perl, you will find the going much easier because of your familiarity with such programming elements as variables, control structures, functions, objects, and the like.

Also Read: 3 Ways to Change PHP Configuration Settings and Options

Similarly, if you have worked with other databases, such as Oracle or Microsoft SQL Server, you already possess a solid foundation for working through the MySQL.

The only real requirement is that you already understand static web content creation with HTML. If you are just starting out in the world of web development, you will still be able to use this book, but you should consider working through an HTML tutorial. If you are comfortable creating basic pages, you will be fine.

This article is designed to help you review what you’ve learned and begin putting your knowledge into practice.

Q1 – How do I completely remove a user? The REVOKE command just eliminates the privileges.

Answer – To completely remove a user from the privilege table, you have to issue a specific DELETE query from the user table in the MySQL database.

Q2 – What if I tell my Internet service provider to stop running MySQL as root and it won’t?

Answer – Switch providers. If your Internet service provider doesn’t recognize the risks of running something as important as your database as the root user and doesn’t listen to your request, find another provider.

Q3 – True or false: SSH is a perfectly acceptable method to securely connect to MySQL from a remote host.

Answer – True. SSH encrypts data between hosts and therefore enables you to securely connect to your server.

Q4 – Which three pieces of information does MySQL check each time a request is made?

Answer – Who you are, where you are accessing from, and what actions you’re allowed to perform.

Q5 – What command would you use to grant SELECT, INSERT, and UPDATE privileges to a user named bill on local host to all tables on the billbook database? Also, what piece of information is missing from this statement that is recommended for security purposes?

Answer – The command is as follows:
GRANT SELECT, INSERT, UPDATE
ON billbook.*
TO bill@localhost;

The important missing piece is a password for the user.

Q6 – How can I start a clean build?

Answer – If you need to build a new Apache from source and do not want the result of earlier builds to affect the new one, it is always a good idea to run the make clean command. Doing so takes care of cleaning up any existing binaries, intermediate object files, and so on.

Q7 – Why are per-directory configuration files useful?

Answer – Although per-directory configuration files have an effect on server performance, they can be useful for delegated administration. Because per-directory configuration files are read every time a request is made, there is no need to restart the server when a change is made to the configuration.

You can allow users of your website to make configuration changes on their own without granting them administrator privileges. In this way, they can password-protect sections of their home pages, for example.

Q8 – What do you mean by a valid Server Name directive?

Answer – The DNS system associates IP addresses with domain names. The value of Server Name is returned when the server generates a URL. If you are using a certain domain name, you must make sure that it is included in your DNS system and will be available to clients visiting your site.

Q9 – How can you specify the location where you want to install Apache?

Answer – Linux/UNIX users can use the –prefix option of the configure script. If an existing installation is present at that location, the configuration files are preserved, but the binaries are replaced. On Windows, this location is set in the Installation Wizard.

Q10 – What is the main difference between <location> and <directory> sections?

Answer – Directory sections refer to file system objects; Location sections refer to elements in the address bar of the web page.

Q11 – What is the difference between a restart and a graceful restart?

Answer – During a normal restart, the server is stopped and then started, causing some requests to be lost. A graceful restart allows Apache children to continue to serve their current requests until they can be replaced with children running the new configuration.

Q12 – Which are the best start and end tags to use?

Answer – It is largely a matter of preference. For the sake of portability, the standard tags (<?php ?>) are preferred.

Q13 – What editors should I avoid when creating PHP code?

Answer – Do not use word processors that format text for printing (Microsoft Word, for example). Even if you save files created using this type of editor in plaintext format, hidden characters are likely to creep into your code.

Q14 – When should I comment my code?

Answer – Again, this is a matter of preference. Some short scripts will be self-explanatory even after a long interval. For scripts of any length or complexity, you should comment your code. Comments in your code often save you time and frustration in the long run

Q15 – From a Linux/UNIX operating system, how would you get help on configuration options (the options that you pass to the configure script in your PHP distribution)?

Answer – You can get help on configuration options by calling the configure script in the PHP distribution folder and passing it the –help argument:

./configure –help

Q16 – What line should you add to the Apache configuration file to ensure that the .php extension is recognized?

Answer – This line ensures that Apache will treat files ending with the .php extension as PHP scripts:

Add Type application/x-httpd-php .php

Q17 – What is PHP’s configuration file called?

Answer – PHP’s configuration file is called php.ini.

Q18 – Can a person browsing your website read the source code of PHP script you have successfully installed?

Answer – No, the user will see only the output of your script.

Q19 – Why is it useful to know the type of data that a variable holds?

Answer – Often the data type of a variable constrains what you can do with it. For example, you cannot perform array-related functions on simple strings.

Similarly, you might want to make sure that a variable contains an integer or a float before using it in a mathematical calculation, even though PHP will often help you by changing data types for you in this situation.

Q20 – Should I obey any conventions when naming variables?

Answer – Your goal should always be to make your code easy to read and understand. A variable such as $ab123245 tells you nothing about its role in your script and invites typos. Keep your variable names short and descriptive.

A variable named $f is unlikely to mean much to you when you return to your code after a month or so. A variable named $filename, however, should make more sense.

Q21 – Should I learn the operator precedence table?

Answer – There is no reason you shouldn’t, but I would save the effort for more useful tasks. By using parentheses in your expressions, you can make your code easy to read while defining your own order of precedence.

Q21 – Which of the following variable names are not valid?
$a_value_submitted_by_a_user
$666666xyz
$xyz666666
$_____counter_____
$the first
$file-name

Answer – The variable name $666666xyz is not valid because it does not begin with a letter or an underscore character. The variable name $the first is not valid because it contains a space. $file-name is also invalid because it contains a nonalphanumeric character (-).

Q22 – What does the following code fragment output?
$num = 33;
(boolean) $num;
echo $num;

Answer – The fragment prints the integer 33. The cast to Boolean produces a converted copy of the value stored in $num. It does not alter the value actually stored there.

Q23 – What does the following statement output?
echo gettype (“4”);

Answer – The statement outputs the string “string”.

Q24 – What is the output from the following code fragment?
$test_val = 5.5466;
settype ($test_val, “integer”);
echo $test_val;

Answer – The code outputs the value 5. When a float is converted to an integer, any information beyond the decimal point is lost.

Q25 – Which of the following statements does not contain an expression?
4;
is_int (44);
5/12;

Answer – They are all expressions because they all resolve to values.

Q26 – In below code, which of the statements contains an operator?
4;
is_int (44);
5/12;

Answer – The statement 5/12; contains a division operator.

Q27 – What value does the following expression return?
5 < 2
What data type will the returned value be?

Answer – The expression resolves to false, which is a Boolean value

Q28 – Must a control structure’s test expression result in a Boolean value?

Answer – Ultimately, yes. But in the context of a test expression, 0, an undefined variable, or an empty string is converted to false. All other values evaluate to true.

Q29 – Must I always surround a code block in a control statement with brackets?

Answer – If the code you want executed as part of a control structure consists of only a single line, you can omit the brackets. However, the habit of always using opening and closing brackets, regardless of structure length, is a good one.

Q30 – How do you use an if statement to print the string “Youth message” to the browser if an integer variable, $age, is between 18 and 35? If $age contains any other value, the string “Generic message” should be printed to the browser.

Answer –

$age = 22;
if (($age >= 18) && ($age <= 35)) {
echo “Youth message”;
} else {
echo “Generic message”;
}

Q31 – How do you extend your code in question 1 to print the string “Child message” if the $age variable is between 1 and 17?

Answer –

$age = 12;
if (($age >= 18) && ($age <= 35)) {
echo “Youth message” ;
} elseif (($age >= 1) && ($age <= 17)) {
echo “Child message” ;
} else {
echo “Generic message” ;
}

Q32 – How do you create a while statement that increments through and prints every odd number between 1 and 49?

Answer – 

$num = 1;
while ($num <= 49) {
echo $num.”<br />”;
$num += 2 ;
}

Q33 – How do you convert the while statement you created in question 3 into a for statement?

Answer –

for ($num = 1; $num <= 49; $num += 2) {
echo $num.”<br />” ;
}

Q34 – Can I include a function call within a double- or single-quoted string, as I can with a variable?

Answer – No. You must call functions outside quotation marks. However, you can break the string apart and place the function call between the parts of the string, using the concatenation operator to tie them together, as follows:

$newstring = “I purchased”.numPurchase ($somenum).” items.”;

Q35 – What happens if I call a function that does not exist, or if I declare a function with a name already in use?

Answer – Calling a function that does not exist or declaring a function with the same name as another existing function causes the script to stop execution. Whether an error message displays in the browser depends on the error settings in your php.ini file.

Q36 – True or false: If a function doesn’t require an argument, you can omit the parentheses in the function call.

Answer – The statement is false. You must always include the parentheses in your function calls, whether or not you are passing arguments to the function.

Q37 – How do you return a value from a function?

Answer – You must use the return keyword.

Q38 – What does the following code fragment print to the browser?
$number = 50;
function tenTimes () {
$number = $number * 10;
}
tenTimes();
echo $number;

Answer – It prints 50. The tenTimes () function has no access to the global $number variable. When it is called, it manipulates its own local $number variable.

Q39 – What does the following code fragment print to the browser?
$number = 50; function tenTimes () {
global $number;
$number = $number * 10 ;
}
tenTimes ();
echo $number;

Answer – It prints 500. This example uses the global statement, which gives the tenTimes () function access to the $number variable.

Q40 – What does the following code fragment print to the browser?
$number = 50;
function tenTimes ( &$n ) {
$n = $n * 10;
}
tenTimes($number );
echo $number;

Answer – It prints 500. By adding the ampersand to the parameter variable $n, you ensure that this argument is passed by reference. $n and $number point to the same value, so any changes to $n are reflected when you access $number.

Q41 – How many dimensions can multidimensional arrays have?

Answer – You can create as many dimensions in your multidimensional array as you can manage, but remember the more dimensions you have, the more you have to manage. If you have data with more than a few dimensions, it might be wise to ask yourself whether that data should be stored differently, such as in a database and accessed that way.

Q42 – If all I’m doing is creating a contact form, why would I care about arrays?

Answer – Arrays are useful in even the most basic client-server interactions, such as a contact form in a website. If your form contains any series of checkboxes or lists from which a user can select more than one option, that data will be sent to your form as an array. You’ll need to get that data out of the array if you want to work with it.

Q43 – What construct can you use to define an array?

Answer – array ()

Q44 – What function would you use to join two arrays?

Answer – Array merge ()

Q45. Why have I seen var instead of public, private, or protected in property declarations?

Answer – In earlier versions of PHP, var was used to declare properties in classes. For backward compatibility, if you use code that still says var in it, it will be treated as public and not cause an error (unless you want it to be a private or protected property).

Q46 – Do I have to understand object-oriented programming to become a good PHP programmer?

Answer – Not at all. Object-oriented programming is an organizational approach intended to improve the reusability and extensibility of the code that makes up a given application.

You might not know enough about your project in the beginning stages of development to fully plan for an object-oriented design. When it is complete or, at least, approaching a solid state you might start to see areas in which an object oriented approach can be taken, and you might start to combine your code into classes, properties, and methods.

But for the most part, you won’t write simple scripts performing particular duties in object-oriented fashion unless it is your background and comes naturally to you.

Q47 – How can you declare a class called empty Class that has no methods or properties?

Answer – Use the class keyword: class empty Class { }

Q48 – How do you choose a name for a constructor method?

Answer – You don’t—a constructor is named for the class in which it resides.

Q49 – If a variable is declared private, where can it be used?

Answer – Variables declared private can only be used in the class itself.

Q50 – Can I combine multiple string functions?

Answer – Yes. You can nest any function, not just string functions. Just remember to count your opening and closing parentheses to ensure that you’ve nested your functions appropriately.

Q51 – What do I do with dates and times stored in my database, not just in my scripts?

Answer – A good rule of thumb is that if you are extracting dates and times from a database and you want to perform date and time-related operations (such as calculating time or converting time from one type to another), you make your database do the work for you. But there’s nothing stopping you from using PHP date and time functions on data extracted out of the database.

Suggested Read: [Programming] List of Important Interview Questions of HTML, CSS, JavaScript, PHP and React

Q52 – What conversion specifier would you use with print () to format an integer as a double? Indicate the full syntax required to convert the integer 33.

Answer – The conversion specifier f is used to format an integer as a double:

print (“%f”, 33);

Q53 – How would you pad the conversion you effected in question 1 with zeros so that the part before the decimal point is four characters long?

Answer – You can pad the output from print () with the padding specifier that is, a space or a zero followed by a number representing the number of characters you want to pad by:

print (“%04f”, 33);

Q54 – How would you specify a precision of two decimal places for the floating-point number you have been formatting in the previous questions?

Answer – The precision specifier consists of a dot (.) followed by a number representing the precision you want to apply. You should place the precision specifier before the conversion specifier:

print (“%04.2f”, 33);

Q55 – What function would you use to extract a substring from a string?

Answer – The substr () function extracts and returns a substring.

Q56 – How might you remove whitespace from the beginning of a string?

Answer – The ltrim () function removes whitespace from the start of a string.

Q57 – How would you break up a delimited string into an array of substrings?

Answer – The explode () function splits up a string into an array.

Q58 – Using PHP, how do you acquire a UNIX timestamp that represents the current date and time?

Answer – Use time ().

Q59 – Which PHP function accepts a timestamp and returns an associative array that represents the given date?

Answer – The getdate () function returns an associative array whose elements contain aspects of the given date.

Q60 – Which PHP function do you use to format date information?

Answer – Use date ().

Q61 – Which PHP function could you use to check the validity of a date?

Answer – You can check a date with the checkdate () function.

Q62 – When I submit other forms online, sometimes I see all the values I entered in the URL leading to the next page. Why is that?

Answer – If you submit a form, such as a Google search, and the next URL you see includes the values that you entered, such as a search for “cheese” that might produce a URL like this: https://www.google.com/#hl=en&output=search&q=cheese

Then what you are seeing is the output of a form that uses a GET action instead of a POST action. In this case, there are at least two fields—one hidden, called “output,” and one that you see, called “q” (for query, presumably). The value of “cheese” is the value you typed in the INPUT field.

Q63 – Why would I need to limit the upload size on a form?

Answer – Without restricting the size of an upload in a form designed to upload files, you can run into the situation of leading users toward an action they can never complete, which could freeze up their system and yours.

Think about the situation when you are looking to accept file uploads of digital images, and a user has created a very large image—let’s say 10 megabytes.

If the intention was to accept only thumbnails of images—something on the order of 350 kilobytes—simply telling the user to adhere to that limit isn’t enough. With a combination of MAX_FILE_SIZE in the form and php.ini settings for upload_max_filesize (among others), you can ensure that a single user’s action won’t clog up the pipes.

Q64 – Which predefined variable do you use to find the name of the script?

Answer – The variable $_SERVER [‘PHP_SELF’] holds the name of the script.

Q65 – Which built-in associative array contains all values submitted as part of a POST request?

Answer – The $_POST super global.

Q66 – Which built-in associative array contains all values submitted as part of a file upload?

Answer – The $_FILES super global.

Q67 – What function do you use to redirect the browser to a new page?

Answer – The header () function, along with a location.

Q68 – What are the five arguments used by the mail () function?

Answer – The recipient, the subject, the message string, additional headers, and additional parameters.

Q69 – On the client side, how do you limit the size of a file that a user can submit via a particular upload form?

Answer – Use a hidden field called MAX_FILE_SIZE in your form

Answers

Q70 – What will happen to my application if users disable cookies?

Answer – Simply put, if your application relies heavily on cookies and users have cookies disabled, your application won’t work. However, you can do your part to warn users that cookies are coming by announcing your intention to use cookies, and also by checking that cookies are enabled before doing anything “important” with your application.

The idea being, of course, that even if users ignore your note that cookies must be turned on in order to use your application, specifically disallowing users to perform an action if your cookie test fails will get their attention!

Q71 – Should I be aware of any pitfalls with session functions?

Answer – The session functions are generally reliable. However, remember that cookies cannot be read across multiple domains. So, if your project uses more than one domain name on the same server (perhaps as part of an e-commerce environment), you might need to consider disabling cookies for sessions by setting the session.use_cookies directive to 0 in the php.ini file.

Q72 – Which function would you use to start or resume a session within a PHP script?

Answer – You can start a session by using the session start () function within your script.

Q73 – Which function can return the current session’s ID?

Answer – You can access the session’s ID by using the session_id () function.

Q74 – How can you end a session and erase all traces of it for future visits?

Answer – The session destroys () function removes all traces of a session for future requests

Q75 – Does the include statement slow down my scripts?

Answer – Because an included file must be opened and parsed by the engine, it adds some overhead. However, the benefits of reusable code libraries often outweigh the relatively low performance overhead.

Q76 – Should I always end script execution if a file cannot be opened for writing or reading?

Answer – You should always allow for this possibility. If your script absolutely depends on the file you want to work with, you might want to use the die() function, writing an informative error message to the browser. In less-critical situations, you still need to allow for the failure, perhaps by adding it to a log file.

Q77 – What functions do you use to add library code to the currently running script?

Answer – You can use the require or include statement to incorporate PHP files into the current document. You could also use include once or require once.

Q78 – What function do you use to find out whether a file is present on your filesystem?

Answer – You can test for the existence of a file with the file exists () function.

Q79 – How do you determine the size of a file?

Answer – The file size () function returns a file’s size in bytes.

Q80 – What function do you use to open a file for reading or writing?

Answer – The fopen () function opens a file. It accepts the path to a file and a character representing the mode. It returns a file resource.

Q81 – What function do you use to read a line of data from a file?

Answer – The fgets () function reads data up to the buffer size you pass it, the end of the line, or the end of the document, whichever comes first.

Q82 – How can you tell when you’ve reached the end of a file?

Answer – The feof () function returns true when the file resource it has passed reaches the end of the file.

Q83 – What function do you use to write a line of data to a file?

Answer – You can write data to a file with the fputs () function.

Q84 – How do you open a directory for reading?

Answer – The opendir () function enables you to open a directory for reading.

Q85 – What function do you use to read the name of a directory item after you’ve opened a directory for reading?

Answer – The readdir () function returns the name of a directory item from an opened directory.

Q86 – Which function do you use to open a pipe to a process?

Answer – The popen () function is used to open a pipe to a process.

Q87 – How can you read data from a process after you have opened a connection? What about writing data?

Answer – You can read and write to and from a process just as you can with an open file, namely with feof () and fgets() for reading and fputs() for writing.

Q88 – How can you escape user input to make it a little safer before passing it to a shell command?

Answer – If user input is part of your shell command, you can use the escapeshellcmd () or escapeshellarg () function to properly escape it.

Q89 – How do I use dynamic data to create the slices of a pie chart?

Answer – When creating any image, the start points and drawing lengths do not need to be statically indicated they can be variables whose values are determined by a database, user input, or calculations within the script.

For example, this code creates a red, filled arc of 90°:

ImageFilledArc($myImage,50,50,100,50,0,90,$red,IMG_ARC_PIE);

You could set this up so that the red-filled arc at the top of the pie holds the percentage of the total for May Sales in a variable called $may_sales_pct. The line then becomes something like this:

ImageFilledArc($myImage,50,50,100,50,0,$may_sales_pct,$red,IMG_ARC_PIE);

The number then is filled in from the calculations or database queries in your script. Be sure to add code to verify that all your arcs add up to 360.

Q90 – What RGB values would you use for pure black and pure white?

Answer – (0, 0, 0) is pure black, and (255,255,255) is pure white.

Q91 – How do you create a new, blank canvas that is 300 pixels wide and 200 pixels tall?

Answer – To create a new, blank canvas that is 300 pixels wide and 200 pixels tall use the following:
$new_image = Image Create (300,200);

Q92 – What function is used to draw a polygon? A filled polygon?

Answer – Image Polygon () and ImageFilledPolygon ()

Q93 – Are there only three normal forms?

Answer – No, there are more than three normal forms. Additional forms are the BoyceCodd normal form, fourth normal form, and fifth normal form/Join-Projection normal form. These forms are not often followed in practical application development because the benefits of doing so are outweighed by the cost in man-hours and database efficiency (but it is certainly fine if you implement them).

Q94 – Name three types of data relationships.

Answer – One-to-one, one-to-many, many-to-many.

Q95 – Because many-to-many relationships are difficult to represent in an efficient database design, what should you do?

Answer – Create a series of one-to-many relationships using intermediary mapping tables.

Q96 – Name a few ways you can create visualizations of data relationships.

Answer – You can use a range of tools, from sticky notes and string (where notes are the tables and string shows the relationships between tables) to software used to draw diagrams, to software programs that interpret your SQL statements and produce visualizations.

Q97 – What characters can I use to name my tables and fields, and what is the character limit?

Answer – The maximum length of database, table, or field names is 64 characters. Any character you can use in a directory name or filename, you can use in database and table names, except / and .. These limitations are in place because MySQL creates directories and files in your file system, which correspond to database and table names. No character limitations (besides length) apply in field names.

Q98 – The integer 56678685 could be which data type(s)?

Answer – MEDIUMINT, INT, or BIGINT.

Q99 – How would you define a field that could contain only the following strings: apple, pear, and banana, cherry?

Answer – ENUM (‘apple’, ‘pear’, ‘banana’, ‘cherry’)
or
SET (‘apple’, ‘pear’, ‘banana’, ‘cherry’)

Q100 – What would be the LIMIT clauses for selecting the first 25 records of a table? Then the next 25?

Answer – LIMIT 0, 25 and LIMIT 25, 25 4.

Q101 – How do you formulate a string comparison using LIKE to match first names of John or Joseph?

Answer – LIKE ‘Jo%’

Q102 – How do you explicitly refer to a field called id in a table called table1?

Answer – Use table1.id instead of id in your query.

Q103 – Write a SQL statement that joins two tables, orders and items_ordered, each of which has a primary key of order_id. From the orders table, select the following fields: order_name and order date. From the items_ordered table, select the item description field.

Answer – SELECT orders. Order_name, orders.order_date, items_ordered.item_description FROM orders LEFT JOIN items_ordered ON orders.order_id = items_ordered.id;

Q104 – Write a SQL query to find the starting position of a substring “grape” in a string “applepearbananagrape”.

Answer – SELECT LOCATE (‘grape’, ‘applepearbananagrape’);

Q105 – Write a query that selects the last five characters from the string “applepearbananagrape”

Answer – SELECT RIGHT (“applepearbananagrape”, 5);

Q106 – Do I have to use transactions all the time now that MySQL supports them?

Answer – No, especially not if the dynamic aspect of your application or site is for dynamic display of data and not for dynamic insertion of data. In addition, if the insertion of data is not necessarily related to any financial- or inventoryrelated actions, you could get away with not using transactions. In other words, if you do not use transactions and an insert or update query fails; be sure that you can live with the failure—either because no money or crucial customer data would be lost

Q107 – True or False: MyISAM is the default and fully transactional storage engine in MySQL.

Answer – False. InnoDB is the default storage engine and supports full transactions.

Q108 – If step two of a three-step transaction fails, what command would you issue?

Answer – ROLLBACK

Q109 – What are two advantages of using stored procedures?

Answer – Better performance and ease of maintenance

Q110 – Is it possible to use both mysql_* and mysqli_* functions in one application?

Answer – If PHP was built with both libraries enabled, you can use either set of functions to talk to MySQL. However, be aware that if you use the mysql_* set of functions with a version of MySQL later than 4.1.3, you cannot access certain new functionality.

In addition, if you are inconsistent with your usage throughout your application, maintenance and upkeep of your application will be time-consuming and produce less-than-optimal results.

Q111 – What is the primary function used to make the connection between PHP and MySQL, and what information is necessary?

Answer – The mysqli_connect () function creates a connection to MySQL and requires the hostname, username, and password.

Q112 – Which PHP function retrieves the text of a MySQL error message?

Answer – The mysqli_error () function returns a MySQL error message.

Q113 – Which PHP function counts the number of records in a resultset?

Answer – The mysqli_num_rows () function counts the number of records in a resultset.

Q114 – How can I ease the burden on my mail server?

Answer – Besides looking into packaged mailing list software, you can bypass the mail () function and talk directly to your SMTP server via a socket connection.

Q115 – Where do bounced messages go?

Answer – As with any email, bounces go to whatever address you specify in your from: or Reply-to: mail headers.

Q116 – Which PHP function sends mail?

Answer – This is not a trick question. It’s the mail() function!

Q117 – What PHP function call causes the script to execute for as long as it needs to run?

Answer – Set_time_limit (0)

Q118 – What do I do if I want to add additional sections to my address book, such as entries for a person’s birthday or other information?

Answer – Different tables are used for address, telephone, fax, email, and personal notes because it is possible for a person to have more than one record containing those types of information.

In the case of a person’s birthday, a person has just one of those, so a relational database is overkill because only one record would ever exist per user. So, to add a person’s birthday you should add a field to the master name table.

In the case of adding tables for other information, ask yourself whether a person will only ever have one instance of that information (such as birthday) or multiple instances (such as email addresses).

If the latter case, create a table much like the address, telephone, fax, email, or personal notes tables, which use master_id as a foreign key.

Q119 – When you are passing a variable through the query string, which super global does it belong in?

Answer – The $_GET super global.

Q220 – How many records in the address, email, telephone, and fax tables can you have for each individual in your master name table?

Answer – As many as you want it’s relational!

Q221 – Through which database field are additional records attached to a master record?

Answer –  The master_id field

Q222 – What if I want multiple forums? This sequence assumes that only one forum is available.

Answer –  If you want to have multiple forums in your discussion board, create a table called forums (or something to that effect) containing fields for an ID, name, and perhaps a forum description.

Then, in the forum topics and forum posts tables, add a field called forum_id so that these elements lower in the hierarchy are tied to the master forum.

Be sure to amend the SQL queries for record insertion to account for the value of the forum_id. Next, instead of starting your display at the topic level, begin it at the forum level. Just as you created a script to display topics, create a script to show the forums.

The link to the forum display would contain the forum_id, and the page itself would show all the topics within that forum.

Q223 – How is the topic ID value passed to the showtopic.php script?

Answer –  Through the $_GET super global, named as the the value of $_GET [‘topic_id’].

Q224 – What else, besides telling the user that the topic was successfully added, could we do at the end of the do addtopic.php script?

Answer –  Just as with the replytopost.php script, we could eliminate the message display and simply redirect the user to the topic she just created, showing the new topic and post in all its glory.

Q225 – Why does the script use the mysqli_real_escape_string () function on values from forms?

Answer –  The mysqli_real_escape_string() function guards against SQL injection attacks by preparing “safe” strings for insertion into the database tables.

Q226 – In the item detail record, you use single filenames in the item image field. What if I want to link to items on a different server?

Answer –  You can enter a URL in the item image field as long as you define the field to hold a long string such as a URL.

Q227 – Which PHP function was used to uppercase the category title strings?

Answer –  Strtoupper ()

Q228 – Why don’t the store_item_size and store_item_color tables contain any unique keys?

Answer –  Presumably, you will have items with more than one color and more than one size. Therefore, item_id is not a unique key. Also, items may have the same colors or sizes, so the item_color and item_size fields must not be primary or unique either.

Q229 – Why do you continue to use mysqli_real_escape_string () on values that will be used in database queries?

Answer –  You should use mysqli_real_escape_string() to ensure values from the user, which will be used in database queries, are safe to use, no matter if you’ve created one script, ten scripts, or one hundred.

Q230 – How can users be sure that an item is in stock when they add it to their cart?

Answer –  If the store items table were modified to contain a field for the current quantity, and when a user completed the checkout sequence that quantity was decreased by the number of items that the user ordered, then in the showitem.php script you could generate a drop-down list that had a maximum selection of the number of items remaining in inventory.

Of course, if you are working with thousands of items in inventory it shouldn’t matter if your drop-down selector only allows the purchase of 10 at a time.

However, for a better user experience you would want the user to be able to add as many to their cart as possible, and in that case you might also add an inventory check before finishing the add-to-cart sequence, and disallow the addition of a quantity greater than the quantity in stock.

Q231 – When removing an item from the cart, why do you suppose that the query validates the session ID of the user against the record?

Answer –  Users should be able to remove only their own items.

Q232 – What would be a reason not to store the price in a hidden field when adding to the cart?

Answer –  If you stored the price in a hidden field, a rogue user could change that value before posting the form (writing whatever price he wanted into the store_shoppertrack table as opposed to the actual price).

Q233 – What would you do to the database and form to handle the need for different shipping and billing addresses?

Answer –  Modify the existing address-related fields in the store_orders table so that it is clear they are either for shipping or billing addresses, then duplicate the set of fields in the table (and give them a name indicating they’re for either shipping or billing—whichever you didn’t use already) and also the form and the eventual INSERT statement.

Q234 – Are there any functions for converting between different calendars?

Answer –  Yes. PHP provides an entire suite of functions that cover alternative calendars.

Q235 – What PHP function did we use to create a timestamp?

Mktime ()

Q236 – What PHP function did we use to create an associative array of date-related information?

Getdate ()

Q237 – Why are the variables in the date_pulldown class declared as public?

Public variables are available outside of the class, as these variables need to be.

Q238 – I have a UNIX system. Can I use /etc/passwd as my user database?

Although using /etc/passwd might seem convenient, it is advisable that you do not use the existing /etc/passwd file for authenticating users of your website. Otherwise, an attacker who gains access to a user of your website will also gain access to the system. Keep separate databases and encourage users to choose different passwords for their system accounts and web access.

Periodically run password checkers that scan for weak passwords and accounts in which the username is also the password.

Q239 – Why am I asked for my password twice in some websites?

Answer – Your browser keeps track of your password so that you do not have to type it for every request. The stored password is based on the realm (AuthName directive) and the hostname of the website. Sometimes you can access a website via different names, such as yourdomain.com and www.yourdomain.com.

If you are authorized to access a certain restricted area of yourdomain.com but are redirected or follow a link to www.yourdomain.com, you will be asked again to provide the username and password because your browser thinks it is a completely different website.

Q240 – Are there any serious security or privacy issues raised by cookies?

Answer – A server can access a cookie set only from its own domain. Although a cookie can be stored on the user’s hard drive, there is no other access to the user’s file system. It is possible, however, to set a cookie in response to a request for an image. So, if many sites include images served from a third-party ad server or counter script, the third party might be able to track a user across multiple domains.

Q241 – What are the advantages of database files over plaintext files for storing user authentication information?

Answer – Database files are much more scalable because they can be indexed, and also clustered for robustness. This means that Apache does not need to read the file sequentially until a match is found for a particular user but rather can jump to the exact location.

Q242 – Can you name some disadvantages of HTTP basic authentication?

Answer – One disadvantage is that the information is transmitted in clear text over the network. This means that unless you are using SSL, it is possible for an attacker to read the packets your browser sends to the server and steal your password.

Another disadvantage is that HTTP authentication does not provide a means for customizing the login (except the real name). It is common for websites to implement custom login mechanisms using HTML forms and cookies.

Q243 – What function is designed to allow you to set a cookie on a visitor’s browser?

Answer – The set cookie () function enables you to set a cookie (although you could also output a Set-Cookie header using the header () function).

Q244 – Why wouldn’t I want to log images?

Answer – In heavily loaded servers, logging can become a bottleneck. If the purpose of logging is to count the number of visitors and analyze their usage of the website, you can achieve this result by logging only the HTML pages, not the images contained in them. This reduces the number of hits stored in the logs and the time spent writing them.

Q245 – How can you avoid logging hits from a client accessing your website from a particular network?

Answer – In some situations, you might want to ignore requests coming from a particular network, such as your own, so that they do not skew the results. You can do this either by post-processing the logs and removing them or by using the SetEnvIf directive:

SetEnvIf Remote_Addr 10\.0\.0\. Intranet
CustomLog logs/access log “%h %l %u %t \”%r\” %> s %b”! Intranet

Q246 – How can you log images to a different file?

Answer – Instead of ignoring images altogether, you can easily log them to a separate file, using the same environment variable mechanism:

SetEnvIf Request_URI “(\.gif|\.jpeg) $” image
CustomLog logs/access_log common env=! Image
CustomLog logs/images log common env=image

Q247 – Why would you want to turn Host Name Lookups off in your Apache configuration?

Answer – Having HostNameLookups on causes extra load on the server because it looks up the IP of the user accessing the site and writes that to the log file.

You can still get the information at a later date by using a hostname resolver when generating usage reports and the server load is then minimized for the user.

Q248 – How do I go about localizing numbers, dates, and currency using PHP?

Answer – Two functions will prove very useful to you in this regard: number format() and date(). You have already learned about the date () function. To use it in a localized environment, you simply rearrange the month, day, and year elements as appropriate to the locale (MM-DD-YYYY, DD-MM-YYYY, and so forth).

The number format () function is used for numbers and currency; it groups the thousandths with a comma, period, or space, as appropriate to the locale.

Q249 – Is English a single-byte or multibyte language? What about Japanese?

Answer – English is single-byte; Japanese is double-byte.

Q250 – What two headers related to character encoding are crucial in a localized site?

Answer – Content-Type with the charset indicator, Content-Language.

Q251 – In addition to text strings, what other content elements need attention when internationalizing a site?

Answer – The formatting of dates, currency, and numbers are other types of content elements that need attention in the internationalization process

Q252 – Why would I use XML to store data when MySQL is a great (and free) database?

Answer – XML can be used not only as a storage method, but also as an intermediary for data transfer. For instance, you might use XML in conjunction with a database, by extracting data and sending it to a third-party function that only interprets XML data.

In addition, although it is true that MySQL is great (and free), some users might not have access to MySQL or any other database, in which case XML files can play the role of a database system.

Q253 – How do I create JSON from arrays and objects created in other parts of my scripts?

Answer – If you want to produce JSON output, you just use the json_encode () function, which takes your existing arrays and objects and puts them into JSON format.

Q254 – What should be the opening line of a valid XML document?

Answer – <? Xml version=”1.0”>

Q255 – Does the following code put your XML content into a new DOM document?
$dom = new DomDocument;

Answer – No, it just creates a DOM document referenced as $dom. To load the content you must also use something like this:
$dom->load (“books.xml”);

Q256 – What code would be used to load the contents of a file called my.xml into a SimpleXML object called $myData?

Answer – $myData = simplexml_load_File (“my.xml”);

Q257 – How can I measure whether my site is fast enough?

Answer – Many developers test their sites locally or over an internal network, but if you run a public website, chances are good that many of your users will access it over slow links. Try navigating your website from a dialup account and make sure that your pages load fast enough; with the rule of thumb being that pages should load in less than three seconds.

Q258 – How can I migrate an existing name-based virtual host to its own machine while maintaining continuous service?

Answer – If a virtual host is destined to move to a neighbouring machine, which by definition cannot have the same IP address, there are some extra measures to take. A common practice is to do something like the following, although many variations on these steps are possible:

  • Set the time-to-live (TTL) of the DNS mapping to a very low number. This increases the frequency of client lookups of the hostname.
  • Configure an IP alias on the old host with the new IP address.
  • Configure the virtual host’s content to be served by both name- and IPaddress-based virtual hosts.
  • After all the requests for the virtual host at the old IP address diminish (due to DNS caches expiring their old lookups), migrate the server.

Q259 – Can I mix IP- and name-based virtual hosting?

Answer – Yes. If multiple IP addresses are bound, you can allocate their usage a number of different ways. A family of name-based virtual hosts might be associated with each; just use a separate NameVirtualHost directive for each IP (if preApache 2.4) or a controlled set of Server Name directives.

One IP might be dedicated as an IP-based virtual host for SSL, for instance, whereas another might be dedicated to a family of name-based virtual hosts.

Q260 – Name some Apache settings that might affect Apache performance.

Answer – Some of the Apache settings that might affect performance include FollowSymLinks, SymLinksIfOwnerMatch arguments to the Options directive, enabling per-directory configuration files, hostname lookups, having a scoreboard file, and statistics collection with mod status.

Q261 – Name some operating system settings that might limit scalability and performance.

Answer – Some operating system settings that might affect scalability and performance include limits for number of processes, open file descriptors, and memory allowed per process.

Q262 – Name some approaches to improve performance.

Answer – The following are some suggestions for improving performance: load distribution via a hardware load balancer or reverse proxy, data compression, caching, mapping files to memory, and compiling modules statically.

Q263 – Is the Server Name directive necessary in a Virtual Host container?

Answer – The Server Name directive is necessary in a Virtual Host container only when name-based virtual hosts are used. The Host header contents are compared to the contents of the Server Name directive. If a match isn’t satisfied, the Virtual Host containers’ Server Alias directive value(s) are checked for matches.

Q264 – Can I use SSL with other protocols?

Answer – The mod_ssl module implements the SSL protocol as a filter. Other protocols using the same Apache server can easily take advantage of the SSL.

Q265 – Name three requirements to carry on secure communications on the Internet.

Answer – Confidentiality, integrity, and authentication.

Q266 – How do you start an SSL-enabled instance of Apache?

Answer – Ensure that the httpd-ssl.conf file is included via a directive in the httpd.conf file, and issue the command apachectl start. As long as the httpd-ssl.conf file is included, any SSL-enabled instances will start along with non-SSL instances.

Q267 – Can MySQL take advantage of multiple CPUs in a single server?

Answer – Absolutely. If your operating system supports multiple CPUs, MySQL takes advantage of them. However, the performance and tuning of MySQL using multiple processors varies, depending on the operating system.

Q268 – What permission level must I have to use the OPTIMIZE command?

Answer – Any user with INSERT privileges for a table can perform OPTIMIZES commands. If a user has only SELECT permissions, the OPTIMIZE command will not execute.

Q269 – Which MySQL function enables you to run an expression many times over to find the speed of the iterations?

Answer – The benchmark () function

Q270 – Which SQL command cleans up the structure of your tables?

Answer – OPTIMIZE

Q271 – Which FLUSH command resets the MySQL log files?

Answer – FLUSH LOGS

Q272 – To quickly determine whether MySQL has support for InnoDB tables, would you use SHOW STATUS or SHOW VARIABLES?

Answer – SHOW VARIABLES

Q273 – Write a SQL statement that enables you to see the SQL statement used to create a table called myTable.

Answer – SHOW CREATE TABLE myTable

Q274 – How would you refer to software in which the major version is 3, the minor version is 4, and the revision is 14?

Answer – The full version number would be 3.4.14.

Q275 – What is considered the primary reason for upgrading to a new minor version of any software?

Answer – Security issues that have been found and fixed by the developers.

Q276 – What command cleans up previous makefiles and cached settings?

Answer – The make clean command

Q277 – What are some of the benefits of using an application framework?

Answer – Working with a stable codebase, adhering to a software architecture pattern, and not reinventing the wheel.

Q278 – In the MVC pattern, what does the model do?

Answer – The model stores and separates data from the controlling and viewing components.

Q279 – Do you have to use an application framework?

Answer – Not at all. In fact, nothing in this book which covers fundamental aspects of developing with PHP and MySQL—relies on a framework.

Other Useful Articles:

Leave a Reply