Posts Tagged ‘PHP’

Gracefully handling errors in php using advanced techniques

Saturday, October 11th, 2008

There are a few ways in which you can handle errors in PHP. You can do the not so smart thing and just turn them off altogether using

ini_set('error_reporting',0);
//or
error_reporting(0);

However this is not a good idea, and should never happen. If you want to hide all of your errors, you can set it so that you have them hidden, but log them to a file instead

ini_set('display_errors','off');
ini_set('log_errors','on');

That will then log all of your errors to your server error log by default. If you wish to set the log to a different file you can do so by using

ini_set('error_log','/path/to/your/error.log');

and that will log all of your errors to error.log in the /path/to/your/ directory.

Another option is to use a custom function to handle all errors. This can be useful should you wish to log all of your errors to a database so that you can use queries to view errors instead. The way that we tell PHP that we want to handle the errors ourselves is to use the set_error_handler() function and pass the name of the function we want to handle the errors.

set_error_handler('custom_error_func');

Then we make a function to handle the errors. For example if you wanted to add the error to your database table it would look something like this

function custom_error_func($errno, $errmsg, $filename, $line, $context)
{
    // Create query - NOTE: This is using the mressf() function that I created available at
    // http://www.jaygilford.com/php/sprintf-and-mysql_real_escape_string-all-in-one-function/
    $query = mressf("INSERT INTO `errors` VALUES(NULL,'%s','%s','%s','%s','%s')",
                    $errno,
                    $errmsg,
                    $filename,
                    $line,
                    $context);
    //run query
    mysql_query($query);
}

If you wish to have any of the above ini_set() functionalities set permanently on your server, you may be able to if you have access to either the php.ini file or your .htaccess allows you to make php changes you can do so quite simply. For the php.ini file, simply search the file for display_errors for example and modify the value in there. If you are using .htaccess, you may be able to use the php_flag or php_value settings to modify the data. For more information on setting values this way, see here

php random string generator function

Wednesday, July 16th, 2008

Many people need a random string for things such as salts, activation keys and new passwords. Here’s a simple but versatile function to return a random string

function rand_text(   $min = 10,
                      $max = 20,
                      $randtext = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' )
{
    if($min < 1) $min=1;
    $varlen = rand($min,$max);
    $randtextlen = strlen($randtext);
    $text = '';

    for($i=0; $i < $varlen; $i++)
    {
        $text .= substr($randtext, rand(1, $randtextlen), 1);
    }
    return $text;
}

To call this function, you can simply use rand_text() which will return a random alphanumeric string between 10 and 20 characters long. You can also specify a min and max length, and can also specify the string of characters that can be used in the random string. For example

echo rand_text(5,8,'abcdef0123456789');

will output a random hex value between 5 and 8 characters in length such as 2fe4e1

how to process a form with php using one page

Tuesday, June 24th, 2008

Many first time coders in PHP tend to use a form on one page, and a PHP script on a completely different page in order to process it. This is highly irritating since you need to make two pages instead of one, and also, if there is an error you have to redirect back to the original page whilst jumping through hoops to send the data back to the original page.

There is however a rather simple way to do this. First you need to create your (X)HTML document. Below, I’ve created a simple example form using XHTML 1.1


As you can see, it has a single text box and a submit button, with ID’s Name and Submit respectively. Also note the action="". This will automatically make your page post the data to the same page. Many people include the

which is discouraged, since it can lead to XSS Attacks, and since it is not required, it’s just asking for trouble.

OK, onto the PHP code. Here’s some simple PHP, which will check if the form has been posted, by checking if the $_POST['Submit'] is set

  0)
{
	$_POST['Name'] = strip_tags($_POST['Name']);
	$contentdiv = '
Your name is '.$_POST['Name'].'
'; }else{ $contentdiv = '
Please enter your name below
'; } ?>

As you can see, I’ve added the content output I wish to be displayed into a simple <div>. All that is left now is to add some PHP code to the XHTML code to echo out the $content, and save as a .php file and it will all be finished

The PHP code is simply <?php echo $contentdiv; ?> and is added between the <body> and the <form> tags.

You can try out this code by clicking here, or download the script using the button below

Form processor download

Headers already sent error php solution

Sunday, June 22nd, 2008

Many people seem to get a problem with the common error message of

Warning: Cannot modify header information - headers already sent by (output started at C:\file.php:1) in C:\file.php on line 4)

There are a number of possible reasons for why this might happen

Output before the <?php tag

There are so many occasions where people report that they have no output, only to find that they have a single space or a new line before their opening <?php tag. Examples

 

appears to be fine to the untrained eye, but upon further inspection we notice that their is a slight gap (one space) before the <?php tag.


also looks fine, however a single carriage return still gets output to the browser, so it's still going to cause the same problem

Output inside your script via functions

php has a number of functions that display code, such as echo(), var_dump() and print_r(). Some people also believe that (X)HTML code does not qualify as content for some reason, and leave it there. This is STILL output, and will still bring up the error. Another instance where people get confused is where there is more than one error on the page. For instance if a Notice: error message comes up before the headers are sent, this will also be classed as an output, therefore turn off notice messages (This should be the case anyway for production servers)

The error is caused by a different file

Warning: Cannot modify header information - headers already sent by (output started at /home/username/www/includedfile.php:1) in /home/username/www/file.php on line 4)
Above shows the location of the file where the output was started at, and also, the line on which it started. Simply go to that line with your editor in that file, and work out what is causing the output. This type of error is common when using include/include_once or require/require_once

When including php from other files, it is a good idea to not have the closing ?> tag. This will NOT affect your script in any way, as PHP is quite happy with no tag. It will also prevent output being left after the tag such as the single space/new line as mentioned above. This is good practice and I recommend doing this with any included files with php, since you should not mix both (X)HTML and PHP in includes other than templates