Archive for the ‘php’ Category


working with file uploads in php

Monday, April 14th, 2008

Information about the uploaded file becomes available to you in the $_FILES superglobal, which is indexed by the name of the upload field (or fields) in the form. The corresponding value for each of these keys is an associative array. These fields are described in table below, using fileupload as the name of the form field used for the upload.

 

Element

Contains

Example

$_FILES[’fileupload’][’name’]

Original name of uploaded file

test.gif

$_FILES[’fileupload’][’tmp_name’]

Path to temporary file

/tmp/phprDfZvN

$_FILES[’fileupload’][’size’]

Size (in bytes) of uploaded file

6835

$_FILES[’fileupload’][’type’]

MIME type of uploaded file (where given by client)

image/gif

Keep these elements in the back of your mind for a moment, while we create the upload form in the next section.

Creating the File Upload Form

First, we must create the HTML form to handle the upload. HTML forms that include file upload fields must include an ENCTYPE argument:

ENCTYPE="multipart/form-data"

PHP also works with an optional hidden field that can be inserted before the file upload field. This field must be called MAX_FILE_SIZE and should have a value representing the maximum size in bytes of the file that you’re willing to accept. This size cannot override the maximum size set in the upload_max_filesize field in your php.ini file that defaults to 2MB. The MAX_FILE_SIZE field is obeyed at the browser’s discretion, so you should rely on the php.ini setting to cap unreasonable uploads. After the MAX_FILE_SIZE field has been entered, you’re ready to add the upload field itself. This is simply an INPUT element with a TYPE argument of “file”. You can give it any name you want.Below form brings all this together into an HTML upload form.

A Simple File Upload Form
  1: <html>
  2: <head>
  3: <title> A simple file upload form</title>
  4: </head>
  5: <body>
  6: <form action=”action_fileupload.php” enctype=”multipart/form-data” method=”POST”>
  7: <input type=”hidden” name=”MAX_FILE_SIZE” value=”51200″>
  8: File to Upload: <input type=”file” name=”fileupload”><br><br>
  9: <input type=”submit” value=”upload!”>
 10: </form>
 11: </body>
 12: </html>

As you can see, file uploads are limited to 50KB on line 7, and the name of the file upload field is fileupload, as shown on line 8. Save this in a text file called fileupload.php, and place that file in your Web server document root.

This form calls the action_fileupload.php script, which we create next.

Creating the File Upload Script

If you remember the information regarding the $_FILES superglobal, you have all the information you need to write a simple file upload script. This script is the backend for the form created in fileupload.php.

A File Upload Script
  1: <html>
  2: <head>
  3: <title> A file upload script</title>
  4: </head>
  5: <body>
  6: <h1>File Upload Results</h1>
  7: <?php
  8: $file_dir = “/path/to/upload/directory”;
  9:
 10: foreach($_FILES as $file_name => $file_array) {
 11:     print “path: “.$file_array[’tmp_name’].”<br>\n”;
 12:     print “name: “.$file_array[’name’].”<br>\n”;
 13:     print “type: “.$file_array[’type’].”<br>\n”;
 14:     print “size: “.$file_array[’size’].”<br>\n”;
 15:
 16:     if (is_uploaded_file($file_array[’tmp_name’])) {
 17:         move_uploaded_file($file_array[’tmp_name’],
 18:            “$file_dir/$file_array[name]”) or die (”Couldn’t copy”);
 19:         print “file was moved!<br><br>”;
 20:      }
 21: }
 22: ?>
 23: </body>
 24: </html>

In action_fileupload.php, we first create the $file_dir variable on line 8 to store path information. This path should be one that exists on your system, and you must have write permissions for it.

 

The path used in line 8 is a Linux/Unix path. Windows users would use backslashes, such as \My Documents\.

Line 10 begins a foreach statement that loops through every element in the $_FILES array. A loop is used rather than an if statement to make our script capable of scaling to deal with multiple uploads on the same page. The foreach loop on line 10 stores the upload file’s name in the $file_name variable and the file information in the $file_array variable. We can then output the information we have about the upload.

Before moving the uploaded file from its temporary position to the location specified in line 8, first check that it exists. We do so on line 16, using the is_uploaded_file() function. This function accepts a path to an uploaded file and returns true only if the file in question is a valid upload file. This function therefore enhances the security of your scripts.

Assuming that all is well, the file is copied from its temporary home to a new directory on lines 17 and 18. We use another function, move_uploaded_file(), for this purpose. This function copies a file from one place to another, first performing the same security checks as those performed by is_uploaded_file(). The move_uploaded_file() function requires a path to the source file and a path to the destination. It returns true if the move is successful and false if the file isn’t a valid upload file or if the file couldn’t be found.

 

Beware of the names of uploaded files. Operating systems such as Mac OS and Windows are pretty relaxed when it comes to file naming, so expect uploaded files to come complete with spaces, quotation marks, and all manner of other unexpected characters. Therefore, it’s a good idea to filter filenames.

 


Accessing Form Input with User-Defined Arrays

Monday, April 14th, 2008

Normally to gather information from HTML elements we submit a single value per element name. This leaves us with a problem when working with SELECT elements. These elements make it possible for the user to choose multiple items. If we name the SELECT element with a plain name, like so

<select name="products" multiple>

the script that receives this data has access to only a single value corresponding to this name. We can change this behavior by renaming an element of this kind so that its name ends with an empty set of square brackets. We do this as shown below.

An HTML Form Including a SELECT Element
  1: <html>
  2: <head>
  3: <title> An HTML form including a SELECT element</title>
  4: </head>
  5: <body>
  6: <form action=”action_multiplevalues.php” method=”POST”>
  7: Name: <br>
  8: <input type=”text” name=”user”>
  9: <br>
 10: Address: <br>
 11: <textarea name=”address” rows=”5″ cols=”40″></textarea>
 12: <br>
 13: Pick Products: <br>
 14: <select name=”products[]” multiple>
 15: <option>Sonic Screwdriver</option>
 16: <option>Tricorder</option>
 17: <option>ORAC AI</option>
 18: <option>HAL 2000</option>
 19: </select>
 20: <br><br>
 21: <input type=”submit” value=”hit it!”>
 22: </form>
 23: </body>
 24: </html>

Put these lines into a text file called form_multiplevalues.php, and place that file in your Web server document root. Next, in the script that processes the form input, we find that input from the “products[]” form element created on line 14 is available in an array called $_POST[products]. Because products[] is a SELECT element, we offer the user multiple choices using the option elements on lines 15 through 18. We demonstrate that the user’s choices are made available in an array in action_multiplevalues.php

Reading Input from the Form in form_multiplevalues.php
  1: <html>
  2: <head>
  3: <title>Action_multiplevalues.php Reading input from the form in form_multiplevalues.php</title>
  4: </head>
  5: <body>
  6: <?php
  7: print “Welcome <b>$_POST[user]</b><p>\n\n”;
  8: print “Your address is:<p>\n\n<b>$_POST[address]</b><p>\n\n”;
  9: print “Your product choices are:<p>\n\n”;
 10: if (!empty($_POST[products])) {
 11:     print “<ul>\n\n”;
 12:     foreach ($_POST[products] as $value) {
 13:        print “<li>$value\n”;
 14:        }
 15:        print “</ul>”;
 16: }
 17: ?>
 18: </body>
 19: </html>

Put these lines into a text file called listing9.5.php, and place that file in your Web server document root. Now access the form in form_multiplevalues.php with your Web browser and fill out the fields.

On line 7 of the script in action_multiplevalues.php, we access the $_POST[user] variable, which is derived from the user form element. On line 10, we test for the $_POST[products] variable. If $_POST[products] is present, we loop through it on line 12, and output each choice to the browser on line 13.

Submit the form and you might see something like that shown in form_multiplevalues.php.

Although the looping technique is particularly useful with the SELECT element, it works with every form element. For example, by giving a number of check boxes the same name, you can enable a user to choose many values within a single field name. As long as the name you choose ends with empty square brackets, PHP compiles the user input for this field into an array. We can replace the SELECT elements from lines 15-18 in form_multiplevalues.php with a series of check boxes to achieve the same effect:

<input type="checkbox" name="products[]" value="Sonic
       Screwdriver">Sonic Screwdriver<br>
<input type="checkbox" name="products[]" value="Tricorder">Tricorder<br>
<input type="checkbox" name="products[]" value="ORAC AI">ORAC AI<br>
<input type="checkbox" name="products[]" value="HAL 2000">HAL 2000<br>


Creating a Simple Input Form working with php

Monday, April 14th, 2008

For now, let’s keep our HTML separate from our PHP code. Code below builds a simple HTML form.

A Simple HTML Form
  1: <html>
  2: <head>
  3: <title>form.php simple HTML form</title>
  4: </head>
  5: <body>
  6: <form action=”formaction.php” method=”POST”>
  7: Name: <br>
  8: <input type=”text” name=”user”>
  9: <br>
 10: Address: <br>
 11: <textarea name=”address” rows=”5″ cols=”40″></textarea>
 12: <br>
 13: <input type=”submit” value=”hit it!”>
 14: </form>
 15: </body>
 16: </html>

Put these lines into a text file called form.php, and place that file in your Web server document root. This listing defines a form that contains a text field with the name “user” on line 8, a text area with the name “address” on line 11, and a submit button on line 13. The FORM element’s ACTION  points to a file called formaction.php, which processes the form information. The method of this form is POST, so the variables are stored in the $_POST superglobal.

Code below creates the code that receives our users’ input.

Reading Input from the Form in form.php
  1: <html>
  2: <head>
  3: <title>formaction.php Reading input from the form in form.php</title>
  4: </head>
  5: <body>
  6: <?php
  7: print “Welcome <b>$_POST[user]</b><P>\n\n”;
  8: print “Your address is:<P>\n\n<b>$_POST[address]</b>”;
  9: ?>
 10: </body>
 11: </html>

Put these lines into a text file called formaction.php, and place that file in your Web server document root. Now access the form itself with your Web browser.

The script in formaction.php is called when a user submits the form defined in form.php

In the code, we access two variables: $_POST[user] and $_POST[address]. These are references to the variables in the $_POST superglobal, which contain the values that the user added to the “user” text field and the “address” text area. Forms in PHP really are as simple as that.

Enter some information in the form fields, and click the Hit It! button. You should see your input echoed to the screen.


Predefined variables in PHP

Monday, April 14th, 2008

PHP has several predefined variables called superglobals, which essentially means that they’re always present and available in your scripts. Each of the following superglobals is actually an array of other variables:

  • $_GET contains any variables provided to a script through the GET method.

  • $_POST contains any variables provided to a script through the POST method.

  • $_COOKIE contains any variables provided to a script through a cookie.

  • $_FILES contains any variables provided to a script through file uploads.

  • $_ENV contains any variables provided to a script as part of the server environment.

  • $_REQUEST contains any variables provided to a script via any user input mechanism.

  • $_SESSION contains any variables that are currently registered in a session.

 

If you’re using a version of PHP earlier than 4.1.x and cannot upgrade to a newer version, you must adjust the names of the variables when you’re following the scripts in this book. The old names are $HTTP_GET_VARS (for $_GET), $HTTP_POST_VARS (for $_POST), $HTTP_COOKIE_VARS (for $_COOKIE), $HTTP_POST_FILES (for $_FILES), $HTTP_ENV_VARS (for $_ENV), and $HTTP_SESSION_VARS (for $_SESSION).


working with php mysql for inserting and retrieving records

Monday, April 14th, 2008

   

Working with MySQL Data

Inserting, updating, deleting, and retrieving data all revolve around the use of the mysql_query() function to execute the basic SQL queries. For INSERT, UPDATE, and DELETE, no additional scripting is required after the query has been executed because you’re not displaying any results (unless you want to). For SELECT, you have a few options for displaying the data retrieved by your query. Let’s start with the basics and insert some data, so you’ll have something to retrieve later on.

Inserting Data with PHP

The easiest method for inserting data is to simply hard-code the INSERT statement, as shown below.

A Script to Insert a Record
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  4: // pick the database to use
  5: mysql_select_db(”testDB”,$conn);
  6: // create the SQL statement
  7: $sql = “INSERT INTO testTable values (”, ’some value’)”;
  8: // execute the SQL statement
  9: $result = mysql_query($sql, $conn) or die(mysql_error());
 10: // echo the result identifier
 11: echo $result;
 12: ?>

You might wonder why you need to echo the result identifier if you’re just inserting data. Well, you don’t have to; it’s just there for kicks. You can clean this script up a bit by replacing the query execution line so that it simply executes and prints a relevant statement if successful, as shown below

The Modified Insert Script
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  4: // pick the database to use
  5: mysql_select_db(”testDB”,$conn);
  6: // create the SQL statement
  7: $sql = “INSERT INTO testTable values (”, ’some value’)”;
  8: // execute the SQL statement
  9: if (mysql_query($sql, $conn)) {
 10:     echo “record added!”;
 11: } else {
 12:     echo “something went wrong”;
 13: }
 14: ?>

Running this script will result in the addition of a row to the testTable table. To enter more records than just the one shown in the script, you can either make a long list of hard-coded SQL statements and use mysql_query() multiple times to execute these statements, or you can create a form-based interface to the record addition script.

To create the form for this script, you really only need one field because the id field can automatically increment. The action of the form is the name of the record-addition script; let’s call it insert.php. Your HTML form might look something like as shown below

An Insert Form
  1: <HTML>
  2: <HEAD>
  3: <TITLE>Insert Form</TITLE>
  4: </HEAD>
  5: <BODY>
  6: <FORM ACTION=”insert.php” METHOD=POST>
  7: <P>Text to add:<br>
  8: <input type=text name=”testField” size=30>
  9: <p><input type=submit name=”submit” value=”Insert Record”></p>
 10: </FORM>
 11: </BODY>
 12: </HTML>

Save this file as insert_form.html, and put it in the document root of your Web server. Next, create the insert.php script shown below. The value entered in the form will replace the hard-coded values in the SQL query with a variable called $_POST[testField].

An Insert Script Used with the Form
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect("localhost", "joeuser", "somepass");
  4: // pick the database to use
  5: mysql_select_db("testDB",$conn);
  6: // create the SQL statement
  7: $sql = "INSERT INTO testTable values ('', '$_POST[testField]')";
  8: // execute the SQL statement
  9: if (mysql_query($sql, $conn)) {
 10:     echo "record added!";
 11: } else {
 12:     echo "something went wrong";
 13: }
 14: ?>

Save the script as insert.php, and put it in the document root of your Web server. In your Web browser, access the HTML form that you created.

To verify your work, you can use the MySQL command-line interface to view the records in the table:

mysql> select * from testTable;

+—-+——————–+

| id | testField          |

+—-+——————–+

|  1 | some value         |

|  2 | this is some text! |
+—-+——————–+

2 rows in set (0.00 sec)

Next, you’ll learn how to retrieve and format results with PHP.

Retrieving Data with PHP

Because you have a few rows in your testTable table, you can write a PHP script to retrieve that data. Starting with the basics, write a script that issues a SELECT query but doesn’t overwhelm you with result data; let’s just get the number of rows. To do this, use the mysql_num_rows() function. This function requires a result, so when you execute the query, put the result index in $result (see below).

A Script to Retrieve Data
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  4: // pick the database to use
  5: mysql_select_db(”testDB”,$conn);
  6: // create the SQL statement
  7: $sql = “SELECT * FROM testTable”;
  8: // execute the SQL statement
  9: $result = mysql_query($sql, $conn) or die(mysql_error());
 10: //get the number of rows in the result set
 11: $number_of_rows = mysql_num_rows($result);
 12: echo “The number of rows is $number_of_rows”;
 13: ?>

Save this script as count.php, place it in your Web server document directory, and access it through your Web browser. You should see a message like this:

The number of rows is 2

The number should be equal to the number of records you inserted during testing. Now that you know there are some records in the table, you can get fancy and fetch the actual contents of those records. You can do this in a few ways, but the easiest method is to retrieve each row as an array.

What you’ll be doing is using a while statement to go through each record in the resultset, place the values of each field into a specific variable, then display the results onscreen. The syntax of mysql_fetch_array() is

$newArray = mysql_fetch_array($result);

Follow along using the sample script shown below

A Script to Retrieve Data and Display Results
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  4: // pick the database to use
  5: mysql_select_db(”testDB”,$conn);
  6: // create the SQL statement
  7: $sql = “SELECT * FROM testTable”;
  8: // execute the SQL statement
  9: $result = mysql_query($sql, $conn) or die(mysql_error());
 10: //go through each row in the result set and display data
 11: while ($newArray = mysql_fetch_array($result)) {
 12:     // give a name to the fields
 13:     $id = $newArray[’id’];
 14:     $testField = $newArray[’testField’];
 15:     //echo the results onscreen
 16:     echo “The ID is $id and the text is $testField <br>”;
 17: }
 18: ?>

Save this script as select.php, place it in your Web server document directory, and access it through your Web browser.

Essentially, you can create an entire database-driven application using just four or five MySQL functions.


Connecting to MySQL with PHP

Monday, April 14th, 2008

To successfully use the PHP functions to talk to MySQL, you must have MySQL running at a location to which your Web server can connect (not necessarily the same machine as your Web server). You also must have created a user (with a password), and you must know the name of the database to which you want to connect.

Using mysql_connect()

The mysql_connect() function is the first function you must call when utilizing a PHP script to connect to MySQL—without an open connection to MySQL, you won’t get very far! The basic syntax for the connection is

mysql_connect("hostname", "username", "password");

Using actual sample values, the connection function looks like this:

mysql_connect("localhost", "joeuser", "somepass");

This function returns a connection index if the connection is successful or returns false if the connection fails. Below is a working example of a connection script. It assigns the value of the connection index to a variable called $conn, then prints the value of $conn as proof of a connection.

A Simple Connection Script
  1: <?php
  2: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  3: echo “$conn”;
  4: ?>

Save this script as mysqlconnect.php and place it in the document area of your Web server. Access the script with your Web browser and you will see something like the following in your Web browser:

Resource id #1

Connecting to MySQL using the mysql_connect() function is pretty straightforward. The connection closes when the script finishes its execution, but if you would like to explicitly close the connection, simply add the mysql_close() function at the end of the script, as shown below

The Modified Simple Connection Script
  1: <?php
  2: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  3: echo “$conn”;
  4: mysql_close($conn);
  5: ?>

That’s all there is to it. The next section will cover the query execution functions, which are far more interesting than simply opening a connection and letting it sit there!

Executing Queries

Half the battle in executing MySQL queries using PHP is knowing how to write the SQL. The mysql_query() function in PHP is used to send your SQL query to MySQL. If it does so successfully, a result index is returned. If a failure occurs, the function returns false.

When you use the mysql_query() function, you’ll notice that one piece of the puzzle is missing: picking the database to use. When you connect to MySQL through the command-line interface, the database is specified in the connection string or changed manually after you log in. With PHP, this is done via a separate function called mysql_select_db() with the following syntax:

mysql_select_db(database name, connection index);

To connect to a database named testDB, first use mysql_connect(), then use mysql_select_db(), as shown below

Connecting and Selecting a Database
  1: <?php
  2: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  3: mysql_select_db(”testDB”,$conn);
  4: ?>

You now have two important pieces of information: the connection index ($conn) and the knowledge that PHP will use testDB as the database throughout the life of this particular script. The connection index is used in mysql_query() syntax:

mysql_query(query, connection index);

In your script, first make the connection, and then execute a query. The script in below example creates a simple table called testTable.

A Script to Create a Table
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  4: // pick the database to use
  5: mysql_select_db(”testDB”,$conn);
  6: // create the SQL statement
  7: $sql = “CREATE TABLE testTable (id int not null primary key auto_increment,
  8: testField varchar (75))”;
  9: // execute the SQL statement
 10: $result = mysql_query($sql, $conn);
 11: // echo the result identifier
 12: echo $result;
 13: ?>

 

When issuing queries using mysql_query(), the semicolon at the end of the SQL statement is not required. The only semicolon in that line should be at the end of the PHP command.

Because the mysql_query function only returns a true or false result, the boring output of this script is

1

The 1 equals true, and indicates that the query was successfully executed. A 0 would have indicated failure. Access MySQL through the command-line interface to verify the creation of the testTable table:

mysql> describe testTable;

+———–+————-+——+—–+———+—————-+

| Field     | Type        | Null | Key | Default | Extra          |

+———–+————-+——+—–+———+—————-+

| id        | int(11)     |      | PRI | NULL    | auto_increment |

| testField | varchar(75) | YES  |     | NULL    |                |

+———–+————-+——+—–+———+—————-+

2 rows in set (0.00 sec)

Congratulations—you have successfully created a table in your MySQL database using PHP!

Retrieving Error Messages

Take some time to familiarize yourself with the mysql_error() function, as it will become your friend. When used in conjunction with the PHP die() function, which simply exits the script at the point at which it appears, the mysql_error() function will return a helpful error message when you make a mistake.

For example, now that you have created a table called testTable, you won’t be able to execute that script again without an error. Let’s try to execute the script again, but modify it first to utilize the mysql_error() function (see below).

The Script to Create a Table, with Error Messages
  1: <?php
  2: // open the connection
  3: $conn = mysql_connect(”localhost”, “joeuser”, “somepass”);
  4: // pick the database to use
  5: mysql_select_db(”testDB”,$conn);
  6: // create the SQL statement
  7: $sql = “CREATE TABLE testTable (id int not null primary key auto_increment,
  8: testField varchar (75))”;
  9: // execute the SQL statement
 10: $result = mysql_query($sql, $conn) or die(mysql_error());
 11: // echo the result identifier
 12: echo $result;
 13: ?>

When you execute the script, you should see something like the following in your Web browser:

Table 'testTable' already exists


Beginning and Ending a Block of PHP Statements

Saturday, April 12th, 2008

When writing PHP, you need to inform the PHP engine that you want it to execute your commands. If you don’t do this, the code you write will be mistaken for HTML and will be output to the browser. You can designate your code as PHP with special tags that mark the beginning and end of PHP code blocks. Table below shows four such PHP delimiter tags.

Tag Style

Start Tag

End Tag

Standard tags

<?php

?>

Short tags

<?

?>

ASP tags

<%

%>

Script tags

<SCRIPT LANGUAGE=”php”>

</SCRIPT>

 

To activate recognition for short tags, you must make sure that the short_open_tag switch is set to On in php.ini:

short_open_tag = On;

 

To activate recognition for the ASP style tags, you must enable the asp_tags setting:

asp_tags = On;


php.ini Basics

Saturday, April 12th, 2008

After you have compiled or installed PHP, you can still change its behavior with the php.ini file.

Directives in the php.ini file come in two forms: values and flags. Value directives take the form of a directive name and a value separated by an equals sign. Possible values vary from directive to directive. Flag directives take the form of a directive name and a positive or negative term separated by an equals sign. Positive terms include 1, On, Yes, and True. Negative terms include 0, Off, No, and False. Whitespace is ignored.

You can change your php.ini settings at any time, but after you do, you’ll need to restart the server for the changes to take effect.

Testing Your Installation

The simplest way to test your PHP installation is to create a small test script utilizing the phpinfo() function. This function will produce a long list of configuration information. Open a text editor and type the following line:

<? phpinfo(); ?>

Save this file as phpinfo.php and place it in the document root of your Web server—the htdocs subdirectory of your Apache installation. Access this file via your Web browser .


output-control functions

Thursday, April 10th, 2008

As with anything that outputs its result directly to the browser, you can use the output-control functions to capture the output of this function.

<?phpob_start();
echo 
“Hello\n”;
setcookie(“cookiename”“cookiedata”); ob_end_flush();?>
 

In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

<?php

ob_start();

echo “Hello World”;

$out ob_get_clean();
$out strtolower($out
);

var_dump($out);
?>

The above example will output:

string(11) "hello world"


function get_resource_type()

Thursday, April 10th, 2008

(PHP 4 >= 4.0.2, PHP 5)

string get_resource_type ( resource $handle )

This function returns the type of the given resource.

If the given handle is a resource, this function will return a string representing its type. If the type is not identified by this function, the return value will be the string Unknown.

<?php
// prints: mysql link
$c mysql_connect();
echo 
get_resource_type($c) . “\n”;
// prints: file
$fp fopen(“foo”“w”);
echo 
get_resource_type($fp) . “\n”;
// prints: domxml document
$doc new_xmldoc(“1.0″);
echo 
get_resource_type($doc->doc) . “\n”;
?>