Detect if a form is submitted

If a form has not been submitted yet, you’ll get an error message if you try to get the values of the form. (Unlike in ASP, which just returns an empty string.)

To detect if a user form has been submitted, use the following code:

if ($_SERVER['REQUEST_METHOD'] == "POST") {
Posted in Uncategorized | Comments Off on Detect if a form is submitted

Mirosoft SQL Server vs. MySQL Server

Note to self: Minor difference between the TOP command in MSSQL and MySQL equivalent.

-- MS-SQL / SQL-Server
SELECT TOP 10 * FROM ExampleTable WHERE Active = 1 ORDER BY Id DESC
-- MySQL
SELECT * FROM ExampleTable WHERE Active = 1 LIMIT 0,10 ORDER BY Id DESC
Posted in sql | Tagged , , | Comments Off on Mirosoft SQL Server vs. MySQL Server

PHP File uploading of Large Files in MAMP PRO

If you want to upload large files and your MAMP setup is not working and giving you an error message (in my case, the $_FILES variables were not being even set), check some parameters in your PHP.INI file.

In MAMP PRO, go to File -> Edit Template -> PHP53.ini

Make sure file_uploads is ON and check the upload_max_filesize.

; Whether to allow HTTP file uploads.
file_uploads = On

; Temporary directory for HTTP uploaded files (will use system default if not
; specified).

upload_tmp_dir = /Applications/MAMP/tmp/php

; Maximum allowed size for uploaded files.
upload_max_filesize = 100M

You may also need to modify the execution time parameters:

max_execution_time = 60  ; Maximum execution time of each script, in seconds
max_input_time = 180     ; Maximum amount of time each script may spend parsing request data
memory_limit = 100M      ; Maximum amount of memory a script may consume (8MB)

I think my settings above are overkill, but hey… it’s just on my test web server.

After I did these changes, my large file uploads worked fine in MAMP PRO.

Oh, and just for good measure… also check your form MAX_FILE_SIZE parameter.

<input type="hidden" name="MAX_FILE_SIZE" value="105000000" />
Posted in Uncategorized | Tagged , , , | Comments Off on PHP File uploading of Large Files in MAMP PRO

PHP Easy file uploading vs. ASP file uploading

I have to admit, uploading a file in PHP is so much easier than doing the same thing in ASP.

With ASP, I used a 3rd-party component (DLL) SA-FileUpload to do my file uploads.

With PHP, file upload capability is already built-in. The file information can easily be accessed by the following variables.

echo 'filename: ' . $_FILES['uploadfile']['name'];
echo "<br>";
echo 'file type: ' . $_FILES['uploadfile']['type'];
echo "<br>";
echo 'size: ' . $_FILES['uploadfile']['size'];
echo "<br>";
echo 'tmp_name: '. $_FILES['uploadfile']['tmp_name'];
echo "<br>";
echo "error code: " . $_FILES['uploadfile']['error'];

The uploaded file is stored in a temporary location with a temporary filename. Then you do your file validation, and if everything is OK, you need to move the temporary file to it’s final destination and filename.

// this is our upload directory
$uploaddir = 'uploads/';

// build fullpathname ,i.e. uploaddir + filename
$uploadfile = $uploaddir . basename($_FILES['uploadfile']['name']);

… do your file validation here, check file extension, size, etc…

if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
$errmessage ="file upload failed";
echo $errmessage;
} // end if move

Easy peasy!

Any failure in the file upload process will be registered in this variable.

$_FILES[‘uploadfile’][‘error’]

Possible values are (say you’re using a Switch statement):

case UPLOAD_ERR_INI_SIZE:    // 1
   return 'ERR: The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:    // 2
   return 'ERR: The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:    // 3
   return 'ERR: The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:    // 4
   return 'ERR: No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:    // 6
   return 'ERR: Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:    // 7
   return 'ERR: Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:    // 8
   return 'ERR: File upload stopped by extension';
Posted in Uncategorized | Tagged , , | Comments Off on PHP Easy file uploading vs. ASP file uploading

PHP Variable Variables — what?

This is something that ASP does not have. — Variable Variables.

It takes the content of a variable and use it as variable names.

$a = ‘foo’;
$$a = ‘bar’;

the above statement is equivalent to:

$foo = ‘bar’;

Two consecutive $ signs ($$a = ‘bar’) tells PHP to take the value of the variable (in our example, $a which contains ‘foo’) and use that as the variable name, then assign ‘bar’ to that variable.

Why would anyone need to do that? I don’t know. What would be a good real-world example use for this feature? Neat feature, just not sure how useful this would be.

Posted in Uncategorized | Tagged , | Comments Off on PHP Variable Variables — what?

PHP Built-In Variables – PHP_SELF

The book I’m using to learn PHP is old… © 2001. It’s using commands from PHP 4.0.3.

Thus, I’m finding some of the commands and examples in the book do not work, because the command format has changed or some commands are already “deprecated.”

Example: The book say $PHP_SELF is  a built-in variable but it just causes an error on my test page.

The new format is now $_SERVER[“PHP_SELF”]

Okay, thanks to Google, I now see that this variable could be dangerous if used as the action item in a form as is, or you echo it’s contents.

If a user entered in his browser http://yourdomain.com/actionform.php/%22%3E%3Cscript%3Ealert(‘hacked!’)%3C/script%3E%3Cfoo%22

Then it’s possible for the hacker to execute scripts on your webpage. NASTY.

The URL needs to be “cleaned.” One way to do this is use the PHP function htmlentities().

So our form will now be
<form name=”test” action=”<?php echo htmlentities($_SERVER[‘PHP_SELF’]); ?>” method=”post”>

I’m going to skip the book section about Built-in variables because it’s just too depracated. I need to buy a new book, or just consult PHP.NET for the correct and latest command format.

Posted in Uncategorized | Tagged , | Comments Off on PHP Built-In Variables – PHP_SELF

Learning PHP vs. ASP … First impressions

Learning PHP is very *easy* especially if you already know ASP.

ASP and PHP are not that very different from each other… (unlike .NET). You just have to wrap your head around a new way of thinking, and maybe learn a few new habits along the way.

Some examples:

In ASP, we enclose commands using the tag <%  %>.
In PHP, we use <?php    ?> instead.
If you’re lazy, you can use the equivalent <?  ?>, which also works… saves you from typing php everytime.

I don’t know what’s the “best practice” for doing this… <?php  or just <?
Anyone knows?
For now, I’m using <?php  ?> for my programs.

In ASP, you can name your variables simply like this:

 Name = "John Doe"

In PHP, you must use a $ sign in front of your variables. The above statement will be written as:

 $Name = "John Doe";

Also, a semi-colon “;” is REQUIRED at the end of every statement! Otherwise, you get runtime errors. I sometimes forget about this semi-colon until the browser reminds me about it.

Parse error: syntax error, unexpected T_ECHO, expecting ‘,’ or ‘;’ in /VirtualHosts/TestSite/hello.php on line 6

Sometimes, the error message given does not make it obvious you forgot a “;”.  The best thing to do is look at the statement above the line where the error is reported.  Chances are the previous statement did not have a “;”.

It’s always good to put comments in your code. In ASP, we just precede every comment line with a quote mark, like this:

 ' this is an ASP comment

In PHP, we use double slashes…

 // this is a PHP comment

This is another ASP habit I need to break when programming in PHP.

One nice feature of PHP that ASP does not have is multi-line comments. In ASP, if I want to disable a portion of my code, I have to precede every line with the quote (‘) mark.

' if not rs.EOF then
 '    varStoryTitle    = rs("StoryTitle")
 '    varStoryTeaser    = rs("StoryTeaser")
 ' end if

In PHP, I can comment whole sections using /*  */.

/*
 while ($row = mysql_fetch_array($result)) {
 echo "User ID: " . $row["UserID"] . "<br>";
 echo "User Name: " . $row["UserName"] . "<br>";
 echo "User Password: " . $row["UserPassword"] . "<br>";
 echo "<p>";
 }; // end while $row=$result
 */

Nice… I like that feature.

In ASP, if you want to output something to the screen, say the value of a variable, we use Response.Write statement.
Response.Write (Name)

In PHP, you can use the “echo” command.
echo $Name;

What else…. okay, Include files.  In ASP, if you want to use Include files, you write:

 <!-- #include virtual="/dbconnect.asp" -->

In PHP, you write Include files like this:

 include('dbconnect.php');

And one thing I discovered that PHP can do (that ASP can’t do) is you can have the name of your include file as a variable! So it will look something like this:

 $fname = 'dbconnect.php';
 include($fname);

I’m pretty sure I can think of a use for this PHP feature someday….

Also note this: In ASP, string variables must be enclosed in double quotes (“).
In PHP, you can use either double quotes (“) or single quote (‘).  So you can do something like this:

$variable = "some content";
$variable = 'some conent';
$variable = 'The movie is called "Lord of the Rings".'

In ASP, I have to write that last line as:

 variable = "The movie is called ""Lord of the Rings""."
Posted in Uncategorized | Tagged , , | Comments Off on Learning PHP vs. ASP … First impressions

Configuring MAMP PRO

The first thing I did after installing MAMP PRO is change the default ports of Apache and mySQL.

Apache = Port 80
MySQL = Port 3306

That way, I don’t have to type port numbers during my testing… i.e. localhost:8080
(Remember, I’m trying to make this as easy as possible.)

Running the Apache/MySQL server as user “www/mysql”. Make sure this is selected in your MAMP Pro General settings.

I also changed the MySQL Root Password to my own password.

For PHP, MAMP offers (2) versions of PHP.
5.2.13
5.3.2

I don’t know what’s the significance of this… I selected 5.3.2 since this is the latest version.

Cache is OFF, and Zend Optimizer checkbox in unchecked.  I don’t know what Zend is and how this is relevant to PHP. If someone can explain it to me briefly, without getting too much technical with me, please let me know.

Under Postfix, I entered the domain of my outgoing mail… also checked the box Smart Host and entered my Hostname, User Name, and Password.  Authentication type I have 2 choices.. Plain Text and MD5 Challenge-Response. I tried both authentication types, and both worked for sending out mail… so <shrug> I just selected Plain Text.

The next step I did is create a “host”… select the Hosts button on MAMP Pro.  I used “testsite.com” as my domain for testing.  Note: You don’t have to register this domain name at Godaddy… this is just for your internal use. You can name it anything you want. For me, I selected “testsite.com”.   Check the box called “Local name resolution”

On my Macintosh HD, I created a subdirectory on the root called “VirtualHosts”… then a subdirectory inside that called “TestSite”.

So basically, if I type “testsite.com” on my browser, it will execute files located in the directory “/VirtualHosts/TestSite”.  This subdirectory will be my playground.

On your Dreamweaver, or HTML editor program, save all your work in the TestSite subdirectory.

I have to tell you, I really like this setup.  Being able to do development on your own workstation machine instead of copying/ftping files to a server.  It just made learning PHP much more efficient and faster.

Before, the workflow was like this:

Edit file
FTP and Upload file to Apache server
Test using web browser
if error, go back and edit file.
Repeat…

Now, my workflow is like this:

Edit file on Macintosh HD
FTP and Upload file to Apache server
Test using web browser
if error, go back and edit file
Repeat…

I only removed a single step (ftping and uploading the file), but it just makes for a more faster workflow… which is conducive when you’re learning a new language and playing around with it.

Posted in mamp | Tagged , , | Comments Off on Configuring MAMP PRO

Apple Macintosh, OSX and MAMP Pro

My journey started after I discovered MAMP. http://www.mamp.info/en/index.html

MAMP stands for Mac-Apache-mySQL-PHP. It’s a “packaged program” that has everything you need to develop websites on the Apache platform, in an easy to use package. Upgrades to PHP, Apache, mySQL are easy… just install the latest MAMP package and you’re done!

I know OSX has a built-in Apache server and you can install the PHP and mySQL packages on it… but hey, coming from a Windows guy, it seems complicated. I want to start slowly at first and not get bogged down with installation problems… plus, I don’t want to screw up my OSX. After all, this is still my development machine for ASP stuff.

With MAMP, I just download the package and run the installation program and I’m DONE.  Apache, PHP and mySQL plus a host of other utilities (phpmyadmin) are installed. No fuss, no mess.

I bought the MAMP PRO package, after trying out the MAMP free version.  I think the cost is very reasonable… only $59.

Things you need:

1. A Mac computer – I have an “old” PowerPC PowerMac G5 with dual 2.5 Ghz. This was a *beast* when it first came out. Now, it’s getting old and some of the newer programs (like Adobe CS5) won’t run anymore on this thing.   But hey, it’s still very capable and I still love using it.

2. MAMP Pro – an easy to use Apache/PHP/mySQL package for use on your Mac computer. Download it, then copy to your Applications folder.

3. Editor – I’m using Dreamweaver CS3 as my editor. Works for me… though the new features in CS5 are tempting and I want to upgrade but CS5 only runs on Intel Macs!

4. Browser – I’m using Firefox with the Firebug extension. It makes developing website and debugging easy.  You can also use Safari.  And if the website you’re developing is for a client, make sure to check the website also using IE.

Posted in mamp | Tagged , , | Comments Off on Apple Macintosh, OSX and MAMP Pro

Not another tutorial site…

My aim is not to make another PHP tutorial site. I think there are plenty of sites on the Internet that do that.

Instead, I’m going to post here musings/confessions of an ASP developer as he learns PHP…. and switch to the GOOD Side (instead of remaining in the DARK Side?)

I’m going to log on this site (or blog) cool stuff I discovered, caveats, bugs, frustrations and joys of learning PHP.

If you’re an experienced PHP developer and you found this site, please feel free to leave comments (hopefully with some great tips or code example!) I’d love to hear from you.

If you’re an ASP developer, hopefully this site will make you want to learn PHP, and learn PHP faster.

Posted in Uncategorized | Tagged | Comments Off on Not another tutorial site…