Tuffest PHP Interview Questions And Answers

Posted by Unknown at 01:42
What Are the Options to Transfer Session IDs?
Once a new session is created, its session ID must be transferred to the client browser and included in the next client request, so that the PHP engine can find the same session created by the same visitor. The PHP engine has two options to transfer the session ID to the client browser:
  • As URL parameter - The Session ID will be embedded in all URLs in the HTML document delivered to the client browser. When the visitor clicks any of those URLs, the session ID will be returned back to the Web server as part of the requesting URL.
  • As a cookie - The session ID will be delivered as a cookie to the client browser. When visitor requests any other pages on the Web server, the session ID will be returned back to the Web server also as a cookie.
The PHP engine is configured to use URL parameters for transferring session IDs by default.

How Session IDs Are Transferred on Your Web Server?
As you know there are two options the PHP engine can use to transfer session IDs to the client browsers. But how to do know which option is your PHP engine is using? The PHP sample script will help you to find out:
<?php
  session_start();
  print("<html><pre>");
  $queryString = $_SERVER["QUERY_STRING"];
  print("Query string of the incoming URL: ".$queryString."\n");
   print("Cookies received:\n");
  foreach ($_COOKIE as $name => $value) {
     print "  $name = $value\n";
  }
  $myLogin = $_SESSION["MyLogin"];
  print("Value of MyLogin has been retrieved: ".$myLogin."\n");
  $myColor = $_SESSION["MyColor"];
  print("Value of MyColor has been retrieved: ".$myColor."\n");
  print("</pre></html>\n");
?>
You need to save this script to your Web server as next_page.php. Now visit first_page.php and click the "Next Page" hyper like, you will get something like this:
Query string of the incoming URL: PHPSESSID=meml483hk4dvm1n2ii8k9hvjj1
Cookies received:
Value of MyLogin has been retrieved: PICKZYCenter
Value of MyColor has been retrieved: Blue
Base on the output, your PHP engine is using URL parameters to transfer session IDs, because you can see the session ID parameter in the query string of the incoming URL, and there is no cookies related to session ID.
Another way to confirm that your PHP engine is using URL parameters to transfer session IDs is to look at the address field of your browser, it will show something like:
http://localhost/next_page.php?PHPSESSID=meml483hk4dvm1n2ii8k9hvjj1

How To Force the PHP Engine to Use Cookies to Transfer Session IDs?
If you want to force your PHP engine to use cookies to transfer session IDs instead of URL parameters, you can open the PHP configuration file, php.ini, and make the following changes:
session.use_cookies = 1
session.use_only_cookies = 1
Now re-run the first_page.php and next_page.php scripts presented in the previous tutorials. You will get something like:
Query string of the incoming URL: 
Cookies received:
  PHPSESSID = r66hq1bcg8o79e5i5gd52p26g3
Value of MyLogin has been retrieved: PICKZYCenter
Value of MyColor has been retrieved: Blue
Base on the output, your PHP engine is using cookies to transfer session IDs now, because you can see the cookie named as PHPSESSID contains the session ID, there is no URL parameters related to session ID.

Is It More Secure to Use Cookies to Transfer Session IDs?
Is it more secure to use cookies to transfer session IDs? The answer is yes, because attacking your Web site using URL parameters is much easier than using cookies.
So if you are the system administrator of your Web server, you should set session.use_only_cookies=1.
If your Web server is provided by a hosting service provider, ask them to set session.use_only_cookies=1.

Where Are the Session Values Stored?
When a value is saved into the current session by one PHP page, the PHP engine must stored this value somewhere on Web server, so that the PHP engine can retrieve it back when same visitor comes back to request another PHP page.
Where are the session values stored on the Web server? The answer depends on the setting named, session.save_path, in the PHP engine configuration file. If session.save_path = "/temp", session values will be stored in special files, one file per session, in the /temp directory on the Web server.
If you re-run the first_page.php and next_page.php scripts presented in the previous tutorials, you can find a special file named like: \temp\sess_r66hq1bcg8o79e5i5gd52p26g3. If you open this file, you will see:
MyLogin|s:9:"PICKZYCenter";MyColor|s:4:"Blue";
Now you know that session values are stored on the Web server as text files, and values are formatted with value names and lengths.

What Is the Timeout Period on Session Values?
The PHP engine has no direct settings on session timeout period. But it has a session garbage collection mechanism that you can set to remove those special files containing session values. There are 3 settings you can use to define the session garbage collection mechanism:
session.gc_probability = 1
session.gc_divisor     = 1000
session.gc_maxlifetime = 1440
The first two settings tell the PHP engine to run the garbage collection process once every 1000 requests received by the Web server. The last setting tells the PHP engine to treat session values as garbage 1440 seconds after they have not been used.
Putting all settings together, your session values probably be removed 1440 seconds after the visitor stopping using your Web site. The probability of this removal is one over 1000 requests received after the 1440-second period.
In another word, if visitor John stopped using your site, and there is no other visitors coming to your site, session values created for John will never be removed. However, if you have a busy site, like 1000 requests per minute, John's session values will be removed about one minute plus 1440 seconds after John stopped using the site.

How To Test the Session Garbage Collection Process?
In order to test the session garbage collection process, you need to change the settings to expire session variables in 10 seconds and run the process on every request:
session.gc_probability = 1
session.gc_divisor     = 1
session.gc_maxlifetime = 10
If you re-run the first_page.php and next_page.php scripts presented in the previous tutorials, you will see some thing like:
Query string of the incoming URL: 
Cookies received:
  PHPSESSID = grm557vicj1edmiikgsa8hbd11
Value of MyLogin has been retrieved: PICKZYCenter
Value of MyColor has been retrieved: Blue
Wait for 10 seconds, and start another browser window to run first_page.php. This is to triger the session garbage collection process to remove values stored in session grm557vicj1edmiikgsa8hbd11.
Go back to the first browser window on second_page.php, and click the browser refresh button, you will get something like:
Query string of the incoming URL: 
Cookies received:
  PHPSESSID = grm557vicj1edmiikgsa8hbd11
Value of MyLogin has been retrieved: 
Value of MyColor has been retrieved: 
As you can see, session values are gone, the browser is still sending the same session ID as a cookie, but the all sesion values are expired (actually, the session file is removed by the garbage collection process).


How To Set session.gc_maxlifetime Properly?
As you know that session.gc_maxlifetime is the session value timeout period. You should set this value based on the usage pattern of your visitors. Here are some suggestions:
# Set it to 20 minutes for a normal Web site:
session.gc_maxlifetime = 1200
 
# Set it to 24 hours if visitors comes to the site many time a day:
# Example: Yahoo email site expires your session in 24 hours.
session.gc_maxlifetime = 86400


How To Set session.gc_divisor Properly?
As you know that session.gc_divisor is the frequency of when the session garbage collection process will be executed. You should set this value based on the income request traffic. Here are some suggestions:
# Set it to 10, if traffic is less than 10,000 per day:
session.gc_divisor = 10
 
# Set it to 100, if traffic is between 10,000 and 100,000 per day:
session.gc_divisor = 100
 
# Set it to 1000, if traffic is greater than 100,000 per day:
session.gc_divisor = 1000


How To Remove Values Saved in the Current Session?
If you want to remove values saved in the current session, you should use the unset() function on those saved values in $_SESSION, or use array() to empty $_SESSION:
  • unset($_SESSION['MyColor']) - Removes one value named MyColor in the current session.
  • $_SESSION = array() - Removes all values in the current session.
  • unset($_SESSION) - Bad statement. It may affect the session mechanism.

How To Tell If a Session Is New?
There is not direct way to tell if a session is new or old. But you can design your site to have a required session value in all sessions. Then you can check the existence of this value in a session to determine if it is a new session by isset($_SESSION['name']).
Let's say you decided to have a required session value called "Status" with two possible values: "Guest" and "Registered". The landing script of your site should look like:
<?php
  session_start();
  if (!isset($_SESSION['Status'])) {
    $_SESSION["Status"] = "Guest";
    print("<html><pre>");
    print("Welcome to PICKZYCenter.com!\n");
    print("  <a href=login.php>Login</a>\n");
    print("  <a href=guest_home.php>Stay as a guest</a>\n");
    print("</pre></html>\n");
  } else {
    if ($_SESSION["Status"] == "Guest") {
      header( 'Location: http://localhost/guest_home.php');
    } else if ($_SESSION["Status"] == "Registered") {
      header( 'Location: http://localhost/home.php');
    }
  }
?>

How To Close a Session Properly?
Let's say you site requires users to login. When a logged in user clicks the logout button, you need to close the session associated with this user properly in 3 steps:
  1. Remove all session values with $_SESSION = array().
  2. Remove the session ID cookie with the setcookie() function.
  3. Destroy the session object with the session_destroy() function.
Below is a good sample script:
<?php
  session_start();
$_SESSION = array();
 if (isset($_COOKIE[session_name()])) {
  setcookie(session_name(), '', time()-42000, '/');
  }
 session_destroy();
  print("<html><pre>");
  print("Thank you for visiting PICKZYCenter.com.\n");
  print("  <a href=login.php>Login Again.</a>\n");
  print("</pre></html>\n");
?>

What Is session_register()?
session_register() is old function that registers global variables into the current session. You should stop using session_register() and use array $_SESSION to save values into the current session now.
How To Install MySQL?
MySQL is an open source database management system developed by MySQL AB, http://www.mysql.com. You can download a copy and install it on your local computer. Here is how you can do this:
  • Go to http://dev.mysql.com/downloads/mysql/5.0.html.
  • Select the "Windows" and "Without installer" version.
  • Unzip the downloaded file to "\mysql" directory, and double click on "\mysql\setup.exe" to start and finish the installation process.
  • Open a command window and run "\mysql\bin\mysqld" to start MySQL server

How To Use MySQL Command Line Interface?
MySQL server comes with a command line interface, which will allow you to operate with the server with SQL statements and other commands. To start the command line interface, you can run the \mysql\bin\mysql program. The tutorial exercise below shows you how to use the command line interface to create a table and insert a row to table:
>\mysql\bin\mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
mysql> use test;
Database changed
mysql> CREATE TABLE pickzy_links (url varchar(80));
Query OK, 0 rows affected (0.58 sec)
 mysql> INSERT INTO pickzy_links VALUES ('dev.pickzycenter.com');
Query OK, 1 row affected (0.38 sec)
 mysql> SELECT * FROM pickzy_links;
+-------------------+
| url               |
+-------------------+
| dev.capptitudebank.blogspot.com |
+-------------------+
1 row in set (0.00 sec)
 mysql> DROP TABLE pickzy_links;
Query OK, 0 rows affected (0.34 sec)
 mysql> quit;
Bye
What Do You Need to Connect PHP to MySQL?
If you want to access MySQL database server in your PHP script, you need to make sure that MySQL module is installed and turned on in your PHP engine. Check the PHP configuration file, php.ini, to make sure the extension=php_mysql.dll is not commented out.
The MySQL module offers a number of functions to allow you to work with MySQL server. Some commonly used MySQL functions are:
  • mysql_connect -- Open a connection to a MySQL Server
  • mysql_close -- Close MySQL connection
  • mysql_db_query -- Send a MySQL query
  • mysql_fetch_array -- Fetch a result row as an associative array, a numeric array, or both
  • mysql_free_result -- Free result memory
  • mysql_list_tables -- List tables in a MySQL database
  • mysql_list_fields -- List MySQL table fields
How To Connect to MySQL from a PHP Script?
If you want access the MySQL server, you must create a connection object first by calling the mysql_connect() function in the following format:
$con = mysql_connect($server, $username, $password);
If you are connecting to a local MySQL server, you don't need to specify username and password. If you are connecting to a MySQL server offered by your Web hosting company, they will provide you the server name, username, and password.
The following script shows you how to connect to a local MySQL server, obtained server information, and closed the connection:
<?php
  $con = mysql_connect('localhost');
  print(mysql_get_server_info($con)."\n");
  print(mysql_get_host_info($con)."\n");
  mysql_close($con); 
?>
If you run this script, you will get something like this:
5.0.2-alpha
localhost via TCP/IP


How To Create a Database?
A database in a MySQL server is a logical container used to group tables and other data objects together as a unit. If you are a the administrator of the server, you can create and delete databases using the CREATE/DROP DATABASE statements. The following PHP script shows you how to create and drop an database called "pickzy":
<?php
  $con = mysql_connect('localhost');
  $sql = 'CREATE DATABASE pickzy';
  if (mysql_query($sql, $con)) {
    print("Database pickzy created.\n");
  } else {
    print("Database creation failed.\n");
  }
 
  $sql = 'DROP DATABASE pickzy';
  if (mysql_query($sql, $con)) {
    print("Database pickzy dropped.\n");
  } else {
    print("Database drop failed.\n");
  }
  mysql_close($con); 
?>
If you run this script, you will get something like this:
Database pickzy created.
Database pickzy dropped.
How To Select an Exiting Database?

The first thing after you have created a connection object to the MySQL server is to select the database where your tables are locate, by using the mysql_select_db() function. If your MySQL server is offered by your Web hosting company, they will assign a database to you and provide you the database name. You should use this name to select your database as your current database. The following script shows you how to select a database called "pickzy". It also shows you how to put all the database connection statements in a single include file, and re-use it in all of your PHP pages.
Create the include file, connect.php, with the following statements:
<?php
  $server = "localhost";
  $username = "";
  $password = "";
  $database = "pickzy";
  $con = mysql_connect($server, $username, $password);
  mysql_select_db($database);
?>
To test this database connection and selection include file, try the following script:
<?php
  include "mysql_connection.php";
   $sql = 'SHOW TABLES';
  if ($rs = mysql_query($sql, $con)) {
    print(mysql_num_rows($rs) . " tables in the database.\n");
  } else {
    print("SHOW TABLES failed.\n");
  }
  mysql_close($con); 
?>
You will get something like this:
0 tables in the database.
How To Run a SQL Statement?
You can run any types of SQL statements through the mysql_query() function. It takes the SQL statement as a string and returns different types of data depending on the SQL statement type and execution status:
  • Returning FALSE, if the execution failed.
  • Returning a result set object, if the execution is successful on a SELECT statement or other statement returning multiple rows of data.
  • Returning TRUE, if the execution is successful on other statements.
Here is a good example of running a SQL statement with the mysql_query() function:
<?php
  include "mysql_connection.php";
  $sql = 'SELECT sysdate() FROM dual';
  $rs = mysql_query($sql, $con);
  $row = mysql_fetch_array($rs);
  print("Database current time: ". $row[0] ."\n");
  mysql_close($con); 
?>
If you run this script, you will get something like this:
Database current time: 2006-02-26 21:34:57

How To Create a Table?
If you want to create a table, you can run the CREATE TABLE statement as shown in the following sample script:
<?php
  include "mysql_connection.php";
  $sql = "CREATE TABLE pickzy_links ("
      . " id INTEGER NOT NULL" 
      . ", url VARCHAR(80) NOT NULL"
      . ", notes VARCHAR(1024)"
      . ", counts INTEGER"
      . ", time TIMESTAMP DEFAULT sysdate()"
      . ")";
  if (mysql_query($sql, $con)) {
    print("Table pickzy_links created.\n");
  } else {
    print("Table creation failed.\n");
  }
  mysql_close($con); 
?>
Remember that mysql_query() returns TRUE/FALSE on CREATE statements. If you run this script, you will get something like this:
Table pickzy_links created.
How To Get the Number of Rows Selected or Affected by a SQL Statement?
There are two functions you can use the get the number of rows selected or affected by a SQL statement:
  • mysql_num_rows($rs) - Returns the number of rows selected in a result set object returned from SELECT statement.
  • mysql_affected_rows() - Returns the number of rows affected by the last INSERT, UPDATE or DELETE statement.
How To Insert Data into a Table?
If you want to insert a row of data into a table, you can use the INSERT INTO statement as shown in the following sample script:
<?php
  include "mysql_connection.php";
   $sql = "INSERT INTO pickzy_links (id, url) VALUES ("
      . " 101, 'dev.pickzycenter.com')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
  $sql = "INSERT INTO pickzy_links (id, url) VALUES ("
      . " 102, 'dba.pickzycenter.com')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
   mysql_close($con); 
?>
Remember that mysql_query() returns integer/FALSE on INSERT statements. If you run this script, you will get something like this:
1 rows inserted.
1 rows inserted.

How To Insert Rows Based on SELECT Statements?
If want to insert rows into a table based on data rows from other tables, you can use a sub-query inside the INSERT statement as shown in the following script example:
<?php
  include "mysql_connection.php";
   $sql = "INSERT INTO pickzy_links"
      . " SELECT id+1000, url, notes, counts, time FROM pickzy_links";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
   mysql_close($con); 
?>
If you run this script, you will get something like this:
2 rows inserted.
What Is a Result Set Object?
A result set object is a logical representation of data rows returned by mysql_query() function on SELECT statements. Every result set object has an internal pointer used to identify the current row in the result set. Once you get a result set object, you can use the following functions to retrieve detail information:
  • mysql_free_result($rs) - Closes this result set object.
  • mysql_num_rows($rs) - Returns the number rows in the result set.
  • mysql_num_fields($rs) - Returns the number fields in the result set.
  • mysql_fetch_row($rs) - Returns an array contains the current row indexed by field position numbers.
  • mysql_fetch_assoc($rs) - Returns an array contains the current row indexed by field names.
  • mysql_fetch_array($rs) - Returns an array contains the current row with double indexes: field position numbers and filed names.
  • mysql_fetch_lengths($rs) - Returns an array contains lengths of all fields in the last row returned.
  • mysql_field_name($rs, $i) - Returns the name of the field of the specified index.
How To Query Tables and Loop through the Returning Rows?
The best way to query tables and loop through the returning rows is to run the SELECT statement with the catch the mysql_query() function, catch the returning object as a result set, and loop through the result with the mysql_fetch_assoc() function in a while loop as shown in the following sample PHP script:
<?php
  include "mysql_connection.php";
  $sql = "SELECT id, url, time FROM pickzy_links";
  $rs = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($rs)) {
    print($row['id'].", ".$row['url'].", ".$row['time']."\n");
  }
  mysql_free_result($rs);
  mysql_close($con); 
?>
Using mysql_fetch_assoc() is better than other fetch functions, because it allows you to access field values by field names. If you run this script, you will see all rows from the pickzy_links table are printed on the screen:
101, dev.pickzycenter.com, 2006-02-26 22:29:02
102, dba.pickzycenter.com, 2006-02-26 22:29:02
1101, dev.pickzycenter.com, 2006-02-26 22:29:02
1102, dba.pickzycenter.com, 2006-02-26 22:29:02


How To Update an Existing Rows in a Table?
Updating existing rows in a table requires to run the UPDATE statement with a WHERE clause to identify the row. The following sample script updates one row with two new values:
<?php
  include "mysql_connection.php";
  $sql = "UPDATE pickzy_links SET notes='Nice site.', counts=8"
    . " WHERE id = 102";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows updated.\n");
  } else {
    print("SQL statement failed.\n");
  }
  mysql_close($con); 
?>
If you run this script, you will get something like this:
1 rows updated.
How To Delete an Existing Rows in a Table?
If you want to remove a row from a table, you can use the DELETE statement with a WHERE clause to identify the row. The following sample script deletes one row:
<?php
  include "mysql_connection.php";
 
  $sql = "DELETE FROM pickzy_links WHERE id = 1102";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows deleted.\n");
  } else {
    print("SQL statement failed.\n");
  }
  mysql_close($con); 
?>
If you run this script, you will get something like this:
1 rows deleted.
How To Quote Text Values in SQL Statements?
Text values in SQL statements should be quoted with single quotes ('). If the text value contains a single quote ('), it should be protected by replacing it with two single quotes (''). In SQL language syntax, two single quotes represents one single quote in string literals. The tutorial exercise below shows you two INSERT statements. The first one will fail, because it has an un-protected single quote. The second one will be ok, because a str_replace() is used to replace (') with (''):
<?php
  include "mysql_connection.php";
  $notes = "It's a search engine!";
  $sql = "INSERT INTO pickzy_links (id, url, notes) VALUES ("
      . " 201, 'www.google.com', '".$notes."')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
  $notes = "It's another search engine!";
  $notes = str_replace("'", "''", $notes);
  $sql = "INSERT INTO pickzy_links (id, url, notes) VALUES ("
      . " 202, 'www.yahoo.com', '".$notes."')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
  mysql_close($con); 
?>
If you run this script, you will get something like this:
SQL statement failed.
1 rows inserted.
How To Quote Date and Time Values in SQL Statements?
If you want to provide date and time values in a SQL statement, you should write them in the format of "yyyy-mm-dd hh:mm:ss", and quoted with single quotes ('). The tutorial exercise below shows you two INSERT statements. The first one uses a hard-code date value. The second one uses the date() function to return a date value.
<?php
  include "mysql_connection.php";
   $notes = "Added long time ago!";
  $time = "1999-01-01 01:02:03";
  $sql = "INSERT INTO pickzy_links (id, url, notes, time) VALUES ("
      . " 301, 'www.netscape.com', '".$notes."', '".$time."')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
   $notes = "Added today!";
  $time = date("Y-m-d H:i:s");
  $sql = "INSERT INTO pickzy_links (id, url, notes, time) VALUES ("
      . " 302, 'www.myspace.com', '".$notes."', '".$time."')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }
   mysql_close($con); 
?>
If you run this script, you will get something like this:
1 rows inserted.
1 rows inserted.
How To Perform Key Word Search in Tables?
The simplest way to perform key word search is to use the SELECT statement with a LIKE operator in the WHERE clause. The LIKE operator allows you to match a text field with a keyword pattern specified as '%keyword%', where (%) represents any number of any characters. Any single quote (') in the keyword needs to be protected by replacing them with two single quotes (''). The tutorial exercise below shows you how to search for records whose "notes" contains "e":
<?php
  include "mysql_connection.php";
  $key = "e";
  $key = str_replace("'", "''", $key);
  $sql = "SELECT id, url, notes FROM pickzy_links"
    . " WHERE notes LIKE '%".$key."%'";
  $rs = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($rs)) {
    print($row['id'].", ".$row['url'].", ".$row['notes']."\n");
  }
  mysql_free_result($rs);
  mysql_close($con); 
?>
If you run this script, you will get something like this:
102, dba.pickzycenter.com, Nice site.
301, www.netscape.com, Added long time ago!
302, www.myspace.com, Added today!
202, www.yahoo.com, It's another search engine!
How To Query Multiple Tables Jointly?
If you want to query information stored in multiple tables, you can use the SELECT statement with a WHERE condition to make an inner join. Assuming that you have 3 tables in a forum system: "users" for user profile, "forums" for forums information, and "posts" for postings, you can query all postings from a single user with a script as shown below:
<?php
  include "mysql_connection.php";
  $userID = 101;
  $sql = "SELECT posts.subject, posts.time, users.name, forums.title"
    . " FROM posts, users, forums"
    . " WHERE posts.userID = ".$userID
    . " AND posts.userID = users.id"
    . " AND posts.forumID = forums.id";
  $rs = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($rs)) {
    print($row['subject'].", ".$row['time'].", "
      .$row['name'].", ".$row['title']."\n");
  }
  mysql_free_result($rs);
  mysql_close($con); 
?>
How To Get the ID Column Auto-Incremented?
Many tables require an ID column to assign a unique ID number for each row in the table. For example, if you have a table to hold forum member profiles, you need an ID number to identify each member. To allow MySQL server to automatically assign a new ID number for each new record, you can define the ID column with AUTO_INCREMENT and PRIMARY KEY attributes as shown in the following sample script:
<?php
  include "mysql_connection.php";
  $sql = "CREATE TABLE pickzy_users ("
      . " id INTEGER NOT NULL AUTO_INCREMENT" 
      . ", name VARCHAR(80) NOT NULL"
      . ", email VARCHAR(80)"
      . ", time TIMESTAMP DEFAULT sysdate()"
      . ", PRIMARY KEY (id)"
      . ")";
  if (mysql_query($sql, $con)) {
    print("Table pickzy_links created.\n");
  } else {
    print("Table creation failed.\n");
  }
  mysql_close($con); 
?>
If you run this script, a new table will be created with ID column defined as auto-increment. The sample script below inserts two records with ID values assigned by MySQL server:
If you run this script, you will get something like this:
 1 rows inserted.
1 rows inserted.
1, John King, 2006-02-26 23:02:39
2, Nancy Greenberg, 2006-02-26 23:02:39
How To Get the Last ID Assigned by MySQL?
If you use an ID column with AUTO_INCREMENT attribute, you can use the mysql_insert_id() function to get the last ID value assigned by the MySQL server, as shown in the sample script below:
<?php
  include "mysql_connection.php";
  $sql = "INSERT INTO pickzy_users (name) VALUES ('John King')";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
    print("Last ID inserted: ".mysql_insert_id()."\n");
  } else {
    print("SQL statement failed.\n");
  }
  mysql_close($con); 
?>
If you run this script, you will get something like this:
1 rows inserted.
Last ID inserted: 3
What Is File Upload?
File upload is Web page function which allows visitor to specify a file on the browser's system and submit it to the Web server. This is a very useful function for many interactive Web sites. Some examples are:
  • Web base email systems for users to send attachments.
  • Forums that allows user to submit pictures.
  • Web sites file managers for users to build their own Web pages.
Which HTML Tag Allows Users to Specify a File for Uploading?
To present an input field on your Web page to allow users to specify a local file to upload, you need to use the <INPUT TYPE="FILE" ...> tag inside a <FORM ...> tag. The <INPUT TYPE="FILE" ...> will be displayed as a text input field followed by a button called "Browse...". Users can either enter the full path name of a local file, or click Browse button to go through a dialog box to select a file interactively. The following PHP code shows you a good example of the file upload tag:
<?php
  print("<html><form>\n");
  print("<input type=file>\n");
  print("<input type=submit>\n");
  print("</form></html>\n");
?>
If you copy this script to PHP file and test it on your Web server, you should see a file upload field.
How To Write the FORM Tag Correctly for Uploading Files?
When users clicks the submit button, files specified in the <INPUT TYPE=FILE...> will be transferred from the browser to the Web server. This transferring (uploading) process is controlled by a properly written <FORM...> tag as:
  <FORM ACTION=receiving.php METHOD=post ENCTYPE=multipart/form-data>
Note that you must specify METHOD as "post" and ENCTYPE as "multipart/form-data" in order for the uploading process to work. The following PHP code, called logo_upload.php, shows you a complete FORM tag for file uploading:
<?php
  print("<html><form action=processing_uploaded_files.php"
    ." method=post enctype=multipart/form-data>\n");
  print("Please submit an image file a Web site logo for"
    ." pickzycenter.com:<br>\n");
  print("<input type=file name=pickzycenter_logo><br>\n");
  print("<input type=submit>\n");
  print("</form></html>\n");
?>
How To Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified in the form action attribute to process them. This receiving PHP script can get the uploaded file information through the predefined array called $_FILES. Uploaded file information is organized in $_FILES as a two-dimensional array as:
  • $_FILES[$fieldName]['name'] - The Original file name on the browser system.
  • $_FILES[$fieldName]['type'] - The file type determined by the browser.
  • $_FILES[$fieldName]['size'] - The Number of bytes of the file content.
  • $_FILES[$fieldName]['tmp_name'] - The temporary filename of the file in which the uploaded file was stored on the server.
  • $_FILES[$fieldName]['error'] - The error code associated with this file upload.
The $fieldName is the name used in the <INPUT TYPE=FILE, NAME=fieldName>.
How To Process the Uploaded Files?
How to process the uploaded files? The answer is really depending on your application. For example:
  • You can attached the outgoing emails, if the uploaded files are email attachments.
  • You can move them to user's Web page directory, if the uploaded files are user's Web pages.
  • You can move them to a permanent directory and save the files names in the database, if the uploaded files are articles to be published on the Web site.
  • You can store them to database tables, if you don't want store them as files.
How To Move Uploaded Files To Permanent Directory?
PHP stores uploaded files in a temporary directory with temporary file names. You must move uploaded files to a permanent directory, if you want to keep them permanently. PHP offers the move_uploaded_file() to help you moving uploaded files. The example script, processing_uploaded_files.php, below shows a good example:
<?php
  $file = '\pickzycenter\images\pickzycenter.logo';
  print("<pre>\n");
  move_uploaded_file($_FILES['pickzycenter_logo']['tmp_name'], $file);
  print("File uploaded: ".$file."\n");
  print("</pre>\n");
?>
Note that you need to change the permanent directory, "\pickzycenter\images\", used in this script to something else on your Web server. If your Web server is provided by a Web hosting company, you may need to ask them which directories you can use to store files.
If you copy both scripts, logo_upload.php and processing_uploaded_files.php, to your Web server, you can try them to upload an image file to your Web server.
How To Detect File Uploading Errors?
If there was a problem for a file upload request specified by the <INPUT TYPE=FILE NAME=fieldName...> tag, an error code will be available in $_FILES[$fieldName]['error']. Possible error code values are:
  • UPLOAD_ERR_OK (0) - There is no error, the file uploaded with success.
  • UPLOAD_ERR_INI_SIZE (1) - The uploaded file exceeds the upload_max_filesize directive in php.ini.
  • UPLOAD_ERR_FORM_SIZE (2) - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  • UPLOAD_ERR_PARTIAL (3) - The uploaded file was only partially uploaded.
  • UPLOAD_ERR_NO_FILE (4) - No file was uploaded.
  • UPLOAD_ERR_NO_TMP_DIR (5) - Missing a temporary folder.
Based on the error codes, you can have a better logic to process uploaded files more accurately, as shown in the following script:
<?php
  $file = '\pickzycenter\images\pickzycenter.logo';
  $error = $_FILES['pickzycenter_logo']['error'];
  $tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
  print("<pre>\n");
  if ($error==UPLOAD_ERR_OK) {
    move_uploaded_file($tmp_name, $file);
    print("File uploaded.\n");
  } else if ($error==UPLOAD_ERR_NO_FILE) {
    print("No files specified.\n");
  } else {
    print("Upload faield.\n");
  }
  print("</pre>\n");
?>
If you try this script with logo_upload.php and do not specify any files, you will get the "No files specified." message.
Why Do You Need to Filter Out Empty Files?
When you are processing uploaded files, you need to check for empty files, because they could be resulted from a bad upload process but the PHP engine could still give no error. For example, if a user typed a bad file name in the upload field and submitted the form, the PHP engine will take it as an empty file without raising any error. The script below shows you an improved logic to process uploaded files:
<?php
  $file = '\pickzycenter\images\pickzycenter.logo';
  $error = $_FILES['pickzycenter_logo']['error'];
  $tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
  print("
\n");
  if ($error==UPLOAD_ERR_OK) {
    if ($_FILES['pickzycenter_logo']['size'] > 0) {
      move_uploaded_file($tmp_name, $file);
      print("File uploaded.\n");
    } else {
      print("Loaded file is empty.\n");
    }
  } else if ($error==UPLOAD_ERR_NO_FILE) {
    print("No files specified.\n");
  } else {
    print("Upload faield.\n");
  }
  print("
\n");
?>
How To Create a Table To Store Files?
If you using MySQL database and want to store files in database, you need to create BLOB columns, which can holds up to 65,535 characters. Here is a sample script that creates a table with a BLOB column to be used to store uploaded files:
<?php
  $con = mysql_connect("localhost", "", "");
  mysql_select_db("pickzy");
  $sql = "CREATE TABLE pickzy_files ("
      . " id INTEGER NOT NULL AUTO_INCREMENT" 
      . ", name VARCHAR(80) NOT NULL"
      . ", type VARCHAR(80) NOT NULL"
      . ", size INTEGER NOT NULL"
      . ", content BLOB"
      . ", PRIMARY KEY (id)"
      . ")";
  mysql_query($sql, $con); 
  mysql_close($con); 
?>
How To Uploaded Files to a Table?
To store uploaded files to MySQL database, you can use the normal SELECT statement as shown in the modified processing_uploaded_files.php listed below:
<?php
  $con = mysql_connect("localhost", "", "");
  mysql_select_db("pickzy");
  $error = $_FILES['pickzycenter_logo']['error'];
  $tmp_name = $_FILES['pickzycenter_logo']['tmp_name'];
  $size = $_FILES['pickzycenter_logo']['size'];
  $name = $_FILES['pickzycenter_logo']['name'];
  $type = $_FILES['pickzycenter_logo']['type'];
  print("
\n");
  if ($error == UPLOAD_ERR_OK && $size > 0) {
    $fp = fopen($tmp_name, 'r');
    $content = fread($fp, $size);
    fclose($fp);     
    $content = addslashes($content);
    $sql = "INSERT INTO pickzy_files (name, type, size, content)"
      . " VALUES ('$name', '$type', $size, '$content')";
    mysql_query($sql, $con);
    print("File stored.\n");
  } else {
    print("Upload faield.\n");
  }
  print("
\n");
  mysql_close($con);
?>
Note that addslashes() is used to add backslashes to special characters that need to be protected in SQL statements.
What Are the File Upload Settings in Configuration File?
There are several settings in the PHP configuration file related to file uploading:
  • file_uploads = On/Off - Whether or not to allow HTTP file uploads.
  • upload_tmp_dir = directory - The temporary directory used for storing files when doing file upload.
  • upload_max_filesize = size - The maximum size of an uploaded file.
How To Get the Technical Specifications for File Upload?
File upload technical specifications is provided in "Form-based File Upload in HTML - RFC 1867". You can get a copy from http://www.ietf.org/rfc/rfc1867.txt.



click the Below link download this file 


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

Blog Archive

 

© 2011. All Rights Reserved | Interview Questions | Template by Blogger Widgets

Home | About | Top