Archive

Posts Tagged ‘functions’

PHP Cryptographic Functions For Passwords

March 27th, 2009 No comments

There are three available cryptographic functions in PHP, these are md5(), sha1() and crc32(). All of the functions take a string and output a value that is encrypted and can’t be reversed to the original string. In fact the only way to get the original string back is to run a brute force algorithm which tries to guess what the original string was.

To test these functions I will use the following string.

$string = 'wibble';

md5()

This function returns the hash as a 32-character hexadecimal number. The md5() function is used quite a bit and most PHP programmers will have come across it at some point.

md5($string);
//returns 50eccc6e2b0d307d5e8a40fb296f6171

The md5() and sh1() functions have a second parameter which makes the function return binary data if set to true (the default is false). This returns binary data, which can be turned back into a hexadecimal number by using the bin2hex() function.

bin2hex(md5($string, true));

This function returns the same as in the previous example.

sha1()

sha1() returns the sha1 hash as a string 40 characters long. This function is more secure than the md5() function as there is a lesser chance of guessing what the original string was.

sha1($string);
//returns 02e0182ae38f90d11be647e337665e67f9243817

The sha1() function can also be made to return binary data if the second optional parameter is set to true.

crc32()

This isn’t really a cryptographic function, but it can be used in a similar way as a string will always come out with the same result. This function returns the crc32 polynomial of a string as an integer.

crc32($string);
//returns 489363548

Because of the way that PHP stores integers (as signed), quite a few of the results of this function will be negative. For example, the string "wibble" will return a positive integer, but the string "wobble" will return a negative number, which must be compensated for. This can be fixed by using the "%u" formatter of the sprintf() function, which will return a string containing the correct integer value.

This hashing function is intended to be used as part of a hash table and not as a mechanism of security. This is because it is very easy to generate a "hash collision" where two separate strings have the same hash value. I include this here to give you that warning.

sprintf("%u", crc32($string));
// returns 489363548

crypt()

The crypt() function will take a string as input and produce a variety of different outputs depending on the current system and environment. The salt is the second parameter and if you don’t include this the function will generate a salt for you, which causes the outcome of the hash to be different every time. An important thing to note is that the value of the salt value effects what hashing algorithm is used. There are a set of constants that can be used if you want to detect if an encryption algorithm is available.

if ( CRYPT_STD_DES == 1 ) {
 crypt($string, 'st');
}
// returns something like "stNPuLMaoIxdU"

If you want to compare a password then you must pass the entire result of crypt() as the salt for a crypt of the password. For example, the following is incorrect.

$one = crypt('one');
$two = crypt('one');
var_dump($one == $two); // returns false

Adding a salt to the second crypt() call gives us the correct answer.

$one = crypt('one');
$two = crypt('one', $one);
var_dump($one == $two); // returns true

As with all hashing functions there is no decrypt function as this is a one way process.

hash()

The hash() function is a multi use function that takes two parameters as a default. The first is the hashing algorithm that will be used and the second is the string to be hashed. To encode the string using the whirlpool algorithm use the following code.

hash("whirlpool&quotl, $string);
// returns 91cefc6cc8eecf3a0ef18889bc3b06e7217ce7d41e1d0d5e37709415c3a98e450c53e62ae57680a011a08ef65429e6ba76701c703fcfc4c63938a4aa61737c38

To find out what hashing algorithms your system supports you can use the hash_algos() function. This returns an array of the available algorithms.

print_r(hash_algos());

If you have haval256,5 available in this list then I suggest you use it as it produces the safest hash value. More information about the hash functions can be found in the hash section of the PHP documentation.

Breaking The Code

It isn’t possible to break a md5 of sha1 encoded string, but this can only be done by trying to guess the original value. The site md5.rednoize.com/ can break a string that you enter, but only because it contains 47 million hashes and can therefore reverse engineer the value of the hash.

To stop this happening to your passwords you can use what is called a salt value. Rather than directly encode the value of the password you store the password along with a salt, which is kept secret. An attacker needs to know the value of the salt value before they can correctly guess a users password.

Connect To FTP Server Using PHP

September 11th, 2008 No comments

FTP connection functions have been built into PHP since version 4 and make transferring files through FTP very easy.

The main function involved is called ftp_connect() which takes a FTP host as a parameter and attempts to connect to it. The port and a timeout limit can also be added to the function if needed.

Once a connection has been made then the ftp_login() function is used to attempt a login. This function returns true on success and false if it fails. The following snippet of code will attempt to connect and login to an FTP server, if any step fails then the code will print out a message saying so.

$host= 'ftp.example.com';
$user = 'notarealusername';
$password = 'notarealpassword';
$ftpConn = ftp_connect($host);
$login = ftp_login($ftpConn,$user,$password);
// check connection
if ((!$ftpConn) || (!$login)) {
 echo 'FTP connection has failed! Attempted to connect to '. $host. ' for user '.$user.'.';
}else{
 echo 'FTP connection was a success.';
 $directory = ftp_nlist($ftpConn,'');
 echo '<pre>'.print_r($directory,true).'</pre>';
}
ftp_close($ftpConn);

The ftp_close() function takes the resource identifier and a closes it. Here is what is printed out if the code fails.

FTP connection has failed! Attempted to connect to ftp.example.com for user notarealusername.

If the connection is a success then the script attempts to retrieve the contents of the root directory, this is done using the ftp_nlist() function. Here is a typical example of what might be found if the code successfully connects to an FTP server.

FTP connection was a sucess.
Array
(
 [0] => cgi-bin
 [1] => logfiles
 [2] => html
)

There are a lot of different FTP functions available, covering the main things that would expect any FTP program to do. The main ones you might use are ftp_get() to download files, ftp_put() to upload files and ftp_nlist() to view the contents of a directory. There is also a function called ftp_chmod() which allows you to set the permissions of a directory on your FTP server.

Categories: PHP Tags: , , , ,

Getting Started With WordPress Templates

July 29th, 2008 No comments

If you are setting up a WordPress blog the chances are that you will be looking into modifying the default theme to be something a little more customised to your site. Theme development can be as complicated or as simple as you want, or are capable of doing.

WordPress themes are stored in the folder wp-content/themes/, each theme being stored in it’s own directory.

The basic theme must contain two basic files, the main control is done from a file called index.php and a file called styles.css, which is also needed to allow you to display the theme within the admin section of WordPress. If you don’t want to use the styles.css file then this is fine, but it should be present and contain the following lines.

/**
* Theme Name: Your theme name
* Theme URI: www.talkincode.com
* Description: A theme designed by the guys at talkincode.com
* Author: Tech
* Author URI: talkincode.com
* Version: 1.0
*  
* General comments can go in this space.
*/

This is all integrated into your WordPress administration section under themes. If you want a screenshot to appear as well as the description then create a file called screenshot.png, make it 300 pixels wide by 225 pixels high and put it in the same folder as the rest of the files.

There is also a file called functions.php in which you can define custom functions that can be used in your template. This includes, but is certainly not limited to, adding a widget definition. The functions file is loaded right at the start of the template and is looked at when viewing the administration section of your site. Any code kept in the functions.php file is called rather like a plugin and so it is possible to write plugin-like code in this file and have it act accordingly.

Other files can be included very easily.

The header file will contain the HTML at the top of the page (including styles and meta tags) and will get included via the get_header() function like this.
<?php get_header(); ?>

The footer file will contain the HTML at the bottom of the page (including copyright and site tags) and will be included via the get_footer() function like this.
<?php get_footer(); ?>

The sidebar of the site can be included using the get_sidebar() function. This can contain a widget call or
<?php get_sidebar(); ?>

If anything else is to be included from the template folder then the TEMPLATEPATH constant can be used in conjunction with a include() function call.
<?php include(TEMPLATEPATH . '/searchform.php'); ?>

WordPress will automatically recognise certain files depending on what action is being taken. For example, when looking at a single post or page the single.php file is used instead of the index.php file to load the template. If this file doesn’t exist then it uses the standard index.php file.

Also, if the user clicks on a link for a category, WordPress will load the category.php file. If this is not present then WordPress tries to load a file called archive.php. If both of these files are not present then WordPress load the main index.php file instead.

A files called 404.php is also used when a 404 response is needed. This file is called automatically during a 404 response and does not require any .htaccess modifications.

A lot of default tags are available for you to use if you don’t want to hard code things into your template. For example, to include the name of your blog in your template you can use the following code.

<?php bloginfo('name'); ?>

In addition to the name tag the tags description, url, admin_email and version are also available.

The Loop is used by WordPress to display each post in turn. The loop takes the following format.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
// the contents of the post can be displayed here
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>

There are a number of different tags that can be placed within the loop to print out different information. For example, to print out the content you just need to call the the_content() function.

<?php the_content(); ?>

The best way to get acquainted with WordPress templates is to simply make a copy of the default template that comes with WordPress and edit it to suit your needs. In this way you can figure out how things work, why the template is set up as it is and what files do what.

The following links go to specific pages within the WordPress documentation and should also help out.

codex.wordpress.org/Stepping_Into_Templates: The WordPress documentation on getting started on templates.

codex.wordpress.org/Stepping_Into_Template_Tags: A list of the different tags available for both the bloginfo() function and within the loop.

codex.wordpress.org/Template_Hierarchy: This page looks at the files available for a theme and when they are called.

codex.wordpress.org/Theme_Development: The WordPress documentation on developing themes.

codex.wordpress.org/Site_Architecture_1.5: The different files available for templating. Although this document was written with version 1.5 the content seems valid.

codex.wordpress.org/Function_Reference: A reference document for all of the functions available in WordPress. Although some don’t matter for template development this is still a good resource for template functions.

codex.wordpress.org/The_Loop: Help on The Loop.

codex.wordpress.org/Using_Themes: Help on using themes.

Fixing WordPress Scheduled Posts

May 7th, 2008 No comments

WordPress has a neat little feature that allows you to write a post and then schedule it to display at some point in the future. This seems good, but it invariably doesn’t work on some server platforms and rather than publishing a post WordPress just counts the amount of time passed since it was supposed to go live. The basic solution to this is to go into the post and click on publish, which can be a pain if you are taking a couple of days off from blogging and want to leave it running.

The problem lies with the functions that convert a scheduled post into a live post which are kept in the file wp-cron.php in the root WordPress directory. For some reason the WordPress developers decided to call the scheduling functions using the fsockopen() function available in PHP. This essentially opens a browser session to the wp-cron.php file, just as you would if you browsed to the location using your web browser.

What seems to be happening is that the browser request is getting blocked due to a permissions problem, which leads to WordPress simply not running the cron functions. However, even when the wp-cron.php file is loaded manually using your web browser there are two if statements at the top of the file that tend to stop things from working.

After much tinkering and research I have found the following solution.

Open the file wp-cron.php (situated in the main WordPress folder) and comment out lines 6 to 10.

Change this:

<?php
ignore_user_abort(true);
define('DOING_CRON', TRUE);
require_once('./wp-config.php');
 
if ( $_GET['check'] != wp_hash('187425') )
  exit;
 
if ( get_option('doing_cron') > time() )
  exit;
 
update_option('doing_cron', time() + 30);

To this:

<?php
ignore_user_abort(true);
define('DOING_CRON', TRUE);
require_once('./wp-config.php');
 
/*if ( $_GET['check'] != wp_hash('187425') )
  exit;
 
if ( get_option('doing_cron') > time() )
  exit;*/
 
update_option('doing_cron', time() + 30);

Next, open the index.php file in your WordPress folder and change it from this:

<?php
/* Short and sweet */
define('WP_USE_THEMES', true);
require('./wp-blog-header.php');
?>

To this:

<?php
/* Short and sweet */
define('WP_USE_THEMES', true);
require('./wp-cron.php');
require('./wp-blog-header.php');
?>

This adds a the wp-cron.php file every time the blog is looked at and because we have removed the if statements at the top of the file the cron functions are always run.

This might cause a small issue on very busy blogs as it can make your pages load slightly slower than normal. So if you have a lot of traffic you might want to just save your posts in draft form and publish them manually each morning.

Of course to run the cron functions on WordPress (modified or not) you need to actually look at the front page of the blog. If you are refreshing the administration section then nothing will happen.

Categories: Wordpress Tags: , , , ,

www.php.net

March 17th, 2008 No comments

By far the best resource for finding information about PHP and all of the functions available is from the PHP website. Not only can you view the PHP documentation, but you can also download PHP and many of the extensions like the Smarty template system.

Each PHP function and section has its own page with lots of detailed information about usage and instillation, which can be found quite easily on the site by entering the domain name followed by the function name you want to look up. If the function isn’t found that the site points you towards a search results page.

www.php.net

One of the better aspects of the site is the user submitted code snippets that can be found on many of the pages. Take the substr() function as an example. There are many pages of user submitted functions, hints, tips, error trapping and other code snippets which can usually solve most of the problems that you are stuck on.

Although the instillation section is completely brilliant, the site probably isn’t the best site in the world if you are starting out to learn PHP, there is a getting started section, but this wont get you past a certain level.

Categories: PHP Websites Tags: , ,