1. General Information
1.1 What is PHP?
From the manual:
PHP Version 3.0 is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
1.2 What is its relation to PHP/FI?
PHP is the successor to PHP/FI 2.0.
1.3 Can I run both PHP/FI 2.0 and PHP at the same time?
Yes, PHP was written so as to not interfere with an existing PHP/FI 2 installation. Instructions for building Apache 1.3.0 with both PHP/FI 2 and PHP modules can be found HERE. A different spin on this is HERE, although the first step where the PHP2 regex code is substituted with the PHP regex code seems redundant. The two regex dirs are pretty much identical.
1.4 What are the differences between PHP and PHP/FI 2.0?
For a complete list of the changes, read the CHANGES file included in the PHP distribution. Some highlights:
All-new parser.
Persistent database connections.
A native Windows95/NT port.
IMAP, SNMP, and LDAP extensions.
1.5 I heard it's possible to access Microsoft SQL Server from PHP. How?
On Windows 95/NT machines, you can simply use the included ODBC support and the correct ODBC driver.
A copy of step-by-step ODBC setup can be found here.
On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question - 1.6.
1.6 Can I access Microsoft Access databases?
Yes. You already have all the tools you need if you are running entirely under Windows 95/98 or NT, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.
If you are running PHP on a Unix box and want to talk to MS-Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.
Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built-in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat-files or dBase databases. On this point Tim Hayes from OpenLink software writes:
Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other unix platforms. Please visit our website for a free download.
One option that has proven successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:
Install MySQL on your platform according to instructions with MySQL. Latest available from www.mysql.org (get it from your mirror!). No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
Download the MyODBC for Windows driver from the MySQL site. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). Install it on your Windows machine. You can test the operation with the utilities included with this program.
Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
Install Access with a full install, this makes sure you get the proper add-ins.. at the least you will need ODBC support and the linked table manager.
Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press ok, and presto! you can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.
Tips and Tricks: - You can construct your tables in access and export them to MySQL, then link them back in. That makes table creation quick.
- When creating tables in access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access.
- If you change a table in MySQL, you have to re-link it in access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing ok.
1.7 Is there a PHP mailing list?
Of course! To subscribe, send mail to php3-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message.
To unsubscribe, send mail to php3-unsubscribe@lists.php.net.
1.8 Help! I can't seem to subscribe to the mailing list!
Help! I can't seem to unsubscribe from the mailing list!
If you have problems subscribing to or unsubscribing from the PHP mailng list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, you can send your subscription request to php3-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php3-unsubscribe-joeblow=example.com@lists.php.net.
1.9 Is there an archive of the mailing list anywhere?
Yes, you will find a list of archive sites on the Support page.
1.10 How did you do those pop-out windows for the Search and Mirror buttons?
Our site designer, Colin Viebrock (cmv@privateworld.com), says:
Those fancy pop-out layers are done with Dynamic HTML (DHTML), Cascading Style Sheets (CSS) and Javascript (version 1.2).
There are plenty of references on the web about DHTML and CSS, including:
CSS Level 1 Spec: www.w3.org/TR/REC-CSS1
Macromedia's DHTML Zone: www.dhtmlzone.com/index.html
Webreference's DHTML Lab: www.webreference.com/dhtml/
Guide to Cascading Style Sheets: www.htmlhelp.com/reference/css/
Dynamic Duo - Cross-Browser DHTML: www.dansteinman.com/dynduo/
Netscape's Guide to JS 1.2: developer.netscape.com/docs/manuals/communicator/jsguide/js1_2.htm
But your best source of information is to view the source code to the pages on the PHP site. To see the actual DHTML/Javascript code, use your browser's "View Source" function. To see how this code was generated dynamically using PHP, click on the "Source" button in the upper-right corner of any PHP page. You will probably also want to view the source of the "shared.inc" file - there is a link to it at the bottom of every source page.
1.11 Can I access Empress RDBMS databases?
Yes. PHP 3.0.6 and Empress RDBMS v8.10 and higher are compatible.
You already have all the tools you need if you are running entirely under Windows 95/98 or NT, where you can use ODBC and the Empress ODBC driver for Windows.
If you are running PHP on a Unix box and want to access Empress databases, you can link the Empress ODBC client driver directly into the PHP unified ODBC API.
Note that does NOT make PHP an ODBC client. The unified ODBC interface simplies uses the ODBC application program interface (API).
Because Empress uses the PHP unified ODBC interface it has very little explicit Empress specific syntax. It is of course possible to use Empress specific SQL in the SQL statements themselves, but this does not affect the interface. It is a good general policy to stick to ANSI standard SQL whenever possible.
Empress Specifics: The only item which is specific to Empress in PHP is that there are two methods for specifying the DNS in the odbc_connect () and odbc_pconnect () functions. The connect syntax is:
odbc_connect (dsn, user_id, password)
odbc_pconnect (dsn, user_id, password)
For Empress dsn can be specified as either:
Data source name
This is the logical database name specified in the ODBC.INI file.
A full connection string, as specified in the ODBC standard.
eg
dsn="DATABASE=db_name;SERVER=server_name;PORT=server_port"
Note that there are other options for this string. But the three shown above are the most important for use with PHP.
Which of these you use is up to you. There are advantages and disadvantages to both. Using the full connection string means that you do NOT require an ODBC.INI file to access the database. However, if you move the datasource, or change the port on which the RDBMS server listens, you will have to modify every call to the odbc_connect/pconnect function.
The choice is yours...
Empress Installation: In order to add the Empress interface to PHP you require an Empress RDBMS with the Empress Connectivity option. If your PHP installation is on the same platform as the RDBMS then setting EMPRESS_PATH to the installation directory will automatically locate the Empress ODBC client driver. However, if the PHP installation is on a separate platform from the RDBMS you will also require an ODBC client on that platform, and you will need to specify the location of the driver when configuring the PHP installation.
--------------------------------------------------------------------------------
2. Obtaining PHP
2.1 Where can I obtain PHP?
You can download PHP from any of the members of the PHP network of sites. These can be found at http://www.php.net/. You can also use anonymous CVS to get the absolute latest version of the source. For more information, go to http://cvs.php.net.
2.2 Are pre-compiled binary versions available?
Yes, although they are not always up to date. The Windows binary is generally current, but the Unix binaries lag behind and are only available for certain platforms. All download are available in the Downloads section.
2.3 Where can I get libraries needed to compile some of the optional PHP extensions?
Note: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.
LDAP (unix): ftp://ftp.openldap.org/pub/openldap/openldap-stable.tgz
LDAP* (unix): ftp://terminator.rs.itd.umich.edu/ldap/ldap-3.3.tar.Z
LDAP (unix/win): Netscape Directory (LDAP) SDK 1.1 There is also a free LDAP server at: ftp://ftp.critical-angle.com/pub/cai/slapd/.
Berkeley DB2 (Unix/Win): http://www.sleepycat.com/
SNMP* (Unix): http://www.ece.ucdavis.edu/ucd-snmp/ (Note: PHP uses the native SNMP interface in Windows.)
GD* (Unix/Win): http://www.boutell.com/gd/#buildgd
mSQL* (Unix): http://www.hughes.com.au/
mSQL* (Win) : MSQL PC Home Page
MySQL (Unix): http://www.mysql.com/
IMAP* (Win/Unix): ftp://ftp.cac.washington.edu/imap/old/imap-4.5.tar.Z
Sybase-CT* (Linux, libc5): Available locally
FreeType (libttf): http://www.freetype.org/
ZLib (Unix/Win32): http://www.cdrom.com/pub/infozip/zlib/
expat XML parser (Unix/Win32): http://www.jclark.com/xml/expat.html
PDFLib: http://www.ifconnection.de/~tm/
mcrypt: ftp://argeas.cs-net.gr/pub/unix/mcrypt/
mhash: http://sasweb.de/mhash/
t1lib: http://www.neuroinformatik.ruhr-uni-bochum.de/ini/PEOPLE/rmz/t1lib/t1lib.html
dmalloc: http://www.dmalloc.com/
aspell: http://metalab.unc.edu/kevina/aspell/aspell-.26.2.tar.gz
2.4 How do I get these libraries to work?
You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.
2.5 I got the latest version of the PHP source code from the CVS repository on my Windows 95/NT machine, what do I need to compile it?
First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need to download the support files. You will need to unzip this file (which has subdirectories, so make sure your unzip program keeps them) into the win32 subdirectory of the source distribution.
2.6 Where do I find the Browser Capabilities File?
You can find PHP's own browscap.ini file at http://php.netvision.net.il/browscap/. There is also another browscap.ini file at http://www.cyscape.com/asp/browscap/.
--------------------------------------------------------------------------------
3. Installation
To install PHP, follow the instructions in the INSTALL file located in the distribution. Windows 95 and NT users should also read the README.WIN32 file. There are also some helpful hints for Windows users here.
If you are trying to install PHP for use with Netscape's web server on Unix see: http://www.webgenx.com/Kwazy/phpunix.html
3.1 Where should my php3.ini file be located?
By default on UNIX it should be in /usr/local/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it to something like:
--with-config-file-path=/etc
And then you would copy php3.ini-dist from the distribution to /etc/php3.ini and edit it to make any local changes you want.
3.2 I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
Assuming you installed Apache PHP completely with RPMS, you need to uncomment or add some or all of the following lines in your http.conf file:
# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c
# Extra Modules
LoadModule php_module modules/mod_php.so
LoadModule php3_module modules/libphp3.so
LoadModule perl_module modules/libperl.so
And add:
AddType application/x-httpd-php3 .php3
To the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.
3.3 I installed PHP using RPMS, but it doesn't compile with the database support I need! What's going on here?
Due to the way PHP is currently built, it is not easy to build a complete flexible PHP RPM. This issue will be addressed in PHP4. For PHP, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP, read on...
Currently the RPM packagers are setting up the RPMS to install without database support to simplify installations AND because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level of your database server.
This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.
Of course all of this information can be adjusted for any database server that PHP supports. I will assume you installed MySQL and Apache completely with RPMS for this example as well.
First remove mod_php3
rpm -e mod_php3
Then get the source rpm and INSTALL it, NOT --rebuild
rpm -Uvh mod_php3-3.0.5-2.src.rpm
Then edit the /usr/src/redhat/SPECS/mod_php3.spec file
In the %build section add the database support you want, and the path.
For MySQL you would add --with-mysql=/usr \
The %build section will look something like this:
./configure --prefix=/usr \
--with-apxs=/usr/sbin/apxs \
--with-config-file-path=/usr/lib \
--enable-debug=no \
--enable-safe-mode \
--with-exec-dir=/usr/bin \
--with-mysql=/usr \
--with-system-regex
Once this modification is made then build the binary rpm as follows:
rpm -bb /usr/src/redhat/SPECS/mod_php3.spec
Then install the rpm
rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm
Make sure you restart Apache, and you now have PHP with MySQL support using RPM's. Note that it is probably much easier to just build from the distribution tarball of PHP and follow the instructions in INSTALL.REDHAT found in that distribution.
--------------------------------------------------------------------------------
4. Build Problems
4.1 I got the latest version of PHP using the anonymous CVS service, but there's no configure script!
You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run autoconf in the top-level directory after getting the sources from the CVS server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.
4.2 I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify '--with-apache=/path/to/apache' and not '--with-apache=/path/to/apache/src'.
4.3 When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
You can make the configure script looks for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:
CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
4.4 When it is compiling the file language-parser.tab.c, it gives me errors that say 'yytname undeclared'.
You need to update your version of Bison. You can find the latest version at ftp://prep.ai.mit.edu/pub/gnu/.
4.5 When I run 'make', it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running "cp *.o functions" and then re-running 'make' to see if that helps. If it does, you should really upgrade to a recent version of GNU make.
4.6 When linking PHP, it complains about a number of undefined references.
Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.
If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the INSTALL file that comes with the distribution for more information.
Some people have also reported that they had to add '-ldl' immediately following 'libphp3.a' when linking with Apache.
4.7 I can't figure out how to build PHP with Apache 1.3.
This is actually quite easy. Follow these steps carefully:
Grab the latest Apache 1.3 distribution from www.apache.org.
Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.
Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory.
Type 'make' followed by 'make install' to build PHP and copy the necessary files to the Apache distribution tree.
Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. At the end of the file, add: AddModule modules/php3/libphp3.a.
Type: './Configure' followed by 'make'.
You should now have a PHP-enabled httpd binary!
Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.
4.8 I have followed all the steps to install the Apache module version on UNIX, and my PHP scripts show up in my browser or I am being asked to save the file. Help!
This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:
Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l
If you don't see mod_php3.c listed then you are not running the right binary. Find and install the correct binary.
Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php3 .php3
Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read corre ctly.
4.9 It says to use: --activate-module=src/modules/php3/libphp3.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php3/libmodphp3.a and it doesn't work!? What's going on?
Well, you decided to try to outsmart the people who wrote those nice step-by-step instructions for you and you have now discovered that these people cannot be outsmarted. The libphp3.a file is not supposed to exist. The Apache build process will create it.
4.10 When I try to build Apache with PHP as a static module using --activate-module=src/modules/php3/libphp3.a it tells me that my compiler is not ANSI compliant.
This is a crappy error message and has been fixed in Apache-1.3.10 (not available yet). For now, go and edit the src/Configure file in the Apache source directory and down around line 2140 you will find a line that looks like this:
if ./helpers/TestCompile sanity; then
Change this line to be this:
if ./helpers/TestCompile -v sanity; then
and now re-run the Apache configure script. It will now show you the actual errors that caused your build to fail. It is usually due to a missing library.
--------------------------------------------------------------------------------
5. Using PHP
5.1 I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
Make sure that the track_vars feature is enabled in your php3.ini file. If you compiled PHP with "--enable-track-vars" it will be on by default. Alternatively you can enable it at run-time on a per-script basis by putting <?php_track_vars?> at the top of your file. When track_vars is on, it creates three associative arrays. $HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS. So, to write a generic script to handle POST method variables you would need something similar to the following:
while (list($var, $value) = each($HTTP_POST_VARS)) {
echo "$var = $value
\n";
}
5.2 I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?
First off, take a look at the addslashes() function. It will do exactly what you want. You should also have a look at the magic_quotes_gpc directive in your php3.ini file.
The ereg_replace magic you're looking for, however, is simply:
$escaped = ereg_replace("'", "\\'", $input);
5.3 When I do the following, the output is printed in the wrong order:
function myfunc($argument) {
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
What's going on?
To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo it.
5.4 Hey, what happened to my newlines in:
<PRE>
1 <?echo $result[1];?>
2 <?echo $result[2];?>
In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). This means that you need to insert an extra newline after each block of PHP code in the above example.
Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.
5.5 I need to access information in the request header directly. How can I do this?
The getallheaders() function will do this if you are running PHP as a module. So, the following bit of code will show you all the request headers:
$headers = getallheaders();
for(reset($headers); $key = key($headers); next($headers)) {
echo "headers[$key] = ".$headers[$key]."
\n";
}
5.6 When I try to use authentication with IIS I get 'No Input file specified'
The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by php) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. When the ISAPI module is ready, this will no longer be a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp.
5.7 I've followed all the instructions, but still can't get PHP and IIS to work together!
Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine.
5.8 My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape. Even when I telnet to port 80 directly the correct content shows up. How can this be? PHP is server-side and my browser can't possibly know that the content it is seeing is generated by PHP, so what is going on?
Very good question! This is a tricky little issue and it has come up twice in the past month as of this writing. Both times I ended up spending a good 20 minutes trying to figure out what the heck was going on. The answer is that both IE and Lynx ignore any NULs (\0) in the HTML stream. Netscape does not. The best way to check for this is to compile the command-line version of PHP (also known as the CGI version) and run your script from the command line and pipe it through 'od -c' and look for any \0 characters. (If you are on Windows you need to find an editor or some other program that lets you look at binary files) When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will. If this issue has bitten you, congratulations! You are not alone.
5.9 How do I get all the results from a SELECT MULTIPLE HTML tag?
The SELECT MULTIPLE tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.
<SELECT NAME="var" MULTIPLE>
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's non-indexed array feature. The following should be used:
<SELECT NAME="var[]" MULTIPLE>
This tells PHP to treat var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.
Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element id instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]'];
5.10 How am I supposed to mix XML and PHP? It complains about my <?xml> tags!
You need to turn off the short tags by setting short_tags to 0 in your php3.ini file, or by using the php3_short_tags Apache directive. (You could even use a <File> section to do this selectively.) You can also disable and re-enable the short tags in your script using the short_tags() function.
5.11 How can I use PHP with FrontPage or Dreamweaver or some other HTML editor that insists on moving my code around?
One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Most of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php3.ini variable, or use the php3_asp_tags Apache directive.
5.12 Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?
The best way is to stick a <?phpinfo()?> tag on a page and load it up. This will show you all sorts of information about your PHP setup, including a list of both environment variables and also special variables set by your web server. This list can't really be documented in the PHP documentation because it will change from one server to another.
5.13 Why do I always get an error that looks something like this:
Warning: 0 is not a MySQL result index in file on line 8
What am I doing wrong?
You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:
$result = mysql_query("select * from tables_priv");
if(!$result) {
echo mysql_error();
exit;
}
or:
$result = mysql_query("select * from tables_priv")
or die("Bad query: ".mysql_error());
5.14 I'm trying to use an <INPUT TYPE="image"> tag, but the $foo.x and $foo.y variables aren't available. Where are they?
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<INPUT TYPE="image" SRC="image.gif" NAME="foo">
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.
Because $foo.x and $foo.y are invalid variable names in PHP, they are automagically converted to $foo_x and $foo_y. That is, the periods are replaced with underscores.
--------------------------------------------------------------------------------
6. New Features
6.1 I saw PHP offers persistent database connections. What does that mean?
Persistent connections are SQL links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same SQL link, they do not give you an ability to build up a transaction efficently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.
Why?
This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.
The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When each request comes in from a a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be serviced by a different child process than the first time. What a persistent connection does for you in this case it make it so each child process only needs to connect to your SQL server the first time that it serves a page that makes us of such a connection. When another page then requires a connection to the SQL server, it can reuse the connection that child established earlier.
The last method is to use PHP as a plug-in for a multithreaded web server. Currently this is only theoretical -- PHP does not yet work as a plug-in for any multithreaded web servers. Work is progressing on support for ISAPI, WSAPI, and NSAPI (on Windows), which will all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack, Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. When this happens, the behavior will be essentially the same as for the multiprocess model described before.
If persistent connections don't have any added functionality, what are they good for?
The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.
An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!
--------------------------------------------------------------------------------
7. Common Problems
7.1 I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:
Stop your httpd processes
gdb httpd
> run -X -f /path/to/httpd.conf
Then fetch the URL causing the problem with your browser
If you are getting a core dump, gdb should inform you of this now
type: bt
Send the resulting backtrace to php-dev@lists.php.net
If your script uses the regular expression functions (ereg() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. (This should happen automatically with PHP and Apache 1.3.x)
7.2 I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
Environment variables are now normal global variables, so you must either declare them as global variables in your function (by using "global $DOCUMENT_ROOT;", for example) or by using the global variable array (ie, "$GLOBALS["DOCUMENT_ROOT"]".
7.3 I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.
7.4 I think I found a bug! Who should I tell?
You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net.
--------------------------------------------------------------------------------
8. Migrating from PHP2 to PHP3
8.1 When I add two strings together and then echo it, it echoes zero instead of the concatenation of the two strings! What's going on? Wouldn't it be great if adding two strings just concatenated them together?
PHP3 does not support the overloading of the addition operator for strings because values that arrive via the GET and POST methods and from databases are always stored as strings. This means that if the plus operator were overloaded to concatenate strings, you could add what you thought were two numbers and get the wrong result! (For example, "4" + "5" would be equal to "45".) One way around this would be to explicitly type-cast one or both of the operands, which is what PHP/FI 2 did.
This has been simplified in PHP3 by the addition of a real string concatenation operator. If you want to "add" two strings together, just write it like: "this" . "that" which will result in the string "thisthat".
The answer to the final part of the question is an emphatic no. Operator overloading can be a source of great confusion, especially when variables aren't very strongly typed to begin with, as they are in PHP3.
8.2 When I use the chmod(), umask(), or mkdir() functions, the permissions are wrong!
Unlike PHP/FI 2, PHP3 does not interpret the numeric arguments for these functions any differently than for any other function, which means you need to pass in an octal value if you are specifying an octal number, such as:
chmod($myfile, 0600);
not
chmod($myfile, 600);
8.3 I converted my script from PHP/FI 2.0 to PHP3 syntax, but now it just hangs! When I looked at the processes running on my server, there was one process that was chewing up all of the CPU cycles!
You probably missed the semi-colon on a while (condition); statement. This will cause PHP3 to spin out of control because it is simply executing an empty body for your while loop! Change the semi-colon to a colon and it should work correctly.
8.4 My user-functions don't work any more! I get a "Parse error (expecting '('" on the first line of the function.
PHP3's function declaration now resembles C function declarations, so your function should look like:
function printsum($a, $b) {
echo $a + $b;
}
You can also use old-style function declarations by use the 'old_function' designation, like so:
old_function printsum $a, $b (
echo $a + $b;
);
8.5 What happened to the securevar() function that was in PHP2? How can I make sure that a GET-method variable does not overwrite a POST-method one?
The securevar() function in PHP2 was a badly named function. It gave the impression that when used the POST-method was secure. It is not. It is only slightly more difficult to fake POST-method variables than GET-method ones.
There are a couple of ways to achieve similar things in PHP3. The most straightforward way is to do it manually by using the $HTTP_POST_VARS array. See FAQ question 5.1 for instructions on how to enable it. To make sure that $foo, for example, comes from the POST data and nowhere else you would do:
$foo = $HTTP_POST_VARS["foo"];
A second way to do this is to change the gpc_order setting in your php3.ini file. The default setting is "GPC" which means that GET variables are parsed first followed by POST variables and lastly by COOKIE variables. This means that GET vars are overwritten by POST vars which are in turn overwritten by COOKIE vars. So, by default if you have the same variables in your GET and POST data the POST one will be the one that shows up in the main PHP symbol table and you would have to use the $HTTP_GET_VARS to get at it. Along with changing the order from "GPC" to something like "CGP" which would make POST variables have the highest priority, you can leave out any of the letters to completely disable PHP's ability to see a certain type of variable. If you never wanted GET-method data to be turned into PHP variables you could use a gpc_order setting of "PC".
--------------------------------------------------------------------------------
Credits
This FAQ was originally written by Jim Winstead. It is currently maintained by the PHP Development Team.
1.1 What is PHP?
From the manual:
PHP Version 3.0 is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.
1.2 What is its relation to PHP/FI?
PHP is the successor to PHP/FI 2.0.
1.3 Can I run both PHP/FI 2.0 and PHP at the same time?
Yes, PHP was written so as to not interfere with an existing PHP/FI 2 installation. Instructions for building Apache 1.3.0 with both PHP/FI 2 and PHP modules can be found HERE. A different spin on this is HERE, although the first step where the PHP2 regex code is substituted with the PHP regex code seems redundant. The two regex dirs are pretty much identical.
1.4 What are the differences between PHP and PHP/FI 2.0?
For a complete list of the changes, read the CHANGES file included in the PHP distribution. Some highlights:
All-new parser.
Persistent database connections.
A native Windows95/NT port.
IMAP, SNMP, and LDAP extensions.
1.5 I heard it's possible to access Microsoft SQL Server from PHP. How?
On Windows 95/NT machines, you can simply use the included ODBC support and the correct ODBC driver.
A copy of step-by-step ODBC setup can be found here.
On Unix machines, you can use the Sybase-CT driver to access Microsoft SQL Servers because they are (at least mostly) protocol-compatible. Sybase has made a free version of the necessary libraries for Linux systems. For other Unix operating systems, you need to contact Sybase for the correct libraries. Also see the answer to the next question - 1.6.
1.6 Can I access Microsoft Access databases?
Yes. You already have all the tools you need if you are running entirely under Windows 95/98 or NT, where you can use ODBC and Microsoft's ODBC drivers for Microsoft Access databases.
If you are running PHP on a Unix box and want to talk to MS-Access on a Windows box you will need Unix ODBC drivers. OpenLink Software has Unix-based ODBC drivers that can do this. There is a free pilot program where you can download an evaluation copy that doesn't expire and prices start at $675 for the commercial supported version.
Another alternative is to use an SQL server that has Windows ODBC drivers and use that to store the data, which you can then access from Microsoft Access (using ODBC) and PHP (using the built-in drivers), or to use an intermediary file format that Access and PHP both understand, such as flat-files or dBase databases. On this point Tim Hayes from OpenLink software writes:
Using another database as an intermediary is not a good idea, when you can use ODBC from PHP straight to your database - i.e. with OpenLink's drivers. If you do need to use an intermediary file format, OpenLink have now released Virtuoso (a virtual database engine) for NT, Linux and other unix platforms. Please visit our website for a free download.
One option that has proven successful is to use MySQL and its MyODBC drivers on Windows and synchronizing the databases. Steve Lawrence writes:
Install MySQL on your platform according to instructions with MySQL. Latest available from www.mysql.org (get it from your mirror!). No special configuration required except when you set up a database, and configure the user account, you should put % in the host field, or the host name of the Windows computer you wish to access MySQL with. Make a note of your server name, username, and password.
Download the MyODBC for Windows driver from the MySQL site. Latest release is myodbc-2_50_19-win95.zip (NT available too, as well as source code). Install it on your Windows machine. You can test the operation with the utilities included with this program.
Create a user or system dsn in your ODBC administrator, located in the control panel. Make up a dsn name, enter your hostname, user name, password, port, etc for you MySQL database configured in step 1.
Install Access with a full install, this makes sure you get the proper add-ins.. at the least you will need ODBC support and the linked table manager.
Now the fun part! Create a new access database. In the table window right click and select Link Tables, or under the file menu option, select Get External Data and then Link Tables. When the file browser box comes up, select files of type: ODBC. Select System dsn and the name of your dsn created in step 3. Select the table to link, press ok, and presto! you can now open the table and add/delete/edit data on your MySQL server! You can also build queries, import/export tables to MySQL, build forms and reports, etc.
Tips and Tricks: - You can construct your tables in access and export them to MySQL, then link them back in. That makes table creation quick.
- When creating tables in access, you must have a primary key defined in order to have write access to the table in access. Make sure you create a primary key in MySQL before linking in access.
- If you change a table in MySQL, you have to re-link it in access. Go to tools>add-ins>linked table manager, cruise to your ODBC DSN, and select the table to re-link from there. you can also move your dsn source around there, just hit the always prompt for new location checkbox before pressing ok.
1.7 Is there a PHP mailing list?
Of course! To subscribe, send mail to php3-subscribe@lists.php.net. You don't need to include anything special in the subject or body of the message.
To unsubscribe, send mail to php3-unsubscribe@lists.php.net.
1.8 Help! I can't seem to subscribe to the mailing list!
Help! I can't seem to unsubscribe from the mailing list!
If you have problems subscribing to or unsubscribing from the PHP mailng list, it may be because the mailing list software can't figure out the correct mailing address to use. If your email address was joeblow@example.com, you can send your subscription request to php3-subscribe-joeblow=example.com@lists.php.net, or your unsubscription request to php3-unsubscribe-joeblow=example.com@lists.php.net.
1.9 Is there an archive of the mailing list anywhere?
Yes, you will find a list of archive sites on the Support page.
1.10 How did you do those pop-out windows for the Search and Mirror buttons?
Our site designer, Colin Viebrock (cmv@privateworld.com), says:
Those fancy pop-out layers are done with Dynamic HTML (DHTML), Cascading Style Sheets (CSS) and Javascript (version 1.2).
There are plenty of references on the web about DHTML and CSS, including:
CSS Level 1 Spec: www.w3.org/TR/REC-CSS1
Macromedia's DHTML Zone: www.dhtmlzone.com/index.html
Webreference's DHTML Lab: www.webreference.com/dhtml/
Guide to Cascading Style Sheets: www.htmlhelp.com/reference/css/
Dynamic Duo - Cross-Browser DHTML: www.dansteinman.com/dynduo/
Netscape's Guide to JS 1.2: developer.netscape.com/docs/manuals/communicator/jsguide/js1_2.htm
But your best source of information is to view the source code to the pages on the PHP site. To see the actual DHTML/Javascript code, use your browser's "View Source" function. To see how this code was generated dynamically using PHP, click on the "Source" button in the upper-right corner of any PHP page. You will probably also want to view the source of the "shared.inc" file - there is a link to it at the bottom of every source page.
1.11 Can I access Empress RDBMS databases?
Yes. PHP 3.0.6 and Empress RDBMS v8.10 and higher are compatible.
You already have all the tools you need if you are running entirely under Windows 95/98 or NT, where you can use ODBC and the Empress ODBC driver for Windows.
If you are running PHP on a Unix box and want to access Empress databases, you can link the Empress ODBC client driver directly into the PHP unified ODBC API.
Note that does NOT make PHP an ODBC client. The unified ODBC interface simplies uses the ODBC application program interface (API).
Because Empress uses the PHP unified ODBC interface it has very little explicit Empress specific syntax. It is of course possible to use Empress specific SQL in the SQL statements themselves, but this does not affect the interface. It is a good general policy to stick to ANSI standard SQL whenever possible.
Empress Specifics: The only item which is specific to Empress in PHP is that there are two methods for specifying the DNS in the odbc_connect () and odbc_pconnect () functions. The connect syntax is:
odbc_connect (dsn, user_id, password)
odbc_pconnect (dsn, user_id, password)
For Empress dsn can be specified as either:
Data source name
This is the logical database name specified in the ODBC.INI file.
A full connection string, as specified in the ODBC standard.
eg
dsn="DATABASE=db_name;SERVER=server_name;PORT=server_port"
Note that there are other options for this string. But the three shown above are the most important for use with PHP.
Which of these you use is up to you. There are advantages and disadvantages to both. Using the full connection string means that you do NOT require an ODBC.INI file to access the database. However, if you move the datasource, or change the port on which the RDBMS server listens, you will have to modify every call to the odbc_connect/pconnect function.
The choice is yours...
Empress Installation: In order to add the Empress interface to PHP you require an Empress RDBMS with the Empress Connectivity option. If your PHP installation is on the same platform as the RDBMS then setting EMPRESS_PATH to the installation directory will automatically locate the Empress ODBC client driver. However, if the PHP installation is on a separate platform from the RDBMS you will also require an ODBC client on that platform, and you will need to specify the location of the driver when configuring the PHP installation.
--------------------------------------------------------------------------------
2. Obtaining PHP
2.1 Where can I obtain PHP?
You can download PHP from any of the members of the PHP network of sites. These can be found at http://www.php.net/. You can also use anonymous CVS to get the absolute latest version of the source. For more information, go to http://cvs.php.net.
2.2 Are pre-compiled binary versions available?
Yes, although they are not always up to date. The Windows binary is generally current, but the Unix binaries lag behind and are only available for certain platforms. All download are available in the Downloads section.
2.3 Where can I get libraries needed to compile some of the optional PHP extensions?
Note: Those marked with * are not thread-safe libraries, and should not be used with PHP as a server module in the multi-threaded Windows web servers (IIS, Netscape). This does not matter in Unix environments, yet.
LDAP (unix): ftp://ftp.openldap.org/pub/openldap/openldap-stable.tgz
LDAP* (unix): ftp://terminator.rs.itd.umich.edu/ldap/ldap-3.3.tar.Z
LDAP (unix/win): Netscape Directory (LDAP) SDK 1.1 There is also a free LDAP server at: ftp://ftp.critical-angle.com/pub/cai/slapd/.
Berkeley DB2 (Unix/Win): http://www.sleepycat.com/
SNMP* (Unix): http://www.ece.ucdavis.edu/ucd-snmp/ (Note: PHP uses the native SNMP interface in Windows.)
GD* (Unix/Win): http://www.boutell.com/gd/#buildgd
mSQL* (Unix): http://www.hughes.com.au/
mSQL* (Win) : MSQL PC Home Page
MySQL (Unix): http://www.mysql.com/
IMAP* (Win/Unix): ftp://ftp.cac.washington.edu/imap/old/imap-4.5.tar.Z
Sybase-CT* (Linux, libc5): Available locally
FreeType (libttf): http://www.freetype.org/
ZLib (Unix/Win32): http://www.cdrom.com/pub/infozip/zlib/
expat XML parser (Unix/Win32): http://www.jclark.com/xml/expat.html
PDFLib: http://www.ifconnection.de/~tm/
mcrypt: ftp://argeas.cs-net.gr/pub/unix/mcrypt/
mhash: http://sasweb.de/mhash/
t1lib: http://www.neuroinformatik.ruhr-uni-bochum.de/ini/PEOPLE/rmz/t1lib/t1lib.html
dmalloc: http://www.dmalloc.com/
aspell: http://metalab.unc.edu/kevina/aspell/aspell-.26.2.tar.gz
2.4 How do I get these libraries to work?
You will need to follow instructions provided with the library. Some of these libraries are detected automatically when you run the 'configure' script of PHP (such as the GD library), and others you will have to enable using '--with-EXTENSION' options to 'configure'. Run 'configure --help' for a listing of these.
2.5 I got the latest version of the PHP source code from the CVS repository on my Windows 95/NT machine, what do I need to compile it?
First, you will need Microsoft Visual C++ v6 (v5 may do it also, but we do it with v6), and you will need to download the support files. You will need to unzip this file (which has subdirectories, so make sure your unzip program keeps them) into the win32 subdirectory of the source distribution.
2.6 Where do I find the Browser Capabilities File?
You can find PHP's own browscap.ini file at http://php.netvision.net.il/browscap/. There is also another browscap.ini file at http://www.cyscape.com/asp/browscap/.
--------------------------------------------------------------------------------
3. Installation
To install PHP, follow the instructions in the INSTALL file located in the distribution. Windows 95 and NT users should also read the README.WIN32 file. There are also some helpful hints for Windows users here.
If you are trying to install PHP for use with Netscape's web server on Unix see: http://www.webgenx.com/Kwazy/phpunix.html
3.1 Where should my php3.ini file be located?
By default on UNIX it should be in /usr/local/lib. Most people will want to change this at compile-time with the --with-config-file-path flag. You would, for example, set it to something like:
--with-config-file-path=/etc
And then you would copy php3.ini-dist from the distribution to /etc/php3.ini and edit it to make any local changes you want.
3.2 I installed PHP using RPMS, but Apache isn't processing the PHP pages! What's going on here?
Assuming you installed Apache PHP completely with RPMS, you need to uncomment or add some or all of the following lines in your http.conf file:
# Extra Modules
AddModule mod_php.c
AddModule mod_php3.c
AddModule mod_perl.c
# Extra Modules
LoadModule php_module modules/mod_php.so
LoadModule php3_module modules/libphp3.so
LoadModule perl_module modules/libperl.so
And add:
AddType application/x-httpd-php3 .php3
To the global properties, or to the properties of the VirtualDomain you want to have PHP support added to.
3.3 I installed PHP using RPMS, but it doesn't compile with the database support I need! What's going on here?
Due to the way PHP is currently built, it is not easy to build a complete flexible PHP RPM. This issue will be addressed in PHP4. For PHP, we currently suggest you use the mechanism described in the INSTALL.REDHAT file in the PHP distribution. If you insist on using an RPM version of PHP, read on...
Currently the RPM packagers are setting up the RPMS to install without database support to simplify installations AND because RPMS use /usr/ instead of the standard /usr/local/ directory for files. You need to tell the RPM spec file which databases to support and the location of the top-level of your database server.
This example will explain the process of adding support for the popular MySQL database server, using the mod installation for Apache.
Of course all of this information can be adjusted for any database server that PHP supports. I will assume you installed MySQL and Apache completely with RPMS for this example as well.
First remove mod_php3
rpm -e mod_php3
Then get the source rpm and INSTALL it, NOT --rebuild
rpm -Uvh mod_php3-3.0.5-2.src.rpm
Then edit the /usr/src/redhat/SPECS/mod_php3.spec file
In the %build section add the database support you want, and the path.
For MySQL you would add --with-mysql=/usr \
The %build section will look something like this:
./configure --prefix=/usr \
--with-apxs=/usr/sbin/apxs \
--with-config-file-path=/usr/lib \
--enable-debug=no \
--enable-safe-mode \
--with-exec-dir=/usr/bin \
--with-mysql=/usr \
--with-system-regex
Once this modification is made then build the binary rpm as follows:
rpm -bb /usr/src/redhat/SPECS/mod_php3.spec
Then install the rpm
rpm -ivh /usr/src/redhat/RPMS/i386/mod_php3-3.0.5-2.i386.rpm
Make sure you restart Apache, and you now have PHP with MySQL support using RPM's. Note that it is probably much easier to just build from the distribution tarball of PHP and follow the instructions in INSTALL.REDHAT found in that distribution.
--------------------------------------------------------------------------------
4. Build Problems
4.1 I got the latest version of PHP using the anonymous CVS service, but there's no configure script!
You have to have the GNU autoconf package installed so you can generate the configure script from configure.in. Just run autoconf in the top-level directory after getting the sources from the CVS server. (Also, unless you run configure with the --enable-maintainer-mode option, the configure script will not automatically get rebuilt when the configure.in file is updated, so you should make sure to do that manually when you notice configure.in has changed. One symptom of this is finding things like @VARIABLE@ in your Makefile after configure or config.status is run.
4.2 I'm having problems configuring PHP to work with Apache. It says it can't find httpd.h, but it's right where I said it is!
You need to tell the configure/setup script the location of the top-level of your Apache source tree. This means that you want to specify '--with-apache=/path/to/apache' and not '--with-apache=/path/to/apache/src'.
4.3 When I run configure, it says that it can't find the include files or library for GD, gdbm, or some other package!
You can make the configure script looks for header files and libraries in non-standard locations by specifying additional flags to pass to the C preprocessor and linker, such as:
CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
If you're using a csh-variant for your login shell (why?), it would be:
env CPPFLAGS=-I/path/to/include LDFLAGS=-L/path/to/library ./configure
4.4 When it is compiling the file language-parser.tab.c, it gives me errors that say 'yytname undeclared'.
You need to update your version of Bison. You can find the latest version at ftp://prep.ai.mit.edu/pub/gnu/.
4.5 When I run 'make', it seems to run fine but then fails when it tries to link the final application complaining that it can't find some files.
Some old versions of make that don't correctly put the compiled versions of the files in the functions directory into that same directory. Try running "cp *.o functions" and then re-running 'make' to see if that helps. If it does, you should really upgrade to a recent version of GNU make.
4.6 When linking PHP, it complains about a number of undefined references.
Take a look at the link line and make sure that all of the appropriate libraries are being included at the end. Common ones that you might have missed are '-ldl' and any libraries required for any database support you included.
If you're linking with Apache 1.2.x, did you remember to add the appropriate information to the EXTRA_LIBS line of the Configuration file and re-rerun Apache's Configure script? See the INSTALL file that comes with the distribution for more information.
Some people have also reported that they had to add '-ldl' immediately following 'libphp3.a' when linking with Apache.
4.7 I can't figure out how to build PHP with Apache 1.3.
This is actually quite easy. Follow these steps carefully:
Grab the latest Apache 1.3 distribution from www.apache.org.
Ungzip and untar it somewhere, for example /usr/local/src/apache-1.3.
Compile PHP by first running ./configure --with-apache=/<path>/apache-1.3 (substitute <path> for the actual path to your apache-1.3 directory.
Type 'make' followed by 'make install' to build PHP and copy the necessary files to the Apache distribution tree.
Change directories into to your /<path>/apache-1.3/src directory and edit the Configuration file. At the end of the file, add: AddModule modules/php3/libphp3.a.
Type: './Configure' followed by 'make'.
You should now have a PHP-enabled httpd binary!
Note: You can also use the new Apache ./configure script. See the instructions in the README.configure file which is part of your Apache distribution. Also have a look at the INSTALL file in the PHP distribution.
4.8 I have followed all the steps to install the Apache module version on UNIX, and my PHP scripts show up in my browser or I am being asked to save the file. Help!
This means that the PHP module is not getting invoked for some reason. Three things to check before asking for further help:
Make sure that the httpd binary you are running is the actual new httpd binary you just built. To do this, try running: /path/to/binary/httpd -l
If you don't see mod_php3.c listed then you are not running the right binary. Find and install the correct binary.
Make sure you have added the correct Mime Type to one of your Apache .conf files. It should be: AddType application/x-httpd-php3 .php3
Also make sure that this AddType line is not hidden away inside a <Virtualhost> or <Directory> block which would prevent it from applying to the location of your test script.
Finally, the default location of the Apache configuration files changed between Apache 1.2 and Apache 1.3. You should check to make sure that the configuration file you are adding the AddType line to is actually being read. You can put an obvious syntax error into your httpd.conf file or some other obvious change that will tell you if the file is being read corre ctly.
4.9 It says to use: --activate-module=src/modules/php3/libphp3.a, but that file doesn't exist, so I changed it to --activate-module=src/modules/php3/libmodphp3.a and it doesn't work!? What's going on?
Well, you decided to try to outsmart the people who wrote those nice step-by-step instructions for you and you have now discovered that these people cannot be outsmarted. The libphp3.a file is not supposed to exist. The Apache build process will create it.
4.10 When I try to build Apache with PHP as a static module using --activate-module=src/modules/php3/libphp3.a it tells me that my compiler is not ANSI compliant.
This is a crappy error message and has been fixed in Apache-1.3.10 (not available yet). For now, go and edit the src/Configure file in the Apache source directory and down around line 2140 you will find a line that looks like this:
if ./helpers/TestCompile sanity; then
Change this line to be this:
if ./helpers/TestCompile -v sanity; then
and now re-run the Apache configure script. It will now show you the actual errors that caused your build to fail. It is usually due to a missing library.
--------------------------------------------------------------------------------
5. Using PHP
5.1 I would like to write a generic PHP script that can handle data coming from any form. How do I know which POST method variables are available?
Make sure that the track_vars feature is enabled in your php3.ini file. If you compiled PHP with "--enable-track-vars" it will be on by default. Alternatively you can enable it at run-time on a per-script basis by putting <?php_track_vars?> at the top of your file. When track_vars is on, it creates three associative arrays. $HTTP_GET_VARS, $HTTP_POST_VARS and $HTTP_COOKIE_VARS. So, to write a generic script to handle POST method variables you would need something similar to the following:
while (list($var, $value) = each($HTTP_POST_VARS)) {
echo "$var = $value
\n";
}
5.2 I need to convert all single-quotes (') to a backslash followed by a single-quote. How can I do this with a regular expression?
First off, take a look at the addslashes() function. It will do exactly what you want. You should also have a look at the magic_quotes_gpc directive in your php3.ini file.
The ereg_replace magic you're looking for, however, is simply:
$escaped = ereg_replace("'", "\\'", $input);
5.3 When I do the following, the output is printed in the wrong order:
function myfunc($argument) {
echo $argument + 10;
}
$variable = 10;
echo "myfunc($variable) = " . myfunc($variable);
What's going on?
To be able to use the results of your function in an expression (such as concatenating it with other strings in the example above), you need to return the value, not echo it.
5.4 Hey, what happened to my newlines in:
<PRE>
1 <?echo $result[1];?>
2 <?echo $result[2];?>
In PHP, the ending for a block of code is either "?>" or "?>\n" (where \n means a newline). This means that you need to insert an extra newline after each block of PHP code in the above example.
Why does PHP do this? Because when formatting normal HTML, this usually makes your life easier because you don't want that newline, but you'd have to create extremely long lines or otherwise make the raw page source unreadable to achieve that effect.
5.5 I need to access information in the request header directly. How can I do this?
The getallheaders() function will do this if you are running PHP as a module. So, the following bit of code will show you all the request headers:
$headers = getallheaders();
for(reset($headers); $key = key($headers); next($headers)) {
echo "headers[$key] = ".$headers[$key]."
\n";
}
5.6 When I try to use authentication with IIS I get 'No Input file specified'
The security model of IIS is at fault here. This is a problem common to all CGI programs running under IIS. A workaround is to create a plain HTML file (not parsed by php) as the entry page into an authenticated directory. Then use a META tag to redirect to the PHP page, or have a link to the PHP page. PHP will then recognize the authentication correctly. When the ISAPI module is ready, this will no longer be a problem. This should not effect other NT web servers. For more information, see: http://support.microsoft.com/support/kb/articles/q160/4/22.asp.
5.7 I've followed all the instructions, but still can't get PHP and IIS to work together!
Make sure any user who needs to run a PHP script has the rights to run php.exe! IIS uses an anonymous user which is added at the time IIS is installed. This user needs rights to php.exe. Also, any authenticated user will also need rights to execute php.exe. And for IIS4 you need to tell it that PHP is a script engine.
5.8 My PHP script works on IE and Lynx, but on Netscape some of my output is missing. When I do a "View Source" I see the content in IE but not in Netscape. Even when I telnet to port 80 directly the correct content shows up. How can this be? PHP is server-side and my browser can't possibly know that the content it is seeing is generated by PHP, so what is going on?
Very good question! This is a tricky little issue and it has come up twice in the past month as of this writing. Both times I ended up spending a good 20 minutes trying to figure out what the heck was going on. The answer is that both IE and Lynx ignore any NULs (\0) in the HTML stream. Netscape does not. The best way to check for this is to compile the command-line version of PHP (also known as the CGI version) and run your script from the command line and pipe it through 'od -c' and look for any \0 characters. (If you are on Windows you need to find an editor or some other program that lets you look at binary files) When Netscape sees a NUL in a file it will typically not output anything else on that line whereas both IE and Lynx will. If this issue has bitten you, congratulations! You are not alone.
5.9 How do I get all the results from a SELECT MULTIPLE HTML tag?
The SELECT MULTIPLE tag in an HTML construct allows users to select multiple items from a list. These items are then passed to the action handler for the form. The problem is that they are all passed with the same widget name. ie.
<SELECT NAME="var" MULTIPLE>
Each selected option will arrive at the action handler as:
var=option1
var=option2
var=option3
Each option will overwrite the contents of the previous $var variable. The solution is to use PHP's non-indexed array feature. The following should be used:
<SELECT NAME="var[]" MULTIPLE>
This tells PHP to treat var as an array and each assignment of a value to var[] adds an item to the array. The first item becomes $var[0], the next $var[1], etc. The count() function can be used to determine how many options were selected, and the sort() function can be used to sort the option array if necessary.
Note that if you are using JavaScript the [] on the element name might cause you problems when you try to refer to the element by name. Use it's numerical form element id instead, or enclose the variable name in single quotes and use that as the index to the elements array, for example:
variable = documents.forms[0].elements['var[]'];
5.10 How am I supposed to mix XML and PHP? It complains about my <?xml> tags!
You need to turn off the short tags by setting short_tags to 0 in your php3.ini file, or by using the php3_short_tags Apache directive. (You could even use a <File> section to do this selectively.) You can also disable and re-enable the short tags in your script using the short_tags() function.
5.11 How can I use PHP with FrontPage or Dreamweaver or some other HTML editor that insists on moving my code around?
One of the easiest things to do is to enable using ASP tags in your PHP code. This allows you to use the ASP-style <% and %> code delimiters. Most of the popular HTML editors handle those more intelligently (for now). To enable the ASP-style tags, you need to set the asp_tags php3.ini variable, or use the php3_asp_tags Apache directive.
5.12 Where can I find a complete list of pre-set variables available to me, and why are these not documented in the PHP documentation?
The best way is to stick a <?phpinfo()?> tag on a page and load it up. This will show you all sorts of information about your PHP setup, including a list of both environment variables and also special variables set by your web server. This list can't really be documented in the PHP documentation because it will change from one server to another.
5.13 Why do I always get an error that looks something like this:
Warning: 0 is not a MySQL result index in file on line 8
What am I doing wrong?
You are trying to use a result identifier that is 0. The 0 indicates that your query failed for some reason. You need to check for errors after submitting a query and before you attempt to use the returned result identifier. The proper way to do this is with code similar to the following:
$result = mysql_query("select * from tables_priv");
if(!$result) {
echo mysql_error();
exit;
}
or:
$result = mysql_query("select * from tables_priv")
or die("Bad query: ".mysql_error());
5.14 I'm trying to use an <INPUT TYPE="image"> tag, but the $foo.x and $foo.y variables aren't available. Where are they?
When submitting a form, it is possible to use an image instead of the standard submit button with a tag like:
<INPUT TYPE="image" SRC="image.gif" NAME="foo">
When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables: foo.x and foo.y.
Because $foo.x and $foo.y are invalid variable names in PHP, they are automagically converted to $foo_x and $foo_y. That is, the periods are replaced with underscores.
--------------------------------------------------------------------------------
6. New Features
6.1 I saw PHP offers persistent database connections. What does that mean?
Persistent connections are SQL links that do not close when the execution of your script ends. When a persistent connection is requested, PHP checks if there's already an identical persistent connection (that remained open from earlier) - and if it exists, it uses it. If it does not exist, it creates the link. An 'identical' connection is a connection that was opened to the same host, with the same username and the same password (where applicable).
People who aren't thoroughly familiar with the way web servers work and distribute the load may mistake persistent connects for what they're not. In particular, they do not give you an ability to open 'user sessions' on the same SQL link, they do not give you an ability to build up a transaction efficently, and they don't do a whole lot of other things. In fact, to be extremely clear about the subject, persistent connections don't give you any functionality that wasn't possible with their non-persistent brothers.
Why?
This has to do with the way web servers work. There are three ways in which your web server can utilize PHP to generate web pages.
The first method is to use PHP as a CGI "wrapper". When run this way, an instance of the PHP interpreter is created and destroyed for every page request (for a PHP page) to your web server. Because it is destroyed after every request, any resources that it acquires (such as a link to an SQL database server) are closed when it is destroyed. In this case, you do not gain anything from trying to use persistent connections -- they simply don't persist.
The second, and most popular, method is to run PHP as a module in a multiprocess web server, which currently only includes Apache. A multiprocess server typically has one process (the parent) which coordinates a set of processes (its children) who actually do the work of serving up web pages. When each request comes in from a a client, it is handed off to one of the children that is not already serving another client. This means that when the same client makes a second request to the server, it may be serviced by a different child process than the first time. What a persistent connection does for you in this case it make it so each child process only needs to connect to your SQL server the first time that it serves a page that makes us of such a connection. When another page then requires a connection to the SQL server, it can reuse the connection that child established earlier.
The last method is to use PHP as a plug-in for a multithreaded web server. Currently this is only theoretical -- PHP does not yet work as a plug-in for any multithreaded web servers. Work is progressing on support for ISAPI, WSAPI, and NSAPI (on Windows), which will all allow PHP to be used as a plug-in on multithreaded servers like Netscape FastTrack, Microsoft's Internet Information Server (IIS), and O'Reilly's WebSite Pro. When this happens, the behavior will be essentially the same as for the multiprocess model described before.
If persistent connections don't have any added functionality, what are they good for?
The answer here is extremely simple -- efficiency. Persistent connections are good if the overhead to create a link to your SQL server is high. Whether or not this overhead is really high depends on many factors. Like, what kind of database it is, whether or not it sits on the same computer on which your web server sits, how loaded the machine the SQL server sits on is and so forth. The bottom line is that if that connection overhead is high, persistent connections help you considerably. They cause the child process to simply connect only once for its entire lifespan, instead of every time it processes a page that requires connecting to the SQL server. This means that for every child that opened a persistent connection will have its own open persistent connection to the server. For example, if you had 20 different child processes that ran a script that made a persistent connection to your SQL server, you'd have 20 different connections to the SQL server, one from each child.
An important summary. Persistent connections were designed to have one-to-one mapping to regular connections. That means that you should always be able to replace persistent connections with non-persistent connections, and it won't change the way your script behaves. It may (and probably will) change the efficiency of the script, but not its behavior!
--------------------------------------------------------------------------------
7. Common Problems
7.1 I installed PHP, but every time I load a document, I get the message 'Document Contains No Data'! What's going on here?
This probably means that PHP is having some sort of problem and is core-dumping. Look in your server error log to see if this is the case, and then try to reproduce the problem with a small test case. If you know how to use 'gdb', it is very helpful when you can provide a backtrace with your bug report to help the developers pinpoint the problem. If you are using PHP as an Apache module try something like:
Stop your httpd processes
gdb httpd
> run -X -f /path/to/httpd.conf
Then fetch the URL causing the problem with your browser
If you are getting a core dump, gdb should inform you of this now
type: bt
Send the resulting backtrace to php-dev@lists.php.net
If your script uses the regular expression functions (ereg() and friends), you should make sure that you compiled PHP and Apache with the same regular expression package. (This should happen automatically with PHP and Apache 1.3.x)
7.2 I'm trying to access one of the standard CGI variables (such as $DOCUMENT_ROOT or $HTTP_REFERER) in a user-defined function, and it can't seem to find it. What's wrong?
Environment variables are now normal global variables, so you must either declare them as global variables in your function (by using "global $DOCUMENT_ROOT;", for example) or by using the global variable array (ie, "$GLOBALS["DOCUMENT_ROOT"]".
7.3 I patched Apache with the FrontPage extensions patch, and suddenly PHP stopped working. Is PHP incompatible with the Apache FrontPage extensions?
No, PHP works fine with the FrontPage extensions. The problem is that the FrontPage patch modifies several Apache structures, that PHP relies on. Recompiling PHP (using 'make clean ; make') after the FP patch is applied would solve the problem.
7.4 I think I found a bug! Who should I tell?
You should go to the PHP Bug Database and make sure the bug isn't a known bug. If you don't see it in the database, use the reporting form to report the bug. It is important to use the bug database instead of just sending an email to one of the mailing lists because the bug will have a tracking number assigned and it will then be possible for you to go back later and check on the status of the bug. The bug database can be found at http://bugs.php.net.
--------------------------------------------------------------------------------
8. Migrating from PHP2 to PHP3
8.1 When I add two strings together and then echo it, it echoes zero instead of the concatenation of the two strings! What's going on? Wouldn't it be great if adding two strings just concatenated them together?
PHP3 does not support the overloading of the addition operator for strings because values that arrive via the GET and POST methods and from databases are always stored as strings. This means that if the plus operator were overloaded to concatenate strings, you could add what you thought were two numbers and get the wrong result! (For example, "4" + "5" would be equal to "45".) One way around this would be to explicitly type-cast one or both of the operands, which is what PHP/FI 2 did.
This has been simplified in PHP3 by the addition of a real string concatenation operator. If you want to "add" two strings together, just write it like: "this" . "that" which will result in the string "thisthat".
The answer to the final part of the question is an emphatic no. Operator overloading can be a source of great confusion, especially when variables aren't very strongly typed to begin with, as they are in PHP3.
8.2 When I use the chmod(), umask(), or mkdir() functions, the permissions are wrong!
Unlike PHP/FI 2, PHP3 does not interpret the numeric arguments for these functions any differently than for any other function, which means you need to pass in an octal value if you are specifying an octal number, such as:
chmod($myfile, 0600);
not
chmod($myfile, 600);
8.3 I converted my script from PHP/FI 2.0 to PHP3 syntax, but now it just hangs! When I looked at the processes running on my server, there was one process that was chewing up all of the CPU cycles!
You probably missed the semi-colon on a while (condition); statement. This will cause PHP3 to spin out of control because it is simply executing an empty body for your while loop! Change the semi-colon to a colon and it should work correctly.
8.4 My user-functions don't work any more! I get a "Parse error (expecting '('" on the first line of the function.
PHP3's function declaration now resembles C function declarations, so your function should look like:
function printsum($a, $b) {
echo $a + $b;
}
You can also use old-style function declarations by use the 'old_function' designation, like so:
old_function printsum $a, $b (
echo $a + $b;
);
8.5 What happened to the securevar() function that was in PHP2? How can I make sure that a GET-method variable does not overwrite a POST-method one?
The securevar() function in PHP2 was a badly named function. It gave the impression that when used the POST-method was secure. It is not. It is only slightly more difficult to fake POST-method variables than GET-method ones.
There are a couple of ways to achieve similar things in PHP3. The most straightforward way is to do it manually by using the $HTTP_POST_VARS array. See FAQ question 5.1 for instructions on how to enable it. To make sure that $foo, for example, comes from the POST data and nowhere else you would do:
$foo = $HTTP_POST_VARS["foo"];
A second way to do this is to change the gpc_order setting in your php3.ini file. The default setting is "GPC" which means that GET variables are parsed first followed by POST variables and lastly by COOKIE variables. This means that GET vars are overwritten by POST vars which are in turn overwritten by COOKIE vars. So, by default if you have the same variables in your GET and POST data the POST one will be the one that shows up in the main PHP symbol table and you would have to use the $HTTP_GET_VARS to get at it. Along with changing the order from "GPC" to something like "CGP" which would make POST variables have the highest priority, you can leave out any of the letters to completely disable PHP's ability to see a certain type of variable. If you never wanted GET-method data to be turned into PHP variables you could use a gpc_order setting of "PC".
--------------------------------------------------------------------------------
Credits
This FAQ was originally written by Jim Winstead. It is currently maintained by the PHP Development Team.