Share Knowledge and Skills

Saturday 4 October 2014

PHP

12:10 Posted by Unknown No comments

Source From 
http://www.php.net/manual/en/tutorial.forms.php
http://www.ebooksfreedirectory.com/index.php?c=21


Preface
Abstract
PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.
Authors and Contributors
We highlight the currently most active people on the manual frontpage, but there are many more contributors who currently help in our work or provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with their user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All the lists provided below are in alphabetical order.
Authors and Editors
The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Hannes Magnusson, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar and Andrei Zmievski.
The following contributors have done significant work editing the manual: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe and Egon Schmid.
User Note Maintainers   
The currently most active maintainers are: Mehdi Achour, Friedhelm Betz, Etienne Kneuss, Nuno Lopes, Hannes Magnusson, Bobby Matthis and Philip Olson.
These people have also put a lot of effort into managing user notes: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Maciek Sokolewicz, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.

What is PHP?
PHP (recursive acronym for "PHP: Hypertext Preprocessor") is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML.
What can PHP do?
Anything. PHP is mainly focused on server-side scripting, so you can do anything any other CGI program can do, such as collect form data, generate dynamic page content, or send and receive cookies. But PHP can do much more.
There are three main areas where PHP scripts are used.
    Server-side scripting. This is the most traditional and main target field for PHP. You need three things to make this work. The PHP parser (CGI or server module), a web server and a web browser. You need to run the web server, with a connected PHP installation. You can access the PHP program output with a web browser, viewing the PHP page through the server. All these can run on your home machine if you are just experimenting with PHP programming. See the installation instructions section for more information.
    Command line scripting. You can make a PHP script to run it without any server or browser. You only need the PHP parser to use it this way. This type of usage is ideal for scripts regularly executed using cron (on *nix or Linux) or Task Scheduler (on Windows). These scripts can also be used for simple text processing tasks. See the section about Command line usage of PHP for more information.
    Writing desktop applications. PHP is probably not the very best language to create a desktop application with a graphical user interface, but if you know PHP very well, and would like to use some advanced PHP features in your client-side applications you can also use PHP-GTK to write such programs. You also have the ability to write cross-platform applications this way. PHP-GTK is an extension to PHP, not available in the main distribution. If you are interested in PHP-GTK, visit » its own website.
PHP can be used on all major operating systems, including Linux, many Unix variants (including HP-UX, Solaris and OpenBSD), Microsoft Windows, Mac OS X, RISC OS, and probably others. PHP has also support for most of the web servers today. This includes Apache, Microsoft Internet Information Server, Personal Web Server, Netscape and iPlanet servers, Oreilly Website Pro server, Caudium, Xitami, OmniHTTPd, and many others. For the majority of the servers PHP has a module, for the others supporting the CGI standard, PHP can work as a CGI processor.
So with PHP, you have the freedom of choosing an operating system and a web server. Furthermore, you also have the choice of using procedural programming or object oriented programming, or a mixture of them. Although not every standard OOP feature is implemented in PHP 4, many code libraries and large applications (including the PEAR library) are written only using OOP code. PHP 5 fixes the OOP related weaknesses of PHP 4, and introduces a complete object model.
With PHP you are not limited to output HTML. PHP's abilities includes outputting images, PDF files and even Flash movies (using libswf and Ming) generated on the fly. You can also output easily any text, such as XHTML and any other XML file. PHP can autogenerate these files, and save them in the file system, instead of printing it out, forming a server-side cache for your dynamic content.
One of the strongest and most significant features in PHP is its support for a wide range of databases. Writing a database-enabled web page is incredibly simple. The following databases are currently supported:
Adabas D    InterBase    PostgreSQL
dBase    FrontBase    SQLite
Empress    mSQL    Solid
FilePro (read-only)    Direct MS-SQL    Sybase
Hyperwave    MySQL    Velocis
IBM DB2    ODBC    Unix dbm
Informix    Oracle (OCI7 and OCI8)   
Ingres    Ovrimos   
We also have a database abstraction extension (named PDO) allowing you to transparently use any database supported by that extension. Additionally PHP supports ODBC, the Open Database Connection standard, so you can connect to any other database supporting this world standard.
PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (on Windows) and countless others. You can also open raw network sockets and interact using any other protocol. PHP has support for the WDDX complex data exchange between virtually all Web programming languages. Talking about interconnection, PHP has support for instantiation of Java objects and using them transparently as PHP objects. You can also use our CORBA extension to access remote objects.
PHP has extremely useful text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents. For parsing and accessing XML documents, PHP 4 supports the SAX and DOM standards, and you can also use the XSLT extension to transform XML documents. PHP 5 standardizes all the XML extensions on the solid base of libxml2 and extends the feature set adding SimpleXML and XMLReader support.
At last but not least, we have many other interesting extensions, the mnoGoSearch search engine functions, the IRC Gateway functions, many compression utilities (gzip, bz2, zip), calendar conversion, translation...
As you can see this page is not enough to list all the features and benefits PHP can offer. Read on in the sections about installing PHP, and see the function reference part for explanation of the extensions mentioned here.


Here we would like to show the very basics of PHP in a short, simple tutorial. This text only deals with dynamic web page creation with PHP, though PHP is not only capable of creating web pages. See the section titled What can PHP do for more information.
PHP-enabled web pages are treated just like regular HTML pages and you can create and edit them the same way you normally create regular HTML pages.
What do I need?
In this tutorial we assume that your server has activated support for PHP and that all files ending in .php are handled by PHP. On most servers, this is the default extension for PHP files, but ask your server administrator to be sure. If your server supports PHP, then you do not need to do anything. Just create your .php files, put them in your web directory and the server will automatically parse them for you. There is no need to compile anything nor do you need to install any extra tools. Think of these PHP-enabled files as simple HTML files with a whole new family of magical tags that let you do all sorts of things. Most web hosts offer PHP support, but if your host does not, consider reading the » PHP Links section for resources on finding PHP enabled web hosts.
Let us say you want to save precious bandwidth and develop locally. In this case, you will want to install a web server, such as » Apache, and of course » PHP. You will most likely want to install a database as well, such as » MySQL.
You can either install these individually or choose a simpler way. Our manual has installation instructions for PHP (assuming you already have some web server set up). In case you have problems with installing PHP yourself, we would suggest you ask your questions on our » installation mailing list. If you choose to go on the simpler route, then » locate a pre-configured package for your operating system, which automatically installs all of these with just a few mouse clicks. It is easy to setup a web server with PHP support on any operating system, including MacOSX, Linux and Windows. On Linux, you may find » rpmfind and » PBone helpful for locating RPMs. You may also want to visit » apt-get to find packages for Debian.



Your first PHP-enabled page
Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:
Example 2.1. Our first PHP script: hello.php
<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?>
 </body>
</html>
Use your browser to access the file with your web server's URL, ending with the "/hello.php" file reference. When developing locally this URL will be something like http://localhost/hello.php or http://127.0.0.1/hello.php but this depends on the web server's configuration. If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>

    

This program is extremely simple and you really did not need to use PHP to create a page like this. All it does is display: Hello World using the PHP echo() statement. Note that the file does not need to be executable or special in any way. The server finds out that this file needs to be interpreted by PHP because you used the ".php" extension, which the server is configured to pass on to PHP. Think of this as a normal HTML file which happens to have a set of special tags available to you that do a lot of interesting things.
If you tried this example and it did not output anything, it prompted for download, or you see the whole file as text, chances are that the server you are on does not have PHP enabled, or is not configured properly. Ask your administrator to enable it for you using the Installation chapter of the manual. If you are developing locally, also read the installation chapter to make sure everything is configured properly. Make sure that you access the file via http with the server providing you the output. If you just call up the file from your file system, then it will not be parsed by PHP. If the problems persist anyway, do not hesitate to use one of the many » PHP support options.
The point of the example is to show the special PHP tag format. In this example we used <?php to indicate the start of a PHP tag. Then we put the PHP statement and left PHP mode by adding the closing tag, ?>. You may jump in and out of PHP mode in an HTML file like this anywhere you want. For more details, read the manual section on the basic PHP syntax.
A Note on Line Feeds: A Note on Line Feeds
Line feeds have little meaning in HTML, however it is still a good idea to make your HTML look nice and clean by putting line feeds in. A linefeed that follows immediately after a closing ?> will be removed by PHP. This can be extremely useful when you are putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything. At the same time it can be a bit confusing. You can put a space after the closing ?> to force a space and a line feed to be output, or you can put an explicit line feed in the last echo/print from within your PHP block.
A Note on Text Editors: A Note on Text Editors
There are many text editors and Integrated Development Environments (IDEs) that you can use to create, edit and manage PHP files. A partial list of these tools is maintained at » PHP Editors List. If you wish to recommend an editor, please visit the above page and ask the page maintainer to add the editor to the list. Having an editor with syntax highlighting can be helpful.
A Note on Word Processors: A Note on Word Processors
Word processors such as StarOffice Writer, Microsoft Word and Abiword are not optimal for editing PHP files. If you wish to use one for this test script, you must ensure that you save the file as plain text or PHP will not be able to read and execute the script.
A Note on Windows Notepad: A Note on Windows Notepad
If you are writing your PHP scripts using Windows Notepad, you will need to ensure that your files are saved with the .php extension. (Notepad adds a .txt extension to files automatically unless you take one of the following steps to prevent it.) When you save the file and are prompted to provide a name for the file, place the filename in quotes (i.e. "hello.php"). Alternatively, you can click on the 'Text Documents' drop-down menu in the 'Save' dialog box and change the setting to "All Files". You can then enter your filename without quotes.
Now that you have successfully created a working PHP script, it is time to create the most famous PHP script! Make a call to the phpinfo() function and you will see a lot of useful information about your system and setup such as available predefined variables, loaded PHP modules, and configuration settings. Take some time and review this important information.


Something Useful
Let us do something more useful now. We are going to check what sort of browser the visitor is using. For that, we check the user agent string the browser sends as part of the HTTP request. This information is stored in a variable. Variables always start with a dollar-sign in PHP. The variable we are interested in right now is $_SERVER['HTTP_USER_AGENT'].
Note: $_SERVER is a special reserved PHP variable that contains all web server information. It is known as a superglobal. See the related manual page on superglobals for more information. These special variables were introduced in PHP » 4.1.0. Before this time, we used the older $HTTP_*_VARS arrays instead, such as $HTTP_SERVER_VARS. Although deprecated, these older variables still exist. (See also the note on old code.)
To display this variable, you can simply do:
Example 2.3. Printing a variable (Array element)
<?php
echo $_SERVER['HTTP_USER_AGENT'];
?>
A sample output of this script may be:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
   

There are many types of variables available in PHP. In the above example we printed an Array element. Arrays can be very useful.
$_SERVER is just one variable that PHP automatically makes available to you. A list can be seen in the Reserved Variables section of the manual or you can get a complete list of them by looking at the output of the phpinfo() function used in the example in the previous section.
You can put multiple PHP statements inside a PHP tag and create little blocks of code that do more than just a single echo. For example, if you want to check for Internet Explorer you can do this:
Example 2.4. Example using control structures and functions
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo 'You are using Internet Explorer.<br />';
}
?>
A sample output of this script may be:

You are using Internet Explorer.<br />

    

Here we introduce a couple of new concepts. We have an if statement. If you are familiar with the basic syntax used by the C language, this should look logical to you. Otherwise, you should probably pick up an introductory PHP book and read the first couple of chapters, or read the Language Reference part of the manual.
The second concept we introduced was the strpos() function call. strpos() is a function built into PHP which searches a string for another string. In this case we are looking for 'MSIE' (so-called needle) inside $_SERVER['HTTP_USER_AGENT'] (so-called haystack). If the needle is found inside the haystack, the function returns the position of the needle relative to the start of the haystack. Otherwise, it returns FALSE. If it does not return FALSE, the if expression evaluates to TRUE and the code within its {braces} is executed. Otherwise, the code is not run. Feel free to create similar examples, with if, else, and other functions such as strtoupper() and strlen(). Each related manual page contains examples too. If you are unsure how to use functions, you will want to read both the manual page on how to read a function definition and the section about PHP functions.
We can take this a step further and show how you can jump in and out of PHP mode even in the middle of a PHP block:
Example 2.5. Mixing both HTML and PHP modes
<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>
<?php
} else {
?>
<h3>strpos() must have returned false</h3>
<p>You are not using Internet Explorer</p>
<?php
}
?>
A sample output of this script may be:

<h3>strpos() must have returned non-false</h3>
<p>You are using Internet Explorer</p>

    

Instead of using a PHP echo statement to output something, we jumped out of PHP mode and just sent straight HTML. The important and powerful point to note here is that the logical flow of the script remains intact. Only one of the HTML blocks will end up getting sent to the viewer depending on the result of strpos(). In other words, it depends on whether the string MSIE was found or not.



Dealing with Forms   Your first PHP-enabled page
________________________________________
Last updated: Mon, 17 Sep 2007
 
 add a note User Contributed Notes
Something Useful
john dot t dot gold at gmail dot com
30-Aug-2007 03:55
<html>
 <head>
  <title>A List of All Those Vaiables Variables you get</title>
 </head>
 <body>
<table border=1>
<tr><td align=center>Array Name</td><td align=center>Array Contents</td></tr>
 <?php

foreach ($GLOBALS as $k => $v)
{
if (is_array($v))
{   
    echo "<tr><td>$".$k."</td><td><table>\n";
    if (count($v)>0)
    {
      echo "<tr><td><b>Index Syntax</b></td><td>&nbsp;</td><td><b>Current Value</b></td></tr>";
    }
    foreach ($v as $key => $value)
    {
        echo "<tr><td>['".$key."']</td><td>=</td><td>".$value."</td></tr>\n";

    }
    echo "</table></td></tr>\n";
}
ELSE
{
    echo "<tr><td>$".$k."</td><td>".$v."</td></tr>\n";
}
}

?>
</table>
 </body>
</html>
dexxter at NOSPAMSPACER dot quantentunnel dot de
29-Jan-2007 04:42
What "rfantin" described in his/her post is commonly known as the MVC pattern. Might want to check out the following link for details http://en.wikipedia.org/wiki/Model-view-controller
rfantin at coralwood dot com
20-Dec-2006 10:00
While it's easy to get carried away mixing your logic and presentation together since it's so easy to do, your better off using PHP within HTML only to fill in values, or include other source files.

Keep your actual processing in separate libraries that are called before you send any headers to the page. Try to avoid calling a script that retrieves or sets information, or manipulates it in the middle of your HTML. You'll find it's much easier to maintain.

Dealing with Forms
One of the most powerful features of PHP is the way it handles HTML forms. The basic concept that is important to understand is that any form element will automatically be available to your PHP scripts. Please read the manual section on Variables from outside of PHP for more information and examples on using forms with PHP. Here is an example HTML form:
Example 2.6. A simple HTML form

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>
</form>

    

There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:
Example 2.7. Printing data from our form
Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.
A sample output of this script may be:

Hi Joe. You are 22 years old.

    

Apart from the htmlspecialchars() and (int) parts, it should be obvious what this does. htmlspecialchars() makes sure any characters that are special in html are properly encoded so people can't inject HTML tags or Javascript into your page. For the age field, since we know it is a number, we can just convert it to an integer which will automatically get rid of any stray characters. You can also have PHP do this for you automatically by using the filter extension. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER superglobal; above we just introduced the $_POST superglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET superglobal instead. You may also use the $_REQUEST superglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data. Also see the import_request_variables() function.
You can also deal with XForms input in PHP, although you will find yourself comfortable with the well supported HTML forms for quite some time. While working with XForms is not for beginners, you might be interested in them. We also have a short introduction to handling data received from XForms in our features section.



Using old code with new versions of PHP   Something Useful
________________________________________
Last updated: Mon, 17 Sep 2007
 
 add a note User Contributed Notes
Dealing with Forms
maheshs60 at gmail dot com
30-Jul-2007 10:46
Here is a PHP script to add more form fields in a page by clicking on a button on the same page.You can add unlimited number of fields dynamically(in run time) in a page by using this script.
(For the alligning of form fields,forms are given in layers)
<html>
<style type="text/css">
#Layer1 {
    position:absolute;
    left:413px;
    top:123px;
    width:203px;
    height:35px;
    z-index:1;
}
#Layer2 {
    position:absolute;
    left:21px;
    top:122px;
    width:389px;
    height:50px;
    z-index:2;
}
</style>
<body>
<?
$n=0;
$n1=$_POST['hf'];
if($n1>=$n){
$t=$n1;}
else{
$t=$n;}
/*For example this script allows user to add more and more file upload fields in a page by clicking on a button*/
?>
<!--creating a form--><!--save this page as "upload.php" -->
<div id="Layer1">
  <form name="form1" method="post" action="upload.php">
<!--creating a hidden field and sets it's value as $t-->
    <input name="hf" type="hidden" id="hf" value="<? echo ++$t; ?>">
<!--creating a button.When we click this, a new field will be generated-->
    <input type="submit" name="Submit" value="one more">
      </form>
<!--another form to submit the uploaded file to be processed-->
<!--the upload script should be written in the file "uploader.php"-->
</div>
<div id="Layer2">
<form action="uploader.php" method="post" enctype="multipart/form-data">
  <p>
  <?
  $i=0;
  while($i<$t){
  echo "Filename:"
  ?>
  <label for="file">
   
    <input type="file" name="file" id="file" >
  <input type="submit" name="submit" value="Submit" >
  <?++$i;}?>

</form>
</div>
</body>
</html>

Like this, you can add any type of form field into the same page by the click of a button.
danrulz98 at yahoo dot com
30-Apr-2007 08:40
If you use ALL of the code above, it works fine. If you misspell "method" it will use $_GET by default ( it did on my server anyway). Make sure you use a spell check.
danrulz98 at yahoo dot com
30-Apr-2007 08:24
In the sample above, the code dose not work. Even if you copy and paste the sample code you will get:

Hi . You are 0 years old

The code should look more like this on the main page:

<?php echo '<p>Hello World</p>'; ?>
<form action="action.php" methhod="get">
<p>Your name: <input type="text" name="name" /></p>
<p>your age: <input type="text" name="age" /></p>
<p><input type="submit" /></p>

Then the action page should look like this:

Hi <?php echo htmlspecialchars($_GET['name']); ?>.
You are <?php echo (int)$_GET['age']; ?> years old
SvendK
08-Nov-2006 08:02
As Seth mentions, when a user clicks reload or goes back with the browser button, data sent to the server, may be sent again (after a click on the ok button).

It might be wise, to let the server handle whatever there is to handle, and then redirect (a redirect is not visible in the history and thus not reachable via reload or "back".

It cannot be used in this exact example, but as Seth also mentions, this example should be using GET instead of POST
yasman at phplatvia dot lv
05-May-2005 12:18
[Editor's Note: Since "." is not legal variable name PHP will translate the dot to underscore, i.e. "name.x" will become "name_x"]

Be careful, when using and processing forms which contains
<input type="image">
tag. Do not use in your scripts this elements attributes `name` and `value`, because MSIE and Opera do not send them to server.
Both are sending `name.x` and `name.y` coordiante variables to a server, so better use them.
sethg at ropine dot com
01-Dec-2003 12:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything.  For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.

Using old code with new versions of PHP
Now that PHP has grown to be a popular scripting language, there are a lot of public repositories and libraries containing code you can reuse. The PHP developers have largely tried to preserve backwards compatibility, so a script written for an older version will run (ideally) without changes in a newer version of PHP. In practice, some changes will usually be needed.
Two of the most important recent changes that affect old code are:
    The deprecation of the old $HTTP_*_VARS arrays (which need to be indicated as global when used inside a function or method). The following superglobal arrays were introduced in PHP » 4.1.0. They are: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST, and $_SESSION. The older $HTTP_*_VARS arrays, such as $HTTP_POST_VARS, still exist as they have since PHP 3. As of PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays directive.
    External variables are no longer registered in the global scope by default. In other words, as of PHP » 4.2.0 the PHP directive register_globals is off by default in php.ini. The preferred method of accessing these values is via the superglobal arrays mentioned above. Older scripts, books, and tutorials may rely on this directive being on. If it were on, for example, one could use $id from the URL http://www.example.com/foo.php?id=42. Whether on or off, $_GET['id'] is available.
For more details on these changes, see the section on predefined variables and links therein.

 add a note User Contributed Notes
Using old code with new versions of PHP
dreamer
02-May-2007 06:31
When in your server the PHP directive register_globals is off, you can use function extract() to quickly create the short name for your variables. For example...

<?php

extract($_GET);

echo $id;

?>

But remember, this method is not out of danger, just like register_globals = on.


What's next?
With your new knowledge you should be able to understand most of the manual and also the various example scripts available in the example archives. You can also find other examples on the php.net websites in the links section: » http://www.php.net/links.php.
To view various slide presentations that show more of what PHP can do, see the PHP Conference Material Sites: » http://conf.php.net/ and » http://talks.php.net/


Part II. Installation and Configuration
Table of Contents
3. General Installation Considerations
4. Installation on Unix systems
5. Installation on Mac OS X
6. Installation on Windows systems
7. Installation of PECL extensions
8. Problems?
9. Runtime Configuration




Chapter 3. General Installation Considerations
Before starting the installation, first you need to know what do you want to use PHP for. There are three main fields you can use PHP, as described in the What can PHP do? section:
    Websites and web applications (server-side scripting)
    Command line scripting
    Desktop (GUI) applications
For the first and most common form, you need three things: PHP itself, a web server and a web browser. You probably already have a web browser, and depending on your operating system setup, you may also have a web server (e.g. Apache on Linux and MacOS X; IIS on Windows). You may also rent webspace at a company. This way, you don't need to set up anything on your own, only write your PHP scripts, upload it to the server you rent, and see the results in your browser.
In case of setting up the server and PHP on your own, you have two choices for the method of connecting PHP to the server. For many servers PHP has a direct module interface (also called SAPI). These servers include Apache, Microsoft Internet Information Server, Netscape and iPlanet servers. Many other servers have support for ISAPI, the Microsoft module interface (OmniHTTPd for example). If PHP has no module support for your web server, you can always use it as a CGI or FastCGI processor. This means you set up your server to use the CGI executable of PHP to process all PHP file requests on the server.
If you are also interested to use PHP for command line scripting (e.g. write scripts autogenerating some images for you offline, or processing text files depending on some arguments you pass to them), you always need the command line executable. For more information, read the section about writing command line PHP applications. In this case, you need no server and no browser.
With PHP you can also write desktop GUI applications using the PHP-GTK extension. This is a completely different approach than writing web pages, as you do not output any HTML, but manage Windows and objects within them. For more information about PHP-GTK, please » visit the site dedicated to this extension. PHP-GTK is not included in the official PHP distribution.
From now on, this section deals with setting up PHP for web servers on Unix and Windows with server module interfaces and CGI executables. You will also find information on the command line executable in the following sections.
PHP source code and binary distributions for Windows can be found at » http://www.php.net/downloads.php. We recommend you to choose a » mirror nearest to you for downloading the distributions.


Chapter 4. Installation on Unix systems
Table of Contents
Apache 1.3.x on Unix systems
Apache 2.0 on Unix systems
Caudium
fhttpd related notes
Sun, iPlanet and Netscape servers on Sun Solaris
CGI and command line setups
HP-UX specific installation notes
OpenBSD installation notes
Solaris specific installation tips
Debian GNU/Linux installation notes
This section will guide you through the general configuration and installation of PHP on Unix systems. Be sure to investigate any sections specific to your platform or web server before you begin the process.
As our manual outlines in the General Installation Considerations section, we are mainly dealing with web centric setups of PHP in this section, although we will cover setting up PHP for command line usage as well.
There are several ways to install PHP for the Unix platform, either with a compile and configure process, or through various pre-packaged methods. This documentation is mainly focused around the process of compiling and configuring PHP. Many Unix like systems have some sort of package installation system. This can assist in setting up a standard configuration, but if you need to have a different set of features (such as a secure server, or a different database driver), you may need to build PHP and/or your web server. If you are unfamiliar with building and compiling your own software, it is worth checking to see whether somebody has already built a packaged version of PHP with the features you need.
Prerequisite knowledge and software for compiling:
    Basic Unix skills (being able to operate "make" and a C compiler)
    An ANSI C compiler
    flex: Version 2.5.4
    bison: Version 1.28 (preferred), 1.35, or 1.75
    A web server
    Any module specific components (such as gd, pdf libs, etc.)
The initial PHP setup and configuration process is controlled by the use of the command line options of the configure script. You could get a list of all available options along with short explanations running ./configure --help. Our manual documents the different options separately. You will find the core options in the appendix, while the different extension specific options are descibed on the reference pages.
When PHP is configured, you are ready to build the module and/or executables. The command make should take care of this. If it fails and you can't figure out why, see the Problems section.
Apache 1.3.x on Unix systems
This section contains notes and hints specific to Apache installs of PHP on Unix platforms. We also have instructions and notes for Apache 2 on a separate page.
You can select arguments to add to the configure on line 10 below from the list of core configure options and from extension specific options described at the respective places in the manual. The version numbers have been omitted here, to ensure the instructions are not incorrect. You will need to replace the 'xxx' here with the correct values from your files.
Example 4.1.  Installation Instructions (Apache Shared Module Version) for PHP

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx

10. Now, configure your PHP.  This is where you customize your PHP
    with various options, like which extensions will be enabled.  Do a
    ./configure --help for a list of available options.  In our example
    we'll do a simple configure with Apache 1 and MySQL support.  Your
    path to apxs may differ from our example.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

    If you decide to change your configure options after installation,
    you only need to repeat the last three steps. You only need to
    restart apache for the new module to take effect. A recompile of
    Apache is not needed.
 
    Note that unless told otherwise, 'make install' will also install PEAR,
    various PHP tools such as phpize, install the PHP CLI, and more.

13. Setup your php.ini file:

      cp php.ini-dist /usr/local/lib/php.ini

    You may edit your .ini file to set PHP options.  If you prefer your
    php.ini in another location, use --with-config-file-path=/some/path in
    step 10.
   
    If you instead choose php.ini-recommended, be certain to read the list
    of changes within, as they affect how PHP behaves.

14. Edit your httpd.conf to load the PHP module.  The path on the right hand
    side of the LoadModule statement must point to the path of the PHP
    module on your system.  The make install from above may have already
    added this for you, but be sure to check.
       
    For PHP 4:
           
      LoadModule php4_module libexec/libphp4.so

    For PHP 5:
                     
      LoadModule php5_module libexec/libphp5.so
     
15. And in the AddModule section of httpd.conf, somewhere under the
    ClearModuleList, add this:
   
    For PHP 4:
   
      AddModule mod_php4.c
     
    For PHP 5:
   
      AddModule mod_php5.c

16. Tell Apache to parse certain extensions as PHP.  For example,
    let's have Apache parse the .php extension as PHP.  You could
    have any extension(s) parse as PHP by simply adding more, with
    each separated by a space.  We'll add .phtml to demonstrate.

      AddType application/x-httpd-php .php .phtml

    It's also common to setup the .phps extension to show highlighted PHP
    source, this can be done with:
   
      AddType application/x-httpd-php-source .phps

17. Use your normal procedure for starting the Apache server. (You must
    stop and restart the server, not just cause the server to reload by
    using a HUP or USR1 signal.)

    

Alternatively, to install PHP as a static object:
Example 4.2.  Installation Instructions (Static Module Installation for Apache) for PHP

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-5.x.y.tar.gz | tar xf -
6.  cd php-5.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
    (The above line is correct! Yes, we know libphp5.a does not exist at this
    stage. It isn't supposed to. It will be created.)

12. make
    (you should now have an httpd binary which you can copy to your Apache bin dir if
    it is your first install then you need to "make install" as well)

13. cd ../php-5.x.y
14. cp php.ini-dist /usr/local/lib/php.ini

15. You can edit /usr/local/lib/php.ini file to set PHP options.
    Edit your httpd.conf or srm.conf file and add:
    AddType application/x-httpd-php .php

     

Note: Replace php-5 by php-4 and php5 by php4 in PHP 4.
Depending on your Apache install and Unix variant, there are many possible ways to stop and restart the server. Below are some typical lines used in restarting the server, for different apache/unix installations. You should replace /path/to/ with the path to these applications on your systems.
Example 4.3. Example commands for restarting Apache

1. Several Linux and SysV variants:
/etc/rc.d/init.d/httpd restart

2. Using apachectl scripts:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl and httpsdctl (Using OpenSSL), similar to apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Using mod_ssl, or another SSL server, you may want to manually
stop and start:
/path/to/apachectl stop
/path/to/apachectl startssl

      

The locations of the apachectl and http(s)dctl binaries often vary. If your system has locate or whereis or which commands, these can assist you in finding your server control programs.
Different examples of compiling PHP for apache are as follows:

./configure --with-apxs --with-pgsql

      
This will create a libphp5.so (or libphp4.so in PHP 4) shared library that is loaded into Apache using a LoadModule line in Apache's httpd.conf file. The PostgreSQL support is embedded into this library.

./configure --with-apxs --with-pgsql=shared

      
This will create a libphp4.so shared library for Apache, but it will also create a pgsql.so shared library that is loaded into PHP either by using the extension directive in php.ini file or by loading it explicitly in a script using the dl() function.

./configure --with-apache=/path/to/apache_source --with-pgsql

      
This will create a libmodphp5.a library, a mod_php5.c and some accompanying files and copy this into the src/modules/php5 directory in the Apache source tree. Then you compile Apache using --activate-module=src/modules/php5/libphp5.a and the Apache build system will create libphp5.a and link it statically into the httpd binary (replace php5 by php4 in PHP 4). The PostgreSQL support is included directly into this httpd binary, so the final result here is a single httpd binary that includes all of Apache and all of PHP.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

      
Same as before, except instead of including PostgreSQL support directly into the final httpd you will get a pgsql.so shared library that you can load into PHP from either the php.ini file or directly using dl().
When choosing to build PHP in different ways, you should consider the advantages and drawbacks of each method. Building as a shared object will mean that you can compile apache separately, and don't have to recompile everything as you add to, or change, PHP. Building PHP into apache (static method) means that PHP will load and run faster. For more information, see the Apache » web page on DSO support.
Note: Apache's default httpd.conf currently ships with a section that looks like this:

User nobody
Group "#-1"

      
Unless you change that to "Group nogroup" or something like that ("Group daemon" is also very common) PHP will not be able to open files.
Note: Make sure you specify the installed version of apxs when using --with-apxs=/path/to/apxs. You must NOT use the apxs version that is in the apache sources but the one that is actually installed on your system.



Apache 2.0 on Unix systems   General Installation Considerations
________________________________________
Last updated: Mon, 17 Sep 2007
 
 add a note User Contributed Notes
Installation on Unix systems
aryeh dot friedman at gmail dot com
13-Sep-2007 04:05
For all multi-core processors (not just Sun as noted above) you need to add --enable-shared-core to the apache config
moonlightcheese
23-Aug-2007 05:49
There is little or no documentation regarding the fact that MySQL Client Library isn't bundled with PHP anymore.  The installation instructions need to be changed with, at the very least, some instructions for how to get PHP to recognize that the client library is installed.  I realize that this may be a problem with licensing and as such, it's not possible to document too much regarding MySQL...

I personally fumbled around with PHPNuke for a day or two before realizing that I was getting blank pages due to database problems.  It would be nice to have a ./config option like --with-mysql-client-library='/path/to/libmysqlclient.so' at the very least... i still can't get PHP to recognize where the mysql client library is and MySQL's documentation is jumbled at best...
Alex at GrimMusic dot com
13-Nov-2006 12:49
In response to the guy who posted about the SELinux:

I am new to linux/apache/php (coming from server 2003/IIS/Asp.Net), so i was stumped as to why php/apache could only use static content. Also, it couldn't access some documents that you created somewhere else, and then dragged into the HTML directory.

After some research, i found the problem was the SELinux context of the files. It took me forever to find the Proper command to use to change that, as all the examples on the net were out dated using old commands:
# chcon "user_u:object_r:httpd_sys_content_t" /var/www/html -Rc

This will change the SELinux context of all the documents under the /var/www/html directory (which is the web directory under Fedora), to allow the httpd process to access them, and the '-Rc' flag will make the changes Recursive, and will output it's progress for each file that it sucessfully changes.
squeegee
30-Sep-2006 09:24
regarding the note by phptard at gmail dot com:

This was a good starting point to get php built against the Intel-compiled mysql, but in my case, there were still errors. It wasn't until I also added LIBS="-lirc" to the beginning of the configure line that it would configure without errors. It also compiled fine after that. So the start of my configure line looked like this:

LDFLAGS="-lirc" LIBS="-lirc" EXTRA_LIBS="-lirc" ./configure
Arjan van Bentem
12-Jul-2006 12:29
When using Red Hat Fedora, beware of Security Enhanced Linux, SELinux.

Quoted from Red Hat: "The security goal is to make sure that Apache HTTP is only reading the static Web content, and not doing anything else such as writing to the content, connecting to database sockets, reading user home directories, etc."

These limitations include, among many other things, using mkdir to create directories, using fopen to access files, using fopen or get_headers to read URLs, or using exec to run external applications that happen to use sockets (or maybe access some files, but which will run fine when executed from the command line as Unix user apache or httpd -- such as HylaFAX "faxstat" as invoked from nweb2fax recvq.php and sendq.php).

See /var/log/messages for any denials due to the SELinux policy. To disable it:

- System, Administration, Security Level and Firewall
- open the SELinux tab
- click the Transition tree
- check Disable SELinux protection for Apache HTTP
- execute /etc/init.d/httpd restart

See also http://fedora.redhat.com/docs/selinux-faq/ and http://php.net/results.php?q=selinux&p=wholesite
flconseil at yahoo dot fr
07-Mar-2006 06:15
Building Apache 2 and PHP 5.1.2 :

On AIX 5.2 : http://flaupretre.free.fr/redir.php?key=build_apa_aix

On HP-UX 11i (11.11) : http://flaupretre.free.fr/redir.php?key=build_apa_hpux

These documents are complete step-by-step howtos, and describe how to buid a self-sufficient package, including every software it depends on (zlib, SSL, LDAP, iconv, expat, xml, xslt, gd, png, Xpm, jpeg, freetype, bzip2, curl, MySQL, PostgreSQL, Oracle, AdoDB).
dpresley4 at yahoo dot com
06-Nov-2005 03:42
Hi,

PROBLEM:  ./configure PHP --with-oci8

fails with unresolved references such as __rpc_thread_destroy@GLIBC_2_2_3_...

ONE SOLUTOIN

FOR SOLVING PHP ./configure RESULTING IN  __rcp_thread_destroy@GLIBC_2_2_3_... AND
UNRESOLVED REFERENCES WITH ORACLE OCI8

KEYWORDS: PHP OCI OCI8 NET8 ./configure __rpc_thred_destroy UNRESOLVED REFERENCES

For building php-4.4.1 or later with oci8, make sure your LD_LIBARRY_PATH has at a minimum the following directories in its path for Oracle8i 8.1.5 or later, Oracle9i 9.0.2 or later, and Oracle9i Release 2: 9.2.0.4 or later, do the following:

Note:  We are not using the Oracle Instant Client here.  This assumes you have an actual Oracle Installation.

1. Set ORACLE_HOME

Example using Oracle 9i Relase 2 -- 9.2.0.5:

ORACLE_HOME=/opt/app/oracle/product/9iR2

2. Set LD_LIBRARY_PATH with:

LD_LIBRARY_PATH=$ORACLE_HOME/lib: \
    $ORACLE_HOME/rdbms/lib:\
    $LD_LIBRARY_PATH

3. On Unix / Linux, don't forget to export these environment variables:

export ORACLE_HOME LD_LIBRARY_PATH

4. Now, build PHP with the following:

./configure --with-apxs2=<path to Apache 2.0/bin/apxs> --with-oci8=$ORACLE_HOME --enable-sigchild

It should now build correctly. The key with Oracle is to ensure that you pick up the libclntX.so (client librariess) where X is the Oracle version associated with the version your using for instance, in the above example, libclnt9.so

Also note that if your using Oracle 9iAS Release 2 v9.0.2, Oracle 10g iAS Release 1 v9.0.4.1, the above steps will work because ORACLE_HOME will containe all of the libraries necessary.  Simply point ORACLE_HOME to the top level directory of these installations and set LD_LIBRARY_PATH as described above.

Hope this helps.
phptard at gmail dot com
23-Mar-2005 04:17
after a long night of wrestling with mysql4.0 under linux compiled with the intel compiler, i've gotten php5.0.3 to compile with mysql libraries for this flavor of mysql:

1: download the mysql for linux/intel compiler and install
2: download the rpm for the intel compiler libraries and install
3: configure php with LDFLAGS="-lirc -lgcc_s" and EXTRA_LIBS="-lirc -lgcc_s"

Example:

LDFLAGS="-lirc -lgcc_s" LD_LIBRARY_PATH="-L/usr/lib64" LD_PATH="-L/usr/lib64" LDPATH="-L/usr/lib64" EXTRA_LIBS="-lirc -lgcc_s" ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-ssl=/usr/local/ssl --without-sqlite --with-zlib-dir=/usr --with-mysql=/usr/local/mysql

of course this is on a xeon system that has half of its modules in the /usr/lib64 directory, so on a normal system, without the other kruft, it would look something more like this:

LDFLAGS="-lirc -lgcc_s" EXTRA_LIBS="-lirc -lgcc_s" ./configure --with-apxs2=/usr/local/apache/bin/apxs --with-mysql=/usr/local/mysql

Hopefully this will save someone the 6 hour headache it caused me..
diemuzi at gmail dot com
13-Jan-2005 10:11
In reference to van [at] webfreshener [dot] com to fix the krb5 problems. An easier fix is to do the following:

ln -s /usr/kerberos/include/krb5.h /usr/include/krb5.h
ln -s /usr/kerberos/include/profile.h /usr/include/profile.h
ln -s /usr/kerberos/include/com_err.h /usr/include/com_err.h

This will help solve some deps. in the future incase a situation with another compilation occurs.
alexander justadot henry at acm dot org
22-Dec-2004 12:48
The system at my workplace has a need for apache/php with all static compilation.  In order to save time adminning our systems, I decided to make my own RPM of php/apache with mod_ssl support.  I had always installed by hand with the instructions on this page, but when buiding the RPM way, came upon the following error when apache was compiling:

===> src/modules/php4
make[4]: *** No rule to make target `all'. Stop.

Ordinarily this is because one did not do a 'make install' in php before the second apache configure, or somehow the make install failed.  But the way rpm's work, the make install must be in the %install portion of the spec file, after all makes are completed.

make install-sapi

This line will copy relevant files to the directory specified in --with-apache
samael99 at web dot de
24-Jun-2004 06:51
Quick hint for people using RH8:

if make gives you this error
FT_ENCODING_MS_SYMBOL undeclared

change on line in this file
/usr/include/freetype2/freetype/freetype.h

Search for ft_encoding_symbol - change it to
ft_encoding_ms_symbol

Now this problem is dealt with, go ahead with make.

Good Luck !
robert_sgi at yahoo dot com
08-May-2004 11:57
If you install php 4 on SGI IRIX 6.5 (in my case it was php 4.3.6 on Silicon Graphics O2 IRIX 6.5.22 machine) and you're building it with:
--with-gettext=/usr/freeware
then you need to manually edit the file named "configure" (from the php source directory) and change the line# 36739
from:
GETTEXT_LIBDIR=$GETTEXT_DIR/lib
to:
GETTEXT_LIBDIR=$GETTEXT_DIR/lib32
If you have problems in locating the line, search the text for "bindtextdomain", and look several (4) lines above.
karthik (dot) k (at) extremix (dot) net
18-Jan-2004 08:28
This is regarding the post down below about the problem with openssl on RH9. Openssl on RH9 is built with kerberos. To get PHP to build correctly you need the output of these commands when you make.

[root@graf-spee local]# pkg-config --cflags openssl
-I/usr/kerberos/include 

[root@graf-spee local]# pkg-config --libs openssl
-L/usr/kerberos/lib -lssl -lcrypto -lresolv -lgssapi_krb5 -lkrb5 -lk5crypto -lcom_err -ldl -lz 

These could be added to your make command thus. I have not tested it out, but should work with some tweaking

make EXTRA_LDFLAGS=`pkg-config --libs openssl` EXTRA_CFLAGS=`pkg-config --cflags openssl`
thansen at terra dot com dot br
30-Dec-2003 08:36
The configure directives --with-apxs2 and --with-apxs2filter are not compatible one with other, even though the configure script will not complain about that. Each one affect the way Apache will call the php parser: If you choose the first one, you must use the traditional include:

AddType application/x-httpd-php php

at httpd.conf, to call the parser. If you use the --with-apxs2filter, the include will be:

<Files *.php>
        SetOutputFilter PHP
        SetInputFilter  PHP
</Files>

, and php will be called as a filter to .php files.

If you use both together, you will get compilation errors (duplicate symbols while linking libphp4).
aaronmorris at mindspring dot com
05-Dec-2003 12:47
If you have the libphp4.a instead of libphp4.so on AIX, you can extract the .so file from the .a file by running "ar -x libphp4.a".
jazee_at_bigfoot.com
26-Mar-2003 12:52
http://dan.drydog.com/apache2php.html has a nice set of instructions for Apache2 + php
doug at NOSPAM dot techie dot net
04-Feb-2003 05:16
Users compiling under some versions of Solaris/SunOS may encounter the following error.
   symbol ap_block_alarms: referenced symbol not found

To address this problem, add the following additional flag to the Apache build configure line:
   --enable-rule=SHARED_CORE

So, adding this to the original instructions, you'd configure your Apache build like so:
   ./configure --prefix=/www --enable-module=so --enable-rule=SHARED_CORE

Doug
mbabcock-php at fibrespeed dot net
20-Jul-2001 09:32
The best configuration guide I've found for Apache with PHP (and PERL, mod_ssl, etc.) is Apacompile.  Its home site is
http://www.delouw.ch/linux/apache.phtml
dimaberastau at hotmail dot com
09-Jun-2001 09:33
when installing with mysql support (--with-mysql=<path/to/your/mysql>) via Apache APXS you'll probably get something like 'can't load libmysqlclient.so' when you try to start up apache. There are 2 solutions to this problem. First, (as documented in INSTALL file of the php4 distribution) you can modify /etc/ld.so.conf to contain the directory name where libmysqlclient.so is (so if your mysql is installed in /usr/local, you want to add something like /usr/local/lib/mysql into /etc/ld.so.conf), else (and particularly if you haven't got the super-user on the system) you can modify (or create if it isn't defined already) LD_LIBRARY_PATH shell variable to reflect the changes you would have otherwise made to /etc/ld.so.conf (again if mysql is /usr/local LD_LIBRARY_PATH=/usr/local/lib/mysql). Either one of these methods will get the problem sorted. Just remember to run ldconfig (so that /etc/ld.so.cache is updated) if you chose to modify /etc/ld.so.conf
marshalm at ebrd dot com
17-May-2001 10:43
HP-UX 11.X PA-RISC installation with oracle (oci8). You need to install the HP-UX patch PHSS_22514 patch (updated libdld.sl), otherwise you will get errors with dlopen() and dlclose() not found during the apache integration stage.
philip at c()rnad() dot c()m
25-Mar-2001 04:22





0 comments:

Post a Comment