News:

:D The Conquer of Constantinople:
It took place on Wednesday ten nights before the end of Jumadal-'Akhirah, year 857 H. The Ottomann Sultan Muhammad Al-Fatih II besieged the City of Constantinople (Istanbul) for 51 days, then conquered it.

Main Menu

Learn PHP over here..

Started by The Tech, 05, 26

Previous topic - Next topic

The Tech

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 made 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 webserver 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.

The Tech

Your first PHP-enabled page


Make 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

Quote<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 make 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 Text Editors: There are many text editors and Integrated Development Environments (IDEs) that you can use to generate, 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: 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: 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 made a working PHP script, it is time to make 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.

The Tech

QuoteExample 2-2. Get system information from PHP

<?php phpinfo(); ?>  


Your first PHP-enabled page

24-May-2005 03:30
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
24-May-2005 03:30
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>

The Tech

Quote17-Jan-2005 08:25

OS X users editing in TextEdit will need to make sure their TextEdit preferences are set to allow plain text files.  Under the TextEdit pull-down menu, choose PREFERENCES, then under NEW DOCUMENT ATTRIBUTES in the window that pops up, click PLAIN TEXT.  

Then, in the section of that same window called "saving," DESELECT "append .txt extension to plain text files."  This will allow you to save your files with a .php extension.

Then close the PREFERENCES window.  You're good to go.
jo at durchholz dot org
30-Sep-2004 08:53
If PHP is running under Apache, there are very different ways to tell Apache what's a PHP script and whether it should be executed. If you can, locate the httpd.conf and look for the appropriate settings; if you can't, ask your site administrator.

The options are:
1) Make Apache interpret any PHP files it finds and serve them like HTML. This kind of set-up is rare, as it is extremely unsafe. PHP "safe mode" is intended to give some measure of protection in such situations, but it doesn't even approach that of setup (3b), below (safe mode is over-restrictive in some areas and not restrictive enough in others, and too many PHP scripts will break in safe mode anyway, so I decided against it - YMMV).
2) Make Apache interpret PHP files only if they are found in some specific URL area (usually /cgi-bin/whatever). This doesn't help in protecting different users from each other, but it makes it more obvious if, say, a file upload would overwrite a script. (It's not a real protective measure though. File uploads shouldn't be permitted except into specially designated data directories with a .htaccess file that disallows script execution of any kind. Actually this applies to any kind of file creation, e.g. many Wikis allow the user to type in a topic name and will make a text file with that name - so the directory in which the name is made should be made non-executable.)
3) Make Apache hand over .php, .sh, .pl etc. etc. to the Unix shell for interpretation. This has the advantage that Apache can use the "suEXEC" mechanism, which allows it to impersonate some other user than the standard "nobody" or "www-data". For example, if multiple users are allowed to make PHP scripts on the same server, the server administrator will make a separate user account for each, and have Apache impersonate the appropriate account. Unfortunately, this setup gives up a large amount of efficiency, which means that the hoster has to set up a larger machine for the same load. In other words, hosting accounts will be a bit more expensive but *far* more safe.
3a) A badly-configured setup of this kind will require that you insert a line like "#! /usr/bin/php4" at the top of each PHP file. Of course, this is simply too much work for even modest amounts of PHP on a site, but some (few) sites require this anyway.
3b) A better-configured setup will recognize file types from the file extension (just as Windows does it). If you have a (3a)-style setup and know or suspect your provider has a Linux box running, talk to him about the binfmt_misc extension. It requires about a hour to install properly and (possibly) a kernel recompilation (that's another hour or two if they are just running preinstalled boxes, and a near-zero overhead if they're installing their machines anyway).

Most sites combine setup (2) with safe mode. In that case, do a regular backup of everything that you have on the server, since your site is open to attacks from script kiddies that live on the same machine. (Source Forge had incidents of that kind.)
(Note that this kind of problem applies to Perl scripts, or any kind of scripting that can make or overwrite files. For example, the TWiki site on SourceForge got clobbered by this at least once - well, SourceForge is particularly vulnerable to this because anybody with a browser and pretending to do open source development will be allowed to upload CGI scripts.)
funkydruid at optusnet dot com dot au
09-Sep-2004 08:47
Mac OSX users

This website is brilliant for setting up php and mysql on max os x

http://www.entropy.ch/software/macosx/php/

Funky
Curtis
10-Aug-2004 05:47
Expansion on saving w/ notepad/wordpad: (tested on XP; but should work on 2000,NT, and 98)

You can associate the .php file extension w/ Windows w/o going into the registry.

Open up My Computer or MSIE in file mode. Go to folder options > File types tab. Now click new. Add the extension as PHP or php. If you can't find the PHP application in the dropdown list under advanced, just go OK, for now. At least the extension is in place.

Now, try and make a php file by using the directions from this page of the PHP tutorial (should save it with the rest of your HTML files, i.e. your DocumentRoot). If you go to view your php file listed in the directory, and you see that it's still a .txt file, right-click the icon to see if you can locate "open with." If so, you should be able to browse for the appropriate file, which should be at (may vary, depending on where you installed PHP):

C:\PHP\php.exe

Click that as the default program, and the PHP logo should appear on all your scripts, and no problems saving should occur w/ any program.

Good luck.
john at php dot com
01-Jan-2004 10:45
att. to adobe golive users,
golive is not widely seen as a comfortable php source code editor, as its use you might find it difficult but theres never a "no";
to work with php you must first realize the dynamic wizard (and its still more important if youre building a website)  
full-house with adobe golive cs, which is the newest one and it has improved in some aspects which newbies cannot see,
Slowpoke
10-Sep-2003 03:27
Mac Users
For those using MAC OSX, you've already got an Apache Server, you just need to switch it on.

Go to: preferences>sharing and turn 'personal web-sharing' on. Then open up you browser and go to http://localhost/ and you should get a screen telling you all about your server. Well done, your Apache Server is switched on and working.

There's a little more to it that that though. You may need to set up PHP and mySQL. I've taken the liberty of throwing you a very useful link that should get your server up and runninig with everything you need, as well as giving you a brief insight into how useful PHP and mySQL can be. It's a big'un!

http://www.macdevcenter.com
/pub/a/mac/2003/04/04/
apache_jaguar_pt1.html
(I had to break this to get it posted I'm afraid)

Thats all for now,

chow chow
Slowpoke
ryan420 at earthling dot net
03-Feb-2003 05:18
Note on permissions of php files:  You don't have to use 'chmod 0755' under UNIX or Linux; the permissions need not be set to executable.  Again, this is more like a html file than a cgi script.  The only mandatory requirement is that the web server process has read access to the php file(s).  With many Linux systems, it is popular for Apache to run under the 'apache' account.  Given that HTML and other web files, like php, are often owned by user 'root' and group 'web' (or another similar group name), acceptable permissions might be those achieved with 'chmod 664' or 'chmod 644'.  The web server process, running under the 'apache' account, will inherit read only permissions.  The 'apache' account is not root and is not a member of the 'web' group, so the "other" portion of the permissions (the last "4") applies.

The Tech

QuoteSomething 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 an autoglobal (or 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 make 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. You can find a list of PHP books at /books.php.

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 make 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.




add a note User Contributed Notes
Something Useful
please_more_spam at yahoo dot com
06-Mar-2004 09:00
It is also possible to do this:

echo <<<END

<a href="http://www.google.com" target="anywhere">Google.com</a>

Blah blah blah, You can put as much stuff in here. Nothing will END it untill "END;" blah blah blah

END;
mjbraca at hotNOSPAMmail dot com
09-Aug-2002 06:31
It wasn't immediately obvious to me what would happen if I jumped from PHP to HTML and back within a function definition. But of course it does the "right thing":

<?
function foo () {
 echo "Enter foo...";
?>Some HTML inside foo...<?
 echo "Leave foo.";
}
?>
 <HTML><BODY>
 <? foo(); ?>
 </BODY></HTML>

produces:

Enter foo...Some HTML inside foo...Leave foo.

The Tech

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 $_POST['name']; ?>.
You are <?php echo $_POST['age']; ?> years old.  

A sample output of this script may be:

Hi Joe. You are 22 years old.




It should be obvious what this does. There is nothing more to it. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER autoglobal; above we just introduced the $_POST autoglobal 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 autoglobal instead. You may also use the $_REQUEST autoglobal, 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.

The Tech

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 autoglobal 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 autoglobal 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.

The Tech

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: /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/