e-mail   
 Menu
  Home
  Download
  Top 10 Downloads
  Last 15 New Files
  Web Links
  Tips
  Last 15 New Tips
  NLM Programming
  Admins Club





SUPLA System
Internet of Things




Installation and Administration






Polish Forum SUSE


 
Who's Online

 There are currently,
11 guest(s)
that is (are) online.
 


Technical Information

Back to List of Categories

Technical Information about
  An Introduction to JBoss
  An Introduction to LDAP: Part 1-LDAP Primer
  An Introduction to LDAP: Part 2-Using LDAP to Create a User Authentication
  AppNote: Configuring an OpenSLP DA on OES or SUSE LINUX Enterprise Servers
  AppNote: Installing Oracle 10g on SLES9
  Developing PHP Scripts with SUSE LINUX
  Encrypting Data Partitions
  How to configure MySQL for NSS File System in OES for Linux
  How to install Webmin - A Web-Based System Admin Tool
  How to Run Binary-Only Application Packages on Various Versions of Linux
  Integrating Novell OES Linux iManager, Virtual Office and Welcome Page with Apache 2.2.2, Tomcat 5.5.17 and Sun Java2 1.4.2
  Keeping Sync with a Remote NTP Server
  Lab Guide for installing Open Enterprise Server with Linux Kernel
  Make your computer a SUSE LINUX Enterprise Server with a normal cable connection.
  Novell SLES9 vs Windows2003 Server
  NTP Active Servers
  Patching Open Enterprise Server with rug/Red Carpet FAQ
  Performance Tuning Installation Tips
  Remote administration

Technical Information
 Developing PHP Scripts with SUSE LINUX

Printer-friendly version

18 Jan 2005

PHP http://www.php.net/ is a very popular open source server-side embedded scripting language that is especially suited for Web development. In fact out of the roughly 14 million sites running on the Apache Web servers, over half are running PHP, according to the SecuretySpace.com, a consulting group that gathers statistics on Internet online services. PHP allows you to embed PHP code (very similar to C code) into your HTML documents to give your web pages dynamic content. PHP can perform any task that any CGI program can do, but its strength lies in its compatibility with many types of databases and adding database queries to a PHP script is a piece of cake. PHP has a relatively low learning curve, if a developer knows HTML and has some knowledge of the C programming language they can easily start developing impressive PHP scripts. This article will walk you through configuring Apache, PHP, and MySQL on SUSE LINUX (NLD, SLES, or Professional). It will also introduce you to a third party product named PhpEd, by NuSphere http://www.nusphere.com/ that can be used to simplify the development and debugging of PHP scripts.

Enable Apache, PHP, and MySQL

(Note: This section requires root user privileges)

SUSE Linux contains support modules for Apache and PHP that make setting up Apache and PHP a breeze. If these products were not installed as part of the original install you will need to install them using the Yast installer. If you are not sure if they are installed you may want use the runlevel editor under the System option in Yast and see if they are available to start. If you determine they are not installed or you need to install additional products shown below, select Install and Remove Software from the Software option and then search for apache. Select the following packages:

Apache 1.3x Web Server (apache)
PHP4 module for Apache 1.3x (apache-mod_php4)

Also install MySQL by searching for mysql and selecting the following packages.

MySQL Database Server (mysql)
MySQL Client (mysql-client)

Using the runlevel editor under the System option enable apache and mysql, or if you prefer you can start them manually by issuing the start command for the following applications.

Apache
/etc/init.d/apache {start | stop | restart}

MySQL
/etc/init.d/mysql {start | stop | status | reload | restart | try-restart | force-reload}

In addition to starting the services it is also important to know the directory location of where to put your PHP script files. On SUSE Linux that directory is /srv/www/htdocs. Also another important file to know about is the PHP configuration file /etc/php.ini. Later we will have you modify this file for remote debugging purposes.

For security reason the Apache documentation recommends that you don't grant write permissions to any user or group of users to the /srv/www/htdocs directory. Instead it recommends that you create a subdirectory and grant write permissions to that directory. Using Yast select Edit and create groups under the Security and Users option. Click the Set Filter button and select System Groups. Select the www group from the list of groups and click the Edit button. Select the check box for your <user name> from the Members of this Group list. Click the Next button, and then the Finish button. From a Terminal Window switch to the root user and create a misc directory under the /srv/www/htdocs directory (mkdir /srv/www/htdocs/misc). Change the group ownership of the /srv/www/htdocs/misc directory from root to the www group (chgrp www /srv/www/htdocs/misc). Assign read/write/execute permissions for the owner and group of the misc directory (chmod 775 /srv/www/htdocs/misc).

Create your first PHP Script

PHP has a function called phpinfo that returns a lot of valuable configuration information and is typically used for a first time script to ensure everything is setup properly. Use your favorite text editor to create a test.php file in the /srv/www/htdocs/misc directory with the follow lines.

<?php
	phpinfo();
?>

Open a web browser and enter http://localhost/misc/test.php for the location. If everything is setup correctly you should see multiple tables containing information about the current PHP environment.

These tables include valuable information about the current environment including the location of where different modules are installed and where configuration files are located. It also includes PHP variables that can be used in your scripts. For example try modifying your test.php script to print out the version of browser that is being used. Locate the variable _SERVER[“HTTP_USER_AGENT”], and notice that it shows the output of this variable in the right column. Add this PHP variable to the test.php script so that it will display the detected browser at the top of the page by adding the following:

<?php
	echo “<center>”;
	echo $_SERVER[“HTTP_USER_AGENT”];
	echo “</center><br>”;
	phpinfo();
?>

Let’s move on to something a little more useful.

Create a Table in the MySQL Database

By default when a MySQL database is installed it has two databases mysql, and test. The mysql database contains all the users and their credentials. By default the test database is empty and needs some tables added to it before we can start using it. Using the MySQL monitor, create a employees table in the test database. The following commands will create the table and display its properties.

student@linux:~> mysql

mysql> use test;

mysql > create table employees (id int auto_increment, firstname varchar(64), lastname varchar(64), address varchar(128), city varchar(64), state varchar(64), zipcode varchar(32), telephone varchar(32), email varchar(64), primary key (id));

mysql > show ables;

mysql > describe employees;
mysql > exit

NuSphere’s PhpED

Even though PHP scripts can be developed using nothing more than a editor and a browser, tools do exist that can speed up the development and debugging of your scripts. One of those tools is NuSphere’s PhpED. PhpED is a world-class PHP IDE that contains a powerful PHP editor and includes everything from a integrated web browser to an integrated debugger. It also has many other features including a integrated database client, integrated help system for many function libraries (including PHP, JavaScript, VBScript, HTML tags), and a profiler to improve on the efficiency of your code. PhpED also comes with it own web server so if you don’t have a web server installed it will still work. Later we will look at configuring PhpED to use a remote web server and use the Apache Web server we enabled through Yast.

Installing NuSphere

Installing NuSphere on SUSE Linux is a snap you simply execute an install shell script.
You can download a trial version of PhpED from http://www.nusphere.com/

Make the shell file an executable

chmod 777 NuSphere-phped-3.3.3evl-Linux.sh

Execute the install shell script

./NuSphere-phped-3.3.3evl-Linux.sh

Execute PhpED

./phped/start_phped

To begin using PhpED right click on the New workspace icon and create a new project. Simply take all the defaults for now including the name project1 for the name of the project and answer yes to create the new project directory. Right click on the new project1 icon, select New File, and then Php File from the New File Dialog, and click OK. This will give you a skeleton Php file for you to begin coding. Insert pnpinfo(); on line 2 between the opening and closing php tags and then run your script by clicking on the green arrow in the tool bar. In the Save As dialog change the file name to test.php and click the Save button.

On Linux a browser window should pop up with PHP configuration information. Notice that it is using PhpEd’s web server on port 8080 and is directed to the test.php file in the project1 directory. Close the browser and add a break point by clicking in the column to the left of the phpinfo(). Run the script again only this time click on the green arrow with the D under it. Notice that the browser window pops up, but the debugger breaks in the code allowing you to step through your code. Isn't that cool? Press F9 to continue.

We need a little more code to really see the benefit of the debugger. The following example will read records from the employees table of the test database and write them to the screen, and then prompts the user for a new entry. Right click on the project1 icon and create a new Php file. Cut and paste the code shown below to this new file. Save the new file as sample1.php. Put a break point on the line after the if statement. Run this example in the debugger and see if you can view variables in the bottom left pane before the they are saved to the database. Hint the F7 & F8 will single step you through the code, F7 steps into functions, and F8 steps over functions.

<HTML>
<BODY>
<?php   	
   //Connect to the database
   $db = mysql_connect("localhost", "root", "");	
   mysql_select_db("test", $db); 	

   //Save the record
   if(isset($_REQUEST['Submit'])) {		
      $firstName = $_REQUEST['fname'];
       $lastName = $_REQUEST['lname'];
       $address = $_REQUEST['address'];
       $city = $_REQUEST['city'];
       $state = $_REQUEST['state'];
       $zip = $_REQUEST['zip'];
       $phone = $_REQUEST['phone'];
       $email = $_REQUEST['email'];

       $sql = "INSERT INTO employees VALUES
       ( 0,'$firstName','$lastName','$address','$city','$state','$zip','$phone','$email')
       ";		

       $result = mysql_query($sql, $db);
   }    

   $result = mysql_query("SELECT * FROM employees ORDER BY lastname", $db);

   // display list if there are records to display
   while ($myrow = mysql_fetch_array($result)) {			
      printf("%s %s<BR>%s<BR>%s, %s  %s<BR>%s<BR>%s<BR><BR>", $myrow["firstname"], $myrow
               ["lastname"], $myrow["address"], $myrow["city"], $myrow["state"], $myrow
               ["zipcode"], $myrow["telephone"], $myrow["email"]);
   }	

   printf("<FORM method='POST' action='%s'>", $_SERVER["PHP_SELF"]);
?>   
   <TABLE>
      <TR><TD>First Name</TD><TD><INPUT type="text" name="fname"></TD></TR>
      <TR><TD>Last Name</TD><TD><INPUT type="text" name="lname"></TD></TR>
      <TR><TD>Address</TD><TD><INPUT type="text" name="address"></TD></TR>
      <TR><TD>City</TD><TD><INPUT type="text" name="city"></TD></TR>
      <TR><TD>State</TD><TD><INPUT type="text" name="state"></TD></TR>   
      <TR><TD>Zip Code</TD><TD><INPUT type="text" name="zip"></TD></TR> 
      <TR><TD>Phone</TD><TD><INPUT type="text" name="phone"></TD></TR>
      <TR><TD>Email</TD><TD><INPUT type="text" name="email"></TD></TR>
      <TR><TD></TD><TD><INPUT type="submit" value="Submit" name="Submit"></TD></TR>
   </TABLE>
   </FORM>
</BODY>
</HTML>

Configure PhpED's DB Client

Select Tools, then Accounts from the main menu. Right click on Database accounts and select new, then MySQL. Enter localhost for the IP address, test for the Initial database, and root for the Login Name and click OK. There are four tab buttons at the bottom of the right pane of the main window. Mouse over each of them and click on the DB Client tab. At this point you should be able to expand the tree for the mysql1 account down to the fields of the database. This feature allows you to quickly find and view the different fields of the database when you are writing PHP code.

Configuring for a remote Web Server

Although the PhpED web server is great for testing simple scripts, it has limitations and is unlikely that you would ever use it to service your PHP scripts. Instead you would more than likely use Apache or some other web server. However, just because you are going to use a remote web server doesn’t mean that you won’t want to debug your scripts from time to time. Fortunately PhpED has made it possible to debug script running a on remote web server. In order to do this it is necessary to modify the /etc/php.ini file to include debug modules and define which IP addresses to grant access.

Make sure the extension_dir points to the PHP extensions directory. On SUSE this is done by default.

extension_dir = /usr/lib/php/extensions

Copy the correct debugger module for the Linux platform and PHP version from the phped/debugger subdirectory to /usr/lib/php/extensions. Rename the module to dbg.so as you copy it.

cp phpded/debugger/dbg.so-4.3.4 /usr/lib/php/extensions/dbg.so

Append the following lines to the /etc/php.ini file and substitute any addresses for the correct IP address of the system you will use to debug with.

extension=dbg.so
[debugger]
debugger.enabled=on
debugger.profiler_enabled=on
debugger.hosts_allow=localhost 137.65.137.126
debugger.hosts_deny=ALL
debugger.ports=7869, 10000/16

Restart your web server, if you are using Apache that can be done by the following command:

/etc/init.d/apache restart

Open a web browser and browse to http://localhost/misc/test.php. You know that debugger is working if you see DBG v2.16.14, (C) 2000,2004, by Dmitri Dmitrienko added to the Powered by Zend frame.

Right click on the project1 icon in the left window pane and select properties. In the mapping section change the Run mode from System default to HTTP mode (3rd party WEB server), enter http://localhost for the Root URL, and /srv/www/htdocs/misc for the Remote root directory. Click on the mapping tab at the top of this dialog and notice that remote directory is mapped to the local directory. Click OK to close the window.

Copy the projects/project1/sample1.php to /srv/www/htdocs/misc directory, or to get a little more exposure to some of the PHP API enter the following example. This example basically does the same thing as the previous example except that it allows you to upload a comma delimited text file which is then used to populate the database instead of entering records one at a time.

<HTML>
<BODY>
<?php
   $db = mysql_connect("localhost", "root", "");

   mysql_select_db("test", $db);

   if(isset($_REQUEST['Submit'])) {
      if (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
         $handle = fopen($_FILES['uploadedfile']['tmp_name'], "r");

         for($string = fgets($handle, 128); !feof($handle); $string = fgets
            ($handle, 128)) {
            list($fname, $lname, $address, $city, $state, $zip, $phone, $email) = 
               explode(",", $string);

            $sql = "INSERT INTO employees  VALUES (0,'$fname','$lname','$address',
               '$city','$state','$zip','$phone','$email')";

            $result = mysql_query($sql, $db);
         }

         fclose($handle);

         unlink($_FILES['uploadedfile']['tmp_name']);
      }
   }

   $result = mysql_query("SELECT * FROM employees ORDER BY lastname", $db);

   while ($myrow = mysql_fetch_array($result)) {
      // display list if there are records to display
      printf("%s %s<BR>%s<BR>%s, %s  %s<BR>%s<BR>%s<BR><BR>", $myrow
	["firstname"], $myrow["lastname"], $myrow["address"], $myrow["city"],
	$myrow["state"], $myrow["zipcode"], $myrow["telephone"], $myrow["email"]);
   }

   printf("<FORM method='POST' enctype='multipart/form-data' action='%s'>", $_SERVER
        ["PHP_SELF"]);
?>

   <INPUT type="hidden" name="MAX_FILE_SIZE" value="20000" />
   <P>
   Import a coma delimited file with the following format:<br/>
   &nbsp;&nbsp;&nbsp;<b>First Name, Last name, Address, City, State, Zip Code, Phone,     
        Email Address</b><br/>
   </P>
   File <INPUT type="file" name="uploadedfile" size="20">
   <BR/>
   <BR/>
    <INPUT type="submit" value="Import File" name="Submit">
   <BR/>
</FORM>
</BODY>
</HTML>

Once again put a break point on the line after the if statement and debug the script. Notice that this time the browser is addressing the Apache web server instead of PhpEd’s web server (No port 8080 in URL).

Publishing to the Web remote server

Being able to debug on the remote web server is really powerful, but having to copy files from the project directory to the htdocs directory could get old really fast. If your remote web server is on the same system that you are developing on which is often the case for doing development, you might want to point your root directory to the /srv/www/htdocs directory. However, at some point it will be necessary to put your files in the htdocs directory that can be seen by the rest of the world. PhpEd allows you to create either a Web DAV or FTP account for the server you wish to publish your files to, and then with the click of a button publishes your files to that account.

Enabling the pure FTP server on SUSE

Using Yast select the Network Services (inetd) from the Network Services option and enable the /usr/sbin/pure-ftpd ftp server.

In the PhpED IDE select Tools, then Accounts from the main menu. Right click on File transfer accounts and select new and then FTP. Enter localhost for the Hostname or IP address, / for the Initial directory, <your username> for the Login Name, and <your password> for Password, and click OK.

Right click on the project1 icon in the left window pane and select properties. In the publishing section select the ftp1 account you just created. Enter /srv/www/htdocs/misc for the Top publishing directory, and click OK. At this point you can select Project, then Upload from the main menu and upload either an entire project or single file.

Conclusion

SUSE Linux is basically pre-configured to be a great platform for developing PHP scripts, and as was seen by the steps in this article setup of Apache, PHP and MySQL was extremely simple, basically starting a few services. With what you have learned from this article you have everything you need to get started developing PHP scripts on the SUSE Linux line of products. In addition, I have also introduced you to a third-party product, NuSphere's PhpEd, that can greatly simplify the development and debugging of PHP scripts.






Since 2003

Portal posiada akceptację firmy Novell Polska
Wszystkie materiały dotyczące produktów firmy Novell umieszczono za zgodą Novell Polska
Portal has been accepted by the Novell Polska
All materials concerning products of Novell firm are placed with Novell Polska consent.
NetWare is a registered trademark of Novell Inc. in the United States and other countries.
Windows is a trademark or a registered trademark of Microsoft Corporation in the United States and other countries.
Sybase is a registered trademark of Sybase Inc. in the United States of America.
Other company and product names are trademarks or registered trademarks of their respective owners.