Learn PHP Now
Your Complete Source For All Things PHP
 

Securing Passwords With PHP

Any website that stores users login information has to store their passwords. One thing that provides an extra layer of security for your users information is to do one way encryption on their passwords. You could in theory store their passwords as plain text, but if someone were able to get in to your database, they would have instant access to every users account.

One way encryption allows the password to be store in a secure manner. In fact it is so secure that you cannot decrypt it to recover the encrypted data. In order to authenticate the user you actually have to encrypt submitted data and compare the results that way.

One of the most widely used ways to accomplish one way encryption is to create an MD5 hash of the password. Lucky for us, it is so incredibly easy to create an MD5 hash of a string. You simply use the function md5(). See the example below:

<?

$encrypted_password = md5("secret");

?>

The value of $encrypted_password is the secured password.

PHP Function – str_replace

The str_replace function is used to replace part of a string with another string. The syntax of this PHP function is detailed below:

<?
mixed str_replace( $search, $replace, $subject, $count );
?>

$search – This can either be a string value or an array of strings. This will be the string or strings you want to be replaced.

$replace – This can either be a string or an array of strings. These will be the value that is replaced when one of the $search items are found.

$subject – The string that will be searched and have replacements placed inside of it.

$count (optional) – The maximum number of times a replace should occur.

There are a number of reasons why you would want to use this function. One of the ways that I use str_replace is when I need to remove line breaks from the a large string that you are working with. You would do that by doing the following:

<?
$input = str_replace( "\n", '', $input );
?>

You may have noticed that I used $input as the return variable and the string that is having the replace performed on it. This is a quirk that I use in order to not have to create extra variables and you cannot pass the $input to the function as reference.

PHP Boolean Type

The boolean data type in PHP is very easy to use (and why should it be difficult, it is either True or it is False).

The basic way to set a boolean value is to use the true and false keyword. Unlike other programming languages, true and false are case insensitive so you can either use true, True, TrUe, or any other variation to get the same effect.

For example:

<?
$yes = true;
$yes2 = True;

$no = false;
$no2 = False;
?>

These are all valid ways to set a variable to true or false.

PHP has some interesing ways of determining if a variable is true or false. Since PHP is a dynamically typed language, nearly any type can be evaulated as true or false. The way you can keep this straight in your head is if the variable’s value is at its default state, it will likely be evaulated as false.

To be more official, here is how PHP evaulates true or false from various values:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string “0″
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Text taken from PHP manual at: http://www.php.net/manual/en/language.types.boolean.php

Ternary Operator – Your Best Friend

If you have never used the Ternary Operator, or ? operator, your life is about to change. The ternary operator is used as a shorthand for if .. else structures that can really clean up your code. Some may want to classify this under a intermediate or advanced skill, but it is so useful that I think it should be included with the most basic tutorials.

Take this for example:

<?
if( $use_live_server ) {
     $url = "http://www.thelivesite.com"
} else {
     $url = "http://www.thedevsite.com";
}
?>

This block of code sets which URL we want to connect to based on if a variable called $use_live_server. While the block of code is perfectly valid, there is a much better way to do the exact same thing in a single line of code.

<?
$url = $use_live_server ? "http://www.thelivesite.com" : "http://www.thedevsite.com";
?>

That one line of code does the exact same thing and once you understand how this works. Here is how the ternary operator works:

<?
$variable = $expression_to_evaulate ? true : false
?>

You do not necessarily have to have a variable that is true or false. You can do any expression you need to.

dBug. Awesome PHP Debugger

I just ran into this awesome PHP class called dBug. It works like print_r, but does so much more. You can expand and collapse anything in the structure you use it with. You know no idea how nice this will be to parse large data structures with. So nice. Check it out at: http://dbug.ospinto.com/

The Ultimate PHP CSV Parser

Lately I have been trying to find cool PHP utilities that I can use to handle my day to day tasks. Lately parsing CSV files in PHP has been something I have had to do over and over again. Such a basic task can be such a pain considering all of the different formats that they can be in (mostly the quotes around some of the values). I would do find and replace on the file to remove all the extra stuff and hope that I did not corrupt the data.

There had to be a better way to do this. I did some searching and I found Ming Hong Ng’s CSV Parsing class. It worked perfectly. I have parsed a ton of CSV files with no problems at all. You can download this class from: http://minghong.blogspot.com/2006/07/csv-parser-for-php.html

It is so simple to use too! Simply create an instance and call ParseFromFile or ParseFromString. The data is stored in the data instance variable. So simple!

This is something that should be apart of any PHP programmers toolkit.

Use cURL to Connect To Another System

cURL is a very useful tool used to pragmatically connect and interact with other systems to do various tasks like download a Web Page or RSS feed. It is also used to send information to another computer and get a response. A common example of using cURL is when you are purchasing something online. When you get your shipping quote or authorizing your credit card, you are very likely using something like cURL.

<?
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec ($ch);
?>

These 5 lines of code do a lot. In line 1 you begin creating your transaction by calling curl_init() and passing the URL you want to connect to (in this case we have a variable called $url).

Lines 2-4 set different options for the transaction. The CURLOPT_HEADER option is set to zero to signify we do not want the header information in the response. CURLOPT_RETURNTRANSFER tells cURL to assign the data we receive to a variable rather than simply output it to the screen. CURLOPT_POSTFIELDS sets what data we want to send in the header of our request. This is a very important option when interacting with other systems as this is generally where you will put your XML or other header data that is required by the system you are connecting with.

Line 5 actually executes the request. It will reach out to the $url, with $fields in the POST areas of variables and putting the data we received into the variable $result. With this variable you can do whatever you need in order to make your application work.

Querying A mySQL Database Using PHP

Querying a mySQL database requires an established connection to a mySQL database.  You can read our article on connecting to a mySQL database here.

Querying the mySQL database is as simple as creating the SQL query and passing it through the mysql_query function.

<?
$sql = "SELECT * FROM products";
$results = mysql_query( $sql, $resource );
?>

With the $results variable you can use it to do a few different things. The first one we will discuss is to determine the total number of rows that was returned by the Select query. You can do that by doing the following:

<?
$num_rows = mysql_num_rows( $results );
?>

It should be noted that using mysql_num_rows is not the most efficent way to determine the number of rows being returned. If there are a lot of rows (I have seen it happen with as few as 1000 rows) that it is faster to query the database for the number of results like this:

<?
$sql = "SELECT COUNT(*) as num_rows FROM products";
$num_rows = mysql_fetch_array( mysql_query( $sql ) );
?>

This example also introduces the mysql_fetch_array function. This function is used to grab the next row of a mySQL query result. The row is returned as an array with the indexes named as the names of the columns in the database. Once there are no more results the function returns null.

The best way to iterate through a result set of a mySQL query is to use a while loop:

<?
$sql = "SELECT * FROM products";
$results = mysql_query($sql);
while( $row = mysql_fetch_array($results) ) {
    echo $row['products_id'] . ': '. $row['products_name'] . '
'; } ?>

Connecting To A mySQL Database Using PHP

Connecting to a mySQL database is a very important part of any PHP application. mySQL has become an integral part of many PHP applications since it is also free to use. Connecting to a mySQL database only requires a single function call.

<?
$resource = mysql_connect( $server, $username, $password );
?>
  • $resource – The variable that the connection will be stored and passed to the other mySQL functions that are going to be called.
  • $server – The address of the database server.  Remembering that this is relative to the server, not your end machines.  For example, if your database server is located on the same machine as your webserver, this will be “localhost”.  If it is in the same datacenter (or network) it could be an ip address like 10.xxx.xxx.xxx or 192.xxx.xxx.xxx.  Otherwise you can use an entire URL like db.mydatabaseurl.com.
  • $username – Username to use to login to the database server
  • $password – Password to use to login to the database server

PHP Variable Syntax

PHP is a dynamically typed language. What this means is that you do not have to specify the variable type. You do not even need to declare you variable before using it. All variables have a $ in front of them and cannot be more than 64 characters long. String variables require that the value be surrounded by double or single quotes. Numerical values do not need to surrounded by quotes, but they can be if you so desire. They will still be recognized as numerical (PHP is nice that way).

For example, here are some basic variable declarations:

<?
$address = "123 Somewhere"; $zip = 49123
?>
 
« Older Entries