Welcome, Guest
  • Author Topic: Web Serving OS X 10.2 (Jaguar) Part 1 (PHP, MySQL, Apache)  (Read 17066 times)

    Flash-db

    • Administrator
    • Systems Administrator
    • *****
    • Posts: 1876
      • View Profile
      • Flash-db.com
    Originally Posted By:  Syion
    Original Thread:  http://www.flash-db.com/Board/index.php?board=4;action=display;threadid=2091

    Moved To Technical Reference Area by Flash-db.

    =======================================================
    Hello everybody,

    MY 1st post. !!!!

    Anyway, I work for Apple in their education division. So I am familiar with the Mac but not a GURU on it. =)
    INTRODUCING APACHE TO THE MAC FAITHFUL:

    Apache is regarded as the most popular web server available today. With its incredible portability and support for anything you'd ever want to do, Apple wisely decided to ship Apache with its Unix-based operating system. With this web-serving powerhouse at your fingertips, I'll explain how you can impress your boss and solidify your love for Mac OS X, all at the same time.

    GETTING STARTED WITH APACHE AND MAC OS X

    The easiest way to begin Apache web-serving is via your Mac OS X system preferences. Click your Apple Menu, choose "System Preferences," then select "Sharing". Within the Sharing preference panel you'll see a number of options, only one of which is of immediate value. See that Web Sharing label? Simply click the Start button beneath it to fire-up the built-in Apache web server.

    By default, the Apache server has been configured to use your Mac OS X "short" user name. (You can find your short user name in the Users preference panel. Click on "Edit User".) If your short user name is "morbus", for example, you can access your personal web site by opening any web browser on the local network and typing http://127.0.0.1/~morbus/. Don't forget that last forward slash!

    That 127.0.0.1 (also known as "localhost") is pretty special -- every computer has one. Both names represent the computer itself; by going to 127.0.0.1 in a web browser, you are accessing the local Apache web server you activated in the Sharing preference panel.

    Now that you know an easy way to serve a site to local users, how do make your web pages available to folks on the World Wide Web?

    The answer is found in your Sharing preference panel. Go there and note the IP address listed. Using that IP address is how outsiders can access your Apache server. If you see 209.204.146.22, visitors could access http://209.204.146.22/~morbus/ and visit your personal web site. In a future article, I'll discuss how to block outside access to only those you deem worthy.

    YOUR PERSONAL WEB SPACE

    If you went to your personal web site now, you'd see a generic introduction written by Apple describing Apache and how to use "Personal Web Sharing." We'll soon be deleting this page, but be sure to give it a read because it contains some helpful bits of information.

    Much in the same way your personal web site is based on your user name, so is the location of your web space in the Mac OS X file system. Continuing our assumption of the "morbus" user name, our current web space lives at /Users/morbus/Sites/

    If you browse there now, you'll see the introductory file (index.html) as well as an images/ subdirectory. Delete (or back up) everything, and use a text editor (such as BBEdit) to create a new index.html file with the following contents:

    html>
    <body>

    <h1>Gleefully Served by Mac OS X</h1>

    </body>
    </html>


    Upon saving, reload http://127.0.0.1/~morbus/, and you'll see your rather bland, boring homepage. This certainly isn't very impressive -- downright pathetic, actually. You can't use server-side includes, can't install CGI programs to your /Sites directory, and can't use PHP or mod_perl. Plus, your inTRAnet is wide open to the InTERnet. Not so good, bub.

    TURNING ON THE MAGIC
     
    What we've done so far won't impress anyone. We have no features and an ugly web site address filled with tildes and unprofessional user names. We've got a long way to go before we can feel good about showing off our masterful Mac OS X box.

    Our first step is to give the site a prettier URL. Above, we placed our index.html file into our own user directory (such as /Users/morbus/Sites/) -- now, we'll place a copy into Apache's DocumentRoot. The DocumentRoot is the default server (not user) location that Apache will serve documents from. For Mac OS X, this is located in the /Library/Webserver/Documents/[/b] directory.


    LOCALIZATION OR "CONTENT NEGOTIATION"

    If you browse to /Library/Webserver/Documents/, you'll inadvertently run across another nice feature of Apache: content negotiation. Depending on your visitor, Apache can serve up international versions of your site -- for example, index.html.en for English speakers, or French (index.html.fr) and German (index.html.de) versions. Apache for OS X comes with over 25 translated versions of the default index.html file.

    You can take advantage of this feature on your own pages. When you're creating the GatesMcFarlaneCo intranet in your native language, you can translate your pages into other languages and add the two-letter language encoding ("de" for German", "fr" for French, "es" for Spanish, etc.) to the file name. Any time international employees of GatesMcFarlaneCo access your intranet, they'll automatically be served the page that's in their native tongue.

    For now, backup or delete all the files you see in /Library/Webserver/Documents/ and copy over the index.html file we created a few steps ago. If you return to http://127.0.0.1/, you'll see our "Gleefully Served" page.


    « Last Edit: 09/28/02, 17:46 by Flash-db »
    Flash-DB

    Flash-db

    • Administrator
    • Systems Administrator
    • *****
    • Posts: 1876
      • View Profile
      • Flash-db.com
    Web Serving OS X 10.2 (Jaguar) Part 2
    « Reply #1 on: 09/28/02, 17:37 »
    Part 2 by: Syion
    ======================================================

    Hallow,

    KNOW BEFORE YOU GO

    Well now you should have a prettier URL, but still a rather boring site. I'm going to assume that you know how to edit and save files via the command line, either through a native shell editor (VI or Emacs) or via a GUI editor such as BBEdit.
    Before we can proceed we need to know where Apache's configuration file lives. To find out we need to quere the Apache web server itself, with this command line:

    httpd -V

    This will spit out a screen of information specific to your Apache installation. (This will work on any platform, Win, Linux, Mac). We should now be looking at something like this.

    Server version: Apache/1.3.26 (Darwin)

    As well as where the config file is located:

    -D SERVER_CONFIG_FILE="/etc/httpd/httpd.comf"

    the httpd.comf is the configuration file for the Apache Webserver, this is where we are going to edit Modules and Types to turn on CGI, PHP, and PERL so that the Apache webserver will be able to display these cool things.

    TURNING ON CGI, TIME TO PLAY

    CGI: What is CGI you ask, well let me explain. CGI allows us to install thousands of different scripts that can be accessed through a normal web browser. CGI scripts are often written in Perl (also installed by default) and can allow users to access databases, use interactive forms, chat in bulletin boards, and so on. (Syion looks around, hmm looks like we are using CGI right now).

    Apache comes with two simple scripts that can verify CGI is configured correctly. Before we test them, however, let's see what we can learn from the Apache configuration file. To start, open up your config file in your favorite text editor (the example below assumes BBEdit 6.5):

    bbedit /etc/httpd/httpd.conf

    Be forewarned: The Apache configuration file is rather large, but also well documented. Take its introductory warning to heart: "Do not simply read the instructions ... without understanding what they do. They're here only as hints or reminders. If you are unsure consult the online docs. You have been warned." For your own reference, the online docs are available at the Apache web site.

    The quickest way to find and learn about the Apache configuration file is to search for the feature you want to enable. In our case, we'll start looking for "CGI". The first entry we find is:

    LoadModule cgi_module libexec/httpd/mod_cgi.so
    Followed shortly by:
    AddModule mod_cgi.c

    You'll see a number of these lines within the Apache config file. If you've ever worked with a plug-in-based program, you'll easily recognize their intent -- these lines load different features into the Apache web server. Apache calls these "modules", and you'll see a lot of module names start with mod_, such as mod_perl and mod_php. Lines that are commented out (that is to say lines that are prefaced with a # character) are inactive.

    For example,

    I have module

    # LoadModule A
    # LoadModule B

    TEXT

    # AddModule A
    # AddModule B

    These modules are inactive. for me to make them active and apart of the Apache Webserver then I just need to remove the # character and they will become active.

    Lets move on to our next search:

    # AddHandler cgi-script  .cgi

    If CGI access is turned on already, we should be able to reach http://127.0.0.1/cgi-bin/test-cgi and see a happy result, right? If you went to that URL, however, you were probably greeted by a not so joyous response: "FORBIDDEN". Apache screams, "You don't have permission to access /cgi-bin/test-cgi.

    Huh? Why didn't this work? Now is a perfect time to prove how useful the Apache web server logs can be. If you recall the results of our httpd -V command above, Apache's access file is located in /var/log/httpd/access_log. Let's look at the very last lines of that file, easily reached with this command:

    tail /var/log/httpd/access_log[/]

    You'll see that the last line looks similar to:

    127.0.0.1 - - [19/Nov/2001:21:59:46-0500]
    "GET /cgi-bin/test-cgi HTTP/1.1" 403 292


    Quickly, this line shows where the access request came from (127.0.0.1), the time the file was requested, the protocol used (HTTP/1.1), the response code (403), and the size of the response (292 bytes). This is all fine and dandy, but doesn't tell us what went wrong. For this, we'll dip into our error log (also pinpointed by the httpd -V command):

    tail /var/log/httpd/error_log

    And we see:

    [Mon Nov 19 21:59:46 2001] [error] [client 127.0.0.1]
      file permissions deny server execution:
       /Library/WebServer/CGI-Executables/test-cgi


    Bingo! This tells us exactly what went wrong -- the file permissions were incorrect. For Apache to run a CGI script, the script in question needs to have "execute" permissions. To give the test-cgi file the correct permissions, we run:

    cd /Library/WebServer/CGI-Executables

    then

    chmod 755 test-cgi

    After doing the above, load the URL again, and you should be happily greeted with gobs of environment information. (To learn more about permissions, the chmod utility, and the server environment, consult your favorite search engine, friendly geek, or O'Reilly-stocked library).

    With the basics of CGI out of the way, you can now install CGI-based applications to complement your intranet. Need a content management system for the developers to keep everyone up to date on their coding progress and discussions? Try Movable Type.
    « Last Edit: 09/28/02, 17:46 by Flash-db »
    Flash-DB

    Flash-db

    • Administrator
    • Systems Administrator
    • *****
    • Posts: 1876
      • View Profile
      • Flash-db.com
    Web Serving OS X 10.2 (Jaguar) Part 3
    « Reply #2 on: 09/28/02, 17:38 »
    Part III by:   Syion
    ======================================================

    TURNING ON SERVER-SIDE INCLUDES

    Server-side includes, better known as SSIs, allow you to include content from other files or scripts into the page currently being served. This is done by Apache before the page is actually shown to the user -- they'll never know what you've included or where.

    Commonly, SSIs are used to include things such as headers, footers, and "what's new" features across an entire site. When you need to change the background color of your site, for instance, you can change the header file only, and the color will be reflected immediately wherever you've included that file.

    SSIs, by default, are turned off. To turn them on, we're going to use the same "search for the feature" trick we did above. Open your Apache configuration file, and search for "server side." Our only match grants us the following:


    # To use server-parsed HTML files
    #
    # AddType text/html .shtml
    # AddHandler server-parsed .shtml

    Happily, this is exactly what we're looking for. Those simple "Add" lines tell us a lot. They establish a pattern based on what we already know about CGI. If you recall above, we could have turned on the CGI feature for files ending in .cgi -- in other words, any file you created with the .cgi extension (whether it was a CGI program or not), would be treated as an executable script.

    Likewise, these lines are telling us that we can turn on the server-side include feature for files ending in .shtml. Whether we actually use the SSI feature in these files doesn't matter -- they'd still be treated and processed as if they did.

    This is important. You may be thinking "If SSIs are so great, why not enable them for .html filenames?" Ultimately, it's a matter of speed. If you have 3,000 .html files, and only 1,000 of them actually use SSI, Apache will still look for SSI instructions in the other 2,000. That's a waste of resources. Granted, processing SSI incurs very little overhead, but if you're being hit 50,000 times a second, it can certainly add up. This isn't too worrisome for our GatesMcFarlaneCo intranet, but is good to know for your future Apache projects.

    For now, uncomment the AddType and AddHandler lines. This will turn on the SSI mojo power. But where? When we were learning about CGI, we saw a configuration setting that said our CGIs lived in /Library/Webserver/CGI-Executables/ -- we now have to tell Apache where we want our SSI capability to take place.

    Because we've building an intranet, that's going to live in /Library/Webserver/Documents, that's where we want our SSI capability to be active. Go to the top of your Apache configuration file and search for "/Library/Webserver/Documents/". The second result looks like the following (we've removed the commented lines from this example):


      <Directory "/Library/WebServer/Documents">
            Options Indexes FollowSymLinks MultiViews
            AllowOverride None
            Order allow,deny
            Allow from all
      </Directory>

    You'll notice that this looks similar to the <Directory> entry we saw when we were looking into CGI. As before, we're going to skip the brunt of it (we'll pay attention to our ignored lines a little bit later in our series). For now, add the word Includes to the Options line. Options is an Apache directive that can turn on or off different features for the <Directory> and all subdirectories beneath it. Subdirectories can override their parent configuration.

    Because we've made changes to Apache's configuration file, we now need to restart Apache. The easiest way to do this is via our Sharing preference panel. Much like we started the sharing preference in part one of this series, we can stop and start to enable our changes. Do this now. Chuckle once or twice, if you must.

    To test that our SSIs are working properly, rename your index.html file to index.shtml (because .shtml is the only extension we've enabled SSIs for), and edit to match the snippet below:


    <html>
     <body>
      <h1>Gleefully Served By Mac OS X</h1>
        <pre><!--#include virtual="/cgi-bin/test-cgi"-->
        </pre>
     </body>
    </html>

    Here, we're including the test CGI script into the contents of our main index page. When you load http://127.0.0.1/ into your browser, you'll see our "Gleefully Served" message, as well as the output of the CGI script itself. We could just have easily created a static web page (say, "navigation.html"), and included that within our page instead.
    « Last Edit: 09/28/02, 17:47 by Flash-db »
    Flash-DB

    Flash-db

    • Administrator
    • Systems Administrator
    • *****
    • Posts: 1876
      • View Profile
      • Flash-db.com
    Web Serving OS X 10.2 (Jaguar) Part 4 (Turning on PHP)
    « Reply #3 on: 09/28/02, 17:39 »
    Part 4 by:  Syion
    ======================================================

    TURNING ON PHP4

    Much like CGI, PHP is very popular and well supported, and very often installed on Web hosts by default. Much like SSI, the code is included and interpreted into the actual HTML of your Web pages.

    Just like our other sections on CGI and SSI, turning on PHP involves searching for the feature name ("php") within our Apache configuration file. The first entries we come up against are:


        # LoadModule php4_module     libexec/httpd/libphp4.so
        # AddModule mod_php4.c


    These lines are just like those we encountered when we were messing around with CGIs -- they enable or disable the loading of PHP on a restart of our Apache Web server. Since they're commented with that little "#" character, we've got to remove the "#" to enable them. Do that now.

    Moving on to our next search result, we see:


        # For example, the PHP 3.x module will typically use:
        #
        # AddType application/x-httpd-php3 .php3
        # AddType application/x-httpd-php3-source .phps
        #
        # And for PHP 4.x, use:
        #
        # AddType application/x-httpd-php .php
        # AddType application/x-httpd-php-source .phps

    We saw these same sorts of lines when we were enabling SSI. In essence, they're saying that any file with the .php extension should be processed by the PHP module we just enabled. As we'll see soon enough, Mac OS X (versions 10.1 and above) comes pre-installed with PHP 4, so go ahead and uncomment the two "for PHP 4.x" lines. Save the Apache configuration file, and stop and start the Web server using the "Sharing" preference panel.

    We're going to return to our Apache error log for a second to illustrate a simple, yet helpful bit of information. Each time you start Apache, it will spit out a single line telling you that everything has started successfully. Often times, it will look like so:


        [notice] Apache/1.3.26 (Darwin) configured
            -- resuming normal operations


    When you add a third party module or feature (like PHP, mod_perl, mod_ssl, etc.), Apache will graciously make mention of it in its startup line. If you just restarted the Apache Web server now, take a look at the error log by typing:

        tail /var/log/httpd/error_log

    You should see Apache wax poetic with:

        [notice] Apache/1.3.20 (Darwin) PHP/4.0.6
            configured -- resuming normal operations


    Apache tells us that PHP is enabled, but how do we really know for sure? Rather easily, actually. Take that index.shtml file that we were testing SSIs with, and rename it to index.php. Now, replace the contents with the following:

        <html><body>
            <h1>Gleefully Served By Mac OS X</h1>
            <? phpinfo()?>
        </body></html>

    Finally, go to http://127.0.0.1/index.php and you should see a long page full of PHP diagnostic information. If so, rub your hands with a gleam in your eye, because PHP has now been added to your arsenal. Want to add a simple Web-based email program for your traveling coworkers? Check out PHPost. Note: Most PHP applications require a sophisticated database backend, like MySQL or Postgres -- PHPost is one of the few that doesn't. While installing and configuring these database systems is relatively easy on Mac OS X, it would be outside the scope of this primer.

    DOWNLOADING AND INSTALLING PHP4

    Well now that we've configure our Apache server to use PHP we now need to acutally install and work with PHP.

    The best resource I have found for installing PHP is: http://www.entropy.ch/software/macosx/php/

    Follow the instructions CAREFULLY.
    « Last Edit: 09/28/02, 17:43 by Flash-db »
    Flash-DB

    Flash-db

    • Administrator
    • Systems Administrator
    • *****
    • Posts: 1876
      • View Profile
      • Flash-db.com
    Web Serving OS X 10.2 (Jaguar) Part 5 MySQL
    « Reply #4 on: 09/28/02, 17:41 »
    Part 5 by:  Syion
    ======================================================

    MYSQL

    Well i figure that you also went to Marc's site and found the MYSQL aspect of it as well. if not the URL for this is: http://www.entropy.ch/software/macosx/mysql/

    Here's a little PHP script you can run to see if your MYSQL is working.

    Copy the following code into your favorite text editor (like BBEdit), and save the file as test.php within a Web site directory (either /Library/WebServer/Documents/ or /Users/morbus/Sites, for example).


    <?
       print "<pre>";

       // log into our local server using the MySQL root user.
       $dbh = mysql_connect( "localhost", "root", "" );


       // select the 'test' database created during installation.
       mysql_select_db( "test" ) or die ( mysql_error() . "\n" );
       print "Connection to the database has been established.\n";


       // create a simplistic table.
       $table = "CREATE table wisdom (
                 id int(4) PRIMARY KEY AUTO_INCREMENT,
                 wisdom char(255), author char(125) );";

       $response = mysql_query( $table, $dbh );
       if ($response) { print "The table was created correctly!\n"; }
       else { print mysql_error () . "\n"; }


       // now, we'll add some data to our newly created table.
       // to add different wisdom, just change the 'values'.
       $insert_data = "INSERT into wisdom ( wisdom, author )
                       values ( 'Must... remain... awake!', 'Morbus' );";

       $response = mysql_query( $insert_data, $dbh );
       if ($response) { print "The data was inserted correctly!\n"; }
       else { print mysql_error () . "\n"; }


       // and read it back for printing purposes.
       $get_table_data = "SELECT * FROM wisdom;";
       $response = mysql_query( $get_table_data, $dbh );
       if ($response) { print "We successfully got all the table data.\n"; }
       else { print mysql_error () . "\n"; }


       // now print it out for the user.
       while ( $one_line_of_data = mysql_fetch_array( $response ) ) {
           extract ( $one_line_of_data );
           print "#$id: $author sez: \"$wisdom\"\n";
       }

       print "</pre>";
    ?>

    Note: Again, we're not going to explore the syntax of the PHP script, or the SQL commands that are used. Suffice it to say that this script will create a table in the MySQL 'test' database, add some data, and then spit back the total contents of the 'wisdom' table.

    Here is what you should see. or something similar

    Connection to the database has been established.
        The table was created correctly!
        The data was inserted correctly!
        We successfully got all the table data.
        #1: Morbus sez: "Must... remain... awake!"

    By default, the MySQL root user has no password assigned to it. If you take a gander back at our PHP script, you'll see that we connect to our database with that field blank:


       // log into our local server using the MySQL root user.
       $dbh = mysql_connect( "localhost", "root", "" );

    The simplest step in beginning to secure our database server is to set a password for MySQL's root user. To do so, enter the following in a Terminal:


        mysqladmin -u root password new_password_here

    Once we do that, we'll have to modify our PHP code as well:


       // log into our local server using the MySQL root user.
       $dbh = mysql_connect( "localhost", "root", "new_password_here" );

    This is just the start of securing a MySQL installation. You can go much deeper, like restricting access to certain databases by host name, much like we restricted access to certain Web directories with Apache's Allow and Deny directives

    Well that's it. Good luck all and happy coding.
    « Last Edit: 09/28/02, 17:44 by Flash-db »
    Flash-DB