Saturday, August 2, 2008

PHP programs

PHP programs

  1. A simple PHP program to print "Hello, world!

PHP

<?php

echo "Hello, world!";

?>

  1. A PHP program to calculate the factorial of a number.

PHP

<?php

function factorial(int $n) {

    if ($n == 0) {

        return 1;

    } else {

        return $n * factorial($n - 1);

    }

}

 

echo factorial(5); // 120

?>

  1. A PHP program to print the Fibonacci sequence.

PHP

<?php

function fibonacci(int $n) {

    if ($n == 0) {

        return 0;

    } else if ($n == 1) {

        return 1;

    } else {

        return fibonacci($n - 1) + fibonacci($n - 2);

    }

}

 

for ($i = 0; $i <= 10; $i++) {

    echo fibonacci($i) . " ";

}

?>

  1. A PHP program to check if a number is prime.

PHP

<?php

function is_prime(int $n) {

    if ($n < 2) {

        return false;

    } else if ($n == 2) {

        return true;

    } else {

        for ($i = 2; $i < $n; $i++) {

            if ($n % $i == 0) {

                return false;

            }

        }

        return true;

    }

}

 

echo is_prime(17) ? "true" : "false";

?>

  1. A PHP program to generate a random number.

PHP

<?php

function random_number(int $min, int $max) {

    return rand($min, $max);

}

 

echo random_number(1, 100);

?>

  1. A PHP program to read and write a file.

PHP

<?php

$filename = "myfile.txt";

 

$content = "This is the content of my file.";

 

file_put_contents($filename, $content);

 

$read_content = file_get_contents($filename);

 

echo $read_content;

?>

  1. A PHP program to connect to a MySQL database.

PHP

<?php

$host = "localhost";

$dbname = "mydb";

$username = "root";

$password = "";

 

$conn = mysqli_connect($host, $username, $password, $dbname);

 

if ($conn) {

    echo "Connection successful!";

} else {

    echo "Connection failed!";

}

?>

  1. A PHP program to insert a record into a MySQL table.

PHP

<?php

$host = "localhost";

$dbname = "mydb";

$username = "root";

$password = "";

 

$conn = mysqli_connect($host, $username, $password, $dbname);

 

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@example.com');";

 

$result = mysqli_query($conn, $sql);

 

if ($result) {

    echo "Record inserted successfully!";

} else {

    echo "Error inserting record: " . mysqli_error($conn);

}

?>

  1. A PHP program to select records from a MySQL table.

PHP

<?php

$host = "localhost";

$dbname = "mydb";

$username = "root";

$password = "";

 

$conn = mysqli_connect($host, $username, $password, $dbname);

 

$sql = "SELECT * FROM users";

 

$result = mysqli_query($conn, $sql);

 

if ($result) {

    while ($row = mysqli_fetch_assoc($result)) {

        echo $row['name'] . " " . $row['email'] . "<br>";

    }

} else {

    echo "Error selecting records: " . mysqli_error($conn);

}

?

 PHP programs:

  1. A simple PHP program to print "Hello, world!

PHP

<?php

echo "Hello, world!";

?>

  1. A PHP program to calculate the factorial of a number.

PHP

<?php

function factorial(int $n) {

    if ($n == 0) {

        return 1;

    } else {

        return $n * factorial($n - 1);

    }

}

 

echo factorial(5); // 120

?>

  1. A PHP program to print the Fibonacci sequence.

PHP

<?php

function fibonacci(int $n) {

    if ($n == 0) {

        return 0;

    } else if ($n == 1) {

        return 1;

    } else {

        return fibonacci($n - 1) + fibonacci($n - 2);

    }

}

 

for ($i = 0; $i <= 10; $i++) {

    echo fibonacci($i) . " ";

}

?>

  1. A PHP program to check if a number is prime.

PHP

<?php

function is_prime(int $n) {

    if ($n < 2) {

        return false;

    } else if ($n == 2) {

        return true;

    } else {

        for ($i = 2; $i < $n; $i++) {

            if ($n % $i == 0) {

                return false;

            }

        }

        return true;

    }

}

 

echo is_prime(17) ? "true" : "false";

?>

  1. A PHP program to generate a random number.

PHP

<?php

function random_number(int $min, int $max) {

    return rand($min, $max);

}

 

echo random_number(1, 100);

?>

  1. A PHP program to read and write a file.

PHP

<?php

$filename = "myfile.txt";

 

$content = "This is the content of my file.";

 

file_put_contents($filename, $content);

 

$read_content = file_get_contents($filename);

 

echo $read_content;

?>

  1. A PHP program to connect to a MySQL database.

PHP

<?php

$host = "localhost";

$dbname = "mydb";

$username = "root";

$password = "";

 

$conn = mysqli_connect($host, $username, $password, $dbname);

 

if ($conn) {

    echo "Connection successful!";

} else {

    echo "Connection failed!";

}

?>

  1. A PHP program to insert a record into a MySQL table.

PHP

<?php

$host = "localhost";

$dbname = "mydb";

$username = "root";

$password = "";

 

$conn = mysqli_connect($host, $username, $password, $dbname);

 

$sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'johndoe@example.com');";

 

$result = mysqli_query($conn, $sql);

 

if ($result) {

    echo "Record inserted successfully!";

} else {

    echo "Error inserting record: " . mysqli_error($conn);

}

?>

  1. A PHP program to select records from a MySQL table.

PHP

<?php

$host = "localhost";

$dbname = "mydb";

$username = "root";

$password = "";

 

$conn = mysqli_connect($host, $username, $password, $dbname);

 

$sql = "SELECT * FROM users";

 

$result = mysqli_query($conn, $sql);

 

if ($result) {

    while ($row = mysqli_fetch_assoc($result)) {

        echo $row['name'] . " " . $row['email'] . "<br>";

    }

} else {

    echo "Error selecting records: " . mysqli_error($conn);

}

?

 

PHP INTERVIEW QUESTIONS LATEST



Q.1 How does a Web work at a fundamental level ?
Ans. When a typical HTTP client visit a URL through the web browser, the browser sends an HTTP request to the web server. The web server responses to this request with the resource that is desired. When the browser receives this response, it will render the web page.
Q.2 What is the code to instruct PHP to use your own session-handling functions? (For opening, closing, reading, writing, deleting and garbage collection.)
Ans. session_set_save_handler ('myopen', 'myclose', 'myread', 'mywrite', 'mydelete', 'mygarbage') ;
Q.3 In PHP, how is "serialization" of Arrays takes place?
Ans. In PHP, serialization is done by two functions:
1. Serialize () renders the array in a format that can be safely saved to any container (such as a database field or a file) capable of handling textual content.
2. Unserialize() takes a serialized input and rebuilds the array in memory.
Q.4 What will be the following script output?
10, 'test' => 'a test string', 200 ); echo "Sorting in ascending order: \n"; ksort ($array, SORT_STRING); var_dump($array); ?>
Ans. array(3) { [1] => int(10) [2] => int(200) ["test"] => string(13) "a test string" }
Q.5 What is the code to grab the local part of an email address (the part before the @ character)?
Ans. $local_part = substr($email, 0, strpos($email, '@'));
Q.6 What do you understand by Inheritance?
Ans. Inheritance is the capability to derive new classes from existing ones. A derived class inherits the instance variables and methods from the base class(or a "superclass") and could add new instance variables and methods. If the new methods are defined with the same name as those in the base class,the new methods will override those defined in the superclass.
Q.7 What do you understand by Session?
Ans. Session is a mechanism for persisting information between page requests from a particular user.After calling session_start(), data stored in the $_SESSION superglobal will continue to be accessiblein future page requests from a client identified by a cookie, POST variable or GET parameter.
Q.8 What is ternary operator?
Ans. The ternary operator is a shorthand version of an if/then/else statement. Three expressions are grouped as (condition) ? (if-true) : (if-false).If the first expression is true, the second condition will be evaluated;if it is false,the third will be evaluated instead.
Q.9 What is ZEND?
Ans. ZEND is a PHP language engine, named for its co-creators Zeev Suraski and Andi Gutmans,which handles the compilation and execution of PHP scripts as well as management of the PHP API.
Q.10 What is Polymorphism?
Ans. Polymorphism is a property of object inheritance that enables methods of the same name to performdifferent actions through successive generations of a class definition.
Q.11 What do you understand by aggregate functions?
Ans. Aggregate functions are special SQL functions that take the values from multiple rows of data to produce a single result per grouping. Examples of aggregate functions include MIN(), MAX(), COUNT(), SUM(), and AVG().
Q.12 What do you understand by clone?
Ans. Clone creates a copy of an object. In most cases, this simply means copying property values from the original object to the new object; however, cloning may require performing alteration or seperation logic so that the new object does not create a resource conflict. In PHP 4, objects are cloned by default. In PHP 5, objects are implicitly referenced and only cloned by explicit request.
Q.13 What does @ operator do?
Ans. @ is an error control operator which prevents the error from being printed out(but not from occurring):
Q.14 What is the use of "variable variables"?
Ans. It allows to use the value of a variable as the name of a variable. For example: When this script is executed and the interpreter encounters the $$b expression,it first determines thevalue of $b,which is the string a. It then reevaluates the expression with a substituted for $b as $a,thus returning the value of the $a variable. Q.15 What is the use of "variable functions"?
Ans. It allows to use the value of a variable as the name of a function. For example:
function even_number ($x) { echo "$x is even"; }
$n = 13; $a = ($n % 2 ? 'odd_number' : 'even_number'); $a($n);?> At the end of the script,$a will contain either odd_number or even_number. The expression $a($n) will then be evaluated as a call to either odd_number() or even_number().
Q.16 Describe the operation of a cookie ?
Ans. The operation of a cookie is described by the following series of events: 1. Client sends an HTTP request to server. 2. Server sends an HTTP response with Set-Cookie: foo=bar to client. 3. Client sends an HTTP request with Cookie: foo=bar to server. 4. Server sends an HTTP response to client.
Q.17 Explain the use of var_dump ($array)?
Ans. Dumps information about a variable. e.g.

Output:array(1) { [1]=> int(1)}
Q.18 What do you understand by radomizing arrays?
Ans. This means to extract a random value from an array. This can be accomplished by using the array_rand() function, which returns the index of one or more elements picked at random:

In this case as we specified only one element should be returned; therefore we'll receive a single value. (It was 2 in my case, corresponding to the "Nains" element.) If we specified more than one element, the result would be returned as an array of keys.
Q.19 What is the difference between '==' and '===' operators?
Ans. '==' operator tests the equivalence of two entities whereas '===' operator also tests data type.
Q.20 Describe regular expressions and their types?
Ans. Regular expressions(regexps) are the most powerful tools in the string manipulation toolbox.They provide a robust language for specifying patterns in strings and extracting or replacing identified portions of text. Regular expressions in PHP are of two types: PCRE and POSIX. PCRE Regular expressions are so named because they use the Perl Compatible Regular Expression library to provide regexps with the same syntax and semantics as those in Perl. POSIX regular expressions support standard POSIX-extended regular expression syntax. Q.21 What is the Basic PCRE Syntax?
Ans. A regular expression pattern is a string consisting of plain text and pattern metacharacters.The regexps metacharacters define the type and number of characters that can match a particular part of a pattern.The most basic set of metacharacters are the character classes, which allow a pattern to match multiple characters simultaneously.The basic character classes are shown in table: PCRE Base Character Classes
Metacharacter Characters Matched \d Digits 0-9 \D Anything not a digit \w Any alphanumeric character or an underscore (_) \W Anything not an alphanumeric character or an underscore \s Any whitespace (spaces,tabs,newlines) \S Any nonwhitespace character . Any character except for a newline The basic character class metacharacters each match a single character. Thus, to make them useful in patterns, it can be specified how many times they must match with the help of PCRE Enumerators.
Q.22 How PHP handles dates and times?
Ans. PHP handles dates and times in three basic formats:1. UNIX time stamps2. Date arrays3. String- formatted dates Internally PHP stores all its dates as UNIX time stamps, which are defined as the number of seconds since the UNIX epoch, January 1, 1970 00:00:00 UTC.
Q.23 For how long are the PHP date functions guaranteed to work on 32-bit systems?
Ans. On 32-bit systems, the PHP date functions are only guaranteed to work until January 19, 2038.
Q.24 Name the function which will return the current UNIX time stamp?
Ans. time().
Q.25 Write any two functions which will output the current time as 11:26 pm?
Ans. print date('g:i a'); and print strftime('%I:%M %p');
Q.26 What is Mail Transport Agent?
Ans. When email is sent from organization to organization, it is sent from email server to email server. The software that runs on our email server and handles sending and receiving email from around the Internet is called the Mail Transport Agent(MTA). Examples of MTA are:- sendmail- postfix- qmail- Microsoft Exchange- Lotus NotesMail transport agents talk to each other using the SMTP network protocol.
Q.27 What is Simple Mail Transport Protocol?
Ans. The Simple Mail Transport Protocol(SMTP) is the standard network-layer protocol for transmitting an email message across the Internet. Servers normally listen for incoming SMTP connections on port 25.
Q.28 What do you understand by MX Records?
Ans. When an MTA has an email message to send to another MTA, it has to convert the address in the To:, Cc:, or Bcc: line into an IP address. Everything after the @ sign in the address is taken to be the email domain. The email domain is not the real name of a server, it's actually a special kind of DNS alias. To receive email for our email domain we have to add an MX record for that email domain to our DNS server.
Q.29 What is Mail User Agent? Ans. The Mail User Agent(MUA) is the jargon name for an email client.Examples of Mail User Agents are:- Outlook Express- Evolution - KMail- pine- mutt- HotmailA PHP scripts that sends email is also a type of Mail User Agent.
Mail User Agents read email directly from files on disk, via network protocols such as POP3 or IMAP, or via proprietary network protocols(as used by Microsoft Exchange). Mail User Agents normally send their email by connecting to a Mail Transport Agent over the network via the SMTP network protocol.Some UNIX-based Mail User Agents may send their email instead by executing a sendmail wrapper program.When a Mail User Agent connects to an MTA via SMTP to send email, it may use SASL to authenticate the user.
Q.30 What is SASL?
Ans. The Simple Authentication and Security Layer(SASL) is a tried and trusted way to bolt user-Authentication onto existing network protocols. SMTP has been extended (via the SMTP AUTH command) to support SASL.
Q.31 How would you attach a file to an email message?
Ans. To attach a file to an email message, we have to create a multipart MIME message. -Pass these headers as the fourth parameter to mail(): MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="php-12345" Note the boundary on the end of the Content-Type.The boundary is an arbitrary US-ASCII string that tells MUAs when the end of a MIME block has been reached. -The first part of the message string should be a plain text message.Note the boundary marker after the message which tells MIME that we've reached the end of this particular part of the email message. -The second part of the "message string " should be the message itself.We need to add Content-Type and Content-Transfer-Encoding headers to the message, followed by the message itself. We have to put the boundary marker after at the end of each part of the message. -Next come the attachments. Each attachment gets added to the "message" string as well. We need to add Content-Type and Content-Transfer-Encoding headers, and then the attachment. Q.32 How would you attach images for HTML emails? Ans. HTML emails will attampt to download their images and stylesheets from our web server. Because of security and privacy reason, many MUAs will refuse to attempt these downloads.We can add images as attachments to the email, and then point HTML at the attached images.- Change the first Content type of email to be multipart/related.Boundary definition must be included.- When we add an image as an attachment, include this additional header: Content-Location: URL URL is the "URL" that we use inside the tag to include the image. Q.33 How do you open a socket?
Ans. We can create a socket using the fsockopen() and pfsockopen() functions.We tell PHP what type of network transport we want to use by prefixing the transport to the name or IP address of the server we want to connect to. Sockets created using fsockopen() are automatically closed by PHP when our script ends while sockets created using pfsockopen() are persistent.
Q.34 What is SQL Injection?
Ans. It is a form of exploit attack, similar to Command Injection, used against scripts that do not adequately validate or filter user supplied data. When unfiltered and unvalidated data is passed to a SQL query, it can potentially allow a malicious user to execute arbitrary SQL commands enabling him to steal and/or destroy important information.
Q.35 What is the use of database indexing?
Ans. A database index enables our RDBMS to more quickly find data based on identifying fields. For example, if we plan to allow searching by name, creating an index on the name field in our database will yield faster lookup results.
Q.36 What is the use of Debuggers?
Ans. Debugger applications and extensions allow a developer to track the runtime execution of a script highlighting variable values and logic flow. Examples of debugging tools include DBG, APD, and XDebug.
Q.37 Why error logging is required for a site?
Ans. Error logging (usually to a file) allows us as the site maintainer to keep a track on error conditions in our script. At the same time, this hides errors from our users who at best will not know what to do with the messages, or at worst will use those errors to compromise our site.
Q.38 What is MIME Encoding?
Ans. MIME(Multipart Internet Message Extensions) Encoding is originally defined by RFC 1341, it extends basic email encapsulation(which is limited to a single text body section) to allow for an arbitrary number of attachments - each of which may use a distinct content type and encoding.
Q.39 What is Open Basedir?
Ans.The php.ini setting open_basedir is a technique used on many Shared Hosting providers(along with safe_mode) to limit the ability of one user to read another user's files. When This setting is used, any running script is restricted from using fopen() or other filesystem access functions on files that resides outside the directory specified.
Q.40 What is the use of Output buffering?
Ans. Output buffering, controlled by settings in our php.ini or use of the ob_ start () function, causes generated output to be temporary stored in memory. While generally streamlining the output pipeline, this process also enables an executing script to cancel, modify, or inject content even after"output" has already started. This also means that the header() command can be used after contant has been output(normally not allowed).


PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

PHP 5 References

At W3Schools you will find complete references of all PHP functions:its good website to practice.

eLearning and Blackboard

  IT professional, U bring a unique set of skills and expertise that can greatly contribute to the successful development and implementati...