PHP INTERVIEW QUESTIONS-4

Posted: March 19, 2012 in Uncategorized
    1. How to Generate Random Numbers using php?

You can generate Random Numbers using php: follow the code.

<? srand(time()); $random = (rand()%9); print("random number between 0 and 9 is: $random"); ?> 
    1. How to send Mail Using PHP to send mail?

Let’s get interactive with surfers again. I’d like to create a form mail system in PHP. First we need to create a form in HTML to gather the information. I am going to use one similar to my Perl http://www.tdscripts.com/formmailer.html, because it looks clean.

form action=”send_email.php3″ method=”POST”>

The $to variable will be defined in the send_mail.php3 script to point to my email address (you’ll see the php code momentarily), of course. I also prefill the subject with the words “diary entry suggestion” which visitors can change to something else, if they want:

<input type=”text” size=”22″ name=”subject” value=”diary entry suggestion”>

Ok, let’s take a look at the code to mail the contents of the above form to me and if the process is successful it will redirect you right back to this page. In order for this code to work you will need to know the path to sendmail on your server.

<? $to = "webmaster@php-scripts.com"; $from_header = "From: $from"; if($contents != "") { //send mail - $subject & $contents come from surfer input mail($to, $subject, $contents, $from_header); // redirect back to url visitor came from header("Location: $HTTP_REFERER"); } else { print("<HTML><BODY>Error, no comments were submitted!"); print("</BODY></HTML>"); } ?> 

Notes: I make sure there are some comments submitted or else show an error message by using the != (not equal) with an if statement. When you want to redirect the browser using the header function (like when using the setcookie function) you must do it before any HTML. With the header and $HTTP_REFERER in the code above I am simply sending people who submit the form back where they came from, which should will be this page that calls the form. I could have easily changed the header line to read:

header(“Location: http://www.freshershome.com/thankyou.html&#8221;);

    1. Using Regular Expressions – Validating Email Addresses

Validating email addresses isn’t a perfect science, unfortunately. When you think of all the different possible formats, you have to be pretty broad — maybe too broad — in defining a matching pattern (or regular expression, whatever you prefer to call it). You will find many different regular expressions other programmers have written for validating email addresses so mine certainly isn’t the only one (nor am I egotistical enough to suggest it is the best one), but it is one that works:

// join the mail list?
if ($php_script_list == “yes”)
{
// is the $from email address in valid format?
if(ereg(“([[:alnum:].-]+)(@[[:alnum:].-]+.+)”, $from))

First we make sure the $php_script_list checkbox is checked. Then we check the syntax of the user submitted $from email address. The first portion of the email needs to contain at least one but likely more {alnum} alphanumeric (a-z or 0-9) character or the dash – symbol then there must be the @ symbol followed by at least one, but likely more. Then there is more alphanumeric characters and at least one period mixed in there. That’s what that long somewhat cryptic regular expression means.

abc@123.com would be a valid email
abc@123com woud be an INvalid email (missing period)
1-1@1-1.com would be a valid email
1-2.com would be an INvalid email (missing @)

In regular expressions you enclose ranges within brackets. Thus [a-z] would mean any letter between a-z would return true. [a-c] would only return true if a,b,c was in the comparison string. I encourage you to refer to the php manual and look at the ereg function again.Note that when using ereg function patterns are case sensitive.

int ereg(string pattern, string string, array [regs]);

Use the eregi function in place of ereg for patterns that are case INsensitive. Let’s look at the rest of the mail list code:

if(file_exists("email_list.txt")) { $newfile = fopen("email_list.txt", "r"); while(!feof($newfile)) { $duplicate = fgetss($newfile, 255); // is email address submitted already on file? if(eregi("$from", $duplicate)) { print("<HTML><BODY>This email <strong>$from</strong>"); print(" is already in the database. <br>Please go back"); print(" and uncheck the mail list box</BODY></HTML>"); fclose($newfile); exit; } } fclose($newfile); $addemail = fopen("email_list.txt", "a"); fputs($addemail, "$from\n"); fclose($addemail); } else { // since file doesn't already exist, let's create for first time $newfile = fopen("email_list.txt", "a"); fputs($newfile, "$from\n"); fclose($newfile); chmod("email_list.txt", 0666); }

Start by determining whether the email_list.txt file exists. If it does not exist then this is the very first time someone is being added to the list and we don’t need to bother with checking to see whether their email address is in the list or not. So we only need to create the file and write the email address. You may also notice I used the chmod function to set the file permissions for the email_list.txt file. This line of code is optional. When using the “a”ppend file option, Unix will automatically create the file for the first time and set the permissions. The problem is, depending, on the directory and umask settings it may create a file that only the script has owner permissions to read and write and update. By using the chmod function sometimes can be the only way to gain the permissions you want once a script has set the initial permissions. If you try to FTP a file to a directory and get the “permissions denied” error, you may very well need to write a small PHP script using the chmod command to change the permissions of the file (or simply delete the file, but then you’ll lose the data in it). Ok, but let’s say the email_list.txt file does exist, now the most logical thing to do is make sure we don’t already have that same email address on file.  We do this by reading a line at a time of the existing file and comparing that line (I named the variable $duplicate) against the $from email address and seeing if there is a match.  If there is then we print the message to the browser letting the person submitting the form know that we already have that email address in the database, close the open file, and exit the script. They can go back and uncheck the box and resubmit and the email will go through fine. Now if the email address does not match another email in the database they are appended to the end of the database.

    1. Changing a strings case in PHP
<? // force all uppercase print(strtoupper("i bet this will show up as all letters capitalized<br>")); // force all lowercase print(strtolower("I BET THIS WILL SHOW UP AS ALL LETTERS IN LOWERCASE<br>")); // force the first letter of a string to be capitalized print(ucfirst("i bet this will show the first letter of the string capitalized<br>")); // force the first letter of each WORD in a string to be capitalized print(ucwords("i bet this will show the first letter of every word capitalized<br>")); ?> 
    1. Admin Password gateway using PHP

The HTML for the above form looks like:

<form method="POST" action="example18.php3"> <div align="left"><p><font face="BankGothic Md BT">Admin password?</font> <input type="password" name="pw" size="14"><input type="submit" value="Submit"></p> </div></form> 

Now the php code to check the submitted password versus the hardcoded one is:

<? $adminpass = "test123"; if ($pw == $adminpass) { print("Welcome to the administration area!"); } else { print("Wrong password"); } ?> 

If you try example 18 with password test123 it will let you in, otherwise you’ll get the wrong password message. As you can see it only takes a few lines of code and this will work on NT or Unix. Additionally, you would enclose the contents of the admin area inside the success portion of the if statement. For those using Unix servers, you also have .htacess available which we’ll look at next.

Using .htaccess (UNIX only)

For those who aren’t already familiar with .htaccess it is a server side password protection scheme. By uploading a file named .htaccess into a directory you can protect every file in that directory and beneath that directory from unauthorized use. Here’s a good way to look at the way .htaccess fundamentally works:

yourdomain.com/root        <————– same as typing —>   http://www.yourdomain.com/
yourdomain.com/root/members   <———- upload .htaccess here —> http://www.yourdomain.com/members
yourdomain.com/root/otherdirectory/dir/  <—- UNprotected –> http://www.yourdomain.com/otherdirectory/dir/
yourdomain.com/root/members/otherdirectory/ <—- protected –> http://www.yourdomain.com/members/otherdirectory

The code inside the .htaccess file you would upload would look like this:

AuthName “Name to display”
AuthType Basic
AuthUserFile /home/usr/www/.htpasswd
AuthGroupFile /dev/null
require valid-user

The AuthUserFile should contain the absolute path to this file above. The .htpasswd file will contain the user id and pw combinations to allow into the admin area. The code inside the .htpasswd file (you can name this file anything you want, though) will contain the username and encrypted password combination in the format

username:encrypted_password

Ref: http://interview.freshershome.com

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s