Saturday, July 2, 2011

Programming with php in a local environment

I have two files, main.php and register.php that I've been editing. I renamed their extensions to .txt so that you can view them here. If I had left them as .php's, they'll try to run when you click on the filenames. You'll see that they are nothing fancy, just an initial draft to get you started. So, now I'd like to show you how to execute those files.

I told you my directory name at the beginning of the post. So, type into your browser: "localhost/eclipseworkspace/projectX/main.php" If I had named it "index.php" instead of main, then you could skip the filename. This code shows how you can validate the fields of the form in PHP, and give the user an error message if something is wrong.

It works fine except for one problem: if there are multiple errors, such as a zero length username AND a zero length password, then only one error message is displayed to the user. In this case it's the password error message, since that check occurs later in the code.

To fix this, we can change the code to keep an array of error messages. Here's how we'll do that: 1. Instead of setting $error=false, lets instead create an empty array, and let's make the variable plural $errors instead of $error. Of course, you know that a compiler, or in this case the PHP interpreter, does not really distinguish between singular and plural form.

It just helps make the variable names more meaningful for us: In this case where it's just one line of HTML to be output, that's not a bad way to do it. But when sending long stretches of HTML I think the format where you jump back and forth between PHP and HTML is the way to do. You end up with a file that looks more like HTML code with PHP sprinkled in, rather than an onslaught of PHP echo statements.

That might be hard to visualize with just a small example like this, but if you code up an entire page you'll see what I mean. The idea of echo'ing all output from a PHP program would be similar to writing a C program where you printf all the HTML. Come to think of it, you could actually write all this pure C. You could have an Apache module that links in your C code as a shared library.

It would handle the TCP connection from the browser, doing printf's to send the HTML and other content to the browser. In other words, you'd be generating the HTML from your C program entirely. All the things that we are doing with PHP, you could do it with C instead in which case you would not need to switch between PHP and HTML. However, it'd be more complex. Say you needed to make a change, with PHP you just edit the file and you are done; with C, you have the extra step of compiling which will slow you down. Then you have to restart the web server process.

No comments:

Post a Comment