eire web design home page contact eire-web design eire web design and development site map
stepping on in business
• Welcome to Eire Web Design Ireland

Archive for the ‘PHP’ Category

Sanitize input from forms or database with php

Thursday, November 1st, 2007

Very often a  website developers has to deal with user input, and if not sanitized properly could break the code or insert malicious code into your database.
By creating customised functions, a website developer’s job, could be made a lot easier and it’s very handy for doing updates to your code.

This function is something I designed, and will allow you to sanitize your input either coming from a form on your website or a database table before doing anything with it like send an email, display it on the website or do an update / insert to a db table.

//function to sanitise user input
//preventing sql errors and code breaking 

// [1] = numbers     

// [2] = small letters     

// [3] = caps letters     

// [4] = other characters that are included between the [4 ] brackets (e.g. [4.,@-_ ])     

//notice last gap for spaces     

// ' " \ / needs a \ in front like : \' and \" and \\ and \/    

function ewd_sanitize($input, $format){ 

 if($input == ""){     

  return;     

 }else{     

  //prepare characters to be kept     

  $ewd_keep = '#[^'; 

  $ewd_keep .= stristr($format,'[1]') ? '0-9' : '';//allow digits 

  $ewd_keep .= stristr($format,'[2]') ? 'a-z' : '';//allow small letters 

  $ewd_keep .= stristr($format,'[3]') ? 'A-Z' : '';//allow caps letters 

  //other     

  if(stristr($format,'[4')){ 

   $pattern = "/(\[4)(.*?)(\])/"; //match the 4th bracket and get the characters     

   preg_match($pattern, $format, $matches);     

   $ewd = $matches[2]; 

   $ewd_keep .= stristr($ewd,' ') ? ' ' : '';//allow spaces 

   $ewd_keep .= stristr($ewd,'.') ? '\.' : '';//allow dot 

   $ewd_keep .= stristr($ewd,'@') ? '@' : '';//allow @ symbol     

   $ewd_keep .= stristr($ewd,'"') ? '\"' : '';//allow " 

   $ewd_keep .= stristr($ewd,"'") ? "\'" : '';//allow ' 

   $ewd_keep .= stristr($ewd,'-') ? '\-' : '';//allow - dash 

   $ewd_keep .= stristr($ewd,'_') ? '\_' : '';//allow _ underscore 

   $ewd_keep .= stristr($ewd,'(') ? '\(' : '';//allow ( open bracket 

   $ewd_keep .= stristr($ewd,')') ? '\)' : '';//allow ) closing bracket 

   $ewd_keep .= stristr($ewd,'\\') ? '\\\\' : '';//allow \ 

   $ewd_keep .= stristr($ewd,'/') ? '\/' : '';//allow / 

  }     

  $ewd_keep .= ']#'; 

  $input = preg_replace($ewd_keep,'',$input); 

 }     

 return $input;     

}

Example how to use it in your code:

//this will allow most characteres 

echo ewd_sanitize("checking this text(123) @. O'Connel \/", "[1][2][3][4@.-()\'\\\\/ ]");
//numbers only     

echo ewd_sanitize("checking this text(123) @. O'Connel \/", "[1]"); 

//small letter only     

echo ewd_sanitize("check this Out 123","[2]"); 

//all letters and numbers     

echo ewd_sanitize("check this Out Now 123","[1][2][3]"); 

//allow an email     

echo ewd_sanitize("info@domain-name.com","[1][2][3][4@.-_]");

PHP create form fields

Friday, October 19th, 2007

The other day I was looking for a solution to help me create a form without the hassle to check it again and again for missing arguments or miss-typing.
Because i couldn’t find any ready made solutions I created this little function that made my life less miserable.

I hope it could be useful to you too.

/*
$ewd_type - could be text, password, submit, hidden, textarea or select
$ewd_name - the name and id of the input filed
$ewd_value - input value default or returned by post
$ewd_size - the size of the input type text
$ewd_cols - number of colums for the textarea type field - default = 30
$ewd_rows -  number of rows for the textarea type field - default = 6
*/    

function ewd_make_form_field($ewd_type,$ewd_name,$ewd_value='',$ewd_size='',$ewd_cols='',$ewd_rows=''){    

 global $_POST;
 $ewd_size = $ewd_size != "" ? $ewd_size : 30;
 $ewd_cols = $ewd_cols != "" ? $ewd_cols : 30;
 $ewd_rows = $ewd_rows != "" ? $ewd_rows : 6;
     

 switch ($ewd_type) {
  case "text":
   echo "<input type='$ewd_type' name='$ewd_name' id='$ewd_name' size='$ewd_size' value='$ewd_value' onfocus='this.style.borderColor=\"#0072BC\";' onblur='this.style.borderColor=\"silver\";' />";
   break;
  case "password":
   echo "<input type='$ewd_type' name='$ewd_name' id='$ewd_name' size='$ewd_size' value='$ewd_value' />";
   break;
  case "textarea":
   echo "<textarea name='$ewd_name' id='$ewd_name' cols='$ewd_cols' rows='ewd_rows'>$ewd_value</textarea>";
   break;
  case "submit":
   echo "<input type='$ewd_type' name='$ewd_name' id='$ewd_name' value='$ewd_value' />";
   break;
  case "hidden":
   echo "<input type='$ewd_type' name='$ewd_name' id='$ewd_name' value='$ewd_value' />";
   break;
  case "select":
   echo "<select name='$ewd_name' id='$ewd_name'> 
     <option value=''>Please Select</option>";
     $ewd_y_value = explode(" ",$ewd_value);
     foreach ($ewd_y_value as $ewd_word) {
     echo "<option value='$ewd_word'";
      if($ewd_word == trim($_POST[$ewd_name])){
       echo " selected='selected'";
      }
     echo ">".$ewd_word."</option>";
     }    

   echo "</select>";
   break;
  default:
   echo "<input type='text' name='$ewd_name' id='$ewd_name' size='$ewd_size' value='$ewd_value' />";
 }
}

Method for using the above function:

<form method="post" action="<?php $_SERVER['REQUEST_URI'];?>" name="x_form" id="x_form">
 <table summary="some form">
  <tr>
   <td colspan="2" style="background-color:#f5f5f5; padding:3px;">
    <b>About yourself</b>
   </td>
  </tr>
  <tr>
   <td>Name:</td>
   <td><?php ewd_make_form_field('text','name',isset($_POST['name']) ? $_POST['name'] : '');?></td>
  </tr>
  <tr>
   <td>Surname:</td>
   <td><?php ewd_make_form_field('text','surname',isset($_POST['surname']) ? $_POST['surname'] : '');?></td>
  </tr>
  <tr>
   <td>Email:</td>
   <td><?php ewd_make_form_field('text','email',isset($_POST['email']) ? $_POST['email'] : '');?></td>
  </tr>
  <tr>
   <td>Phone:</td>
   <td><?php ewd_make_form_field('text','phone',isset($_POST['phone']) ? $_POST['phone'] : '');?></td>
  </tr>
  <tr>
   <td>Type of Sale:</td>
   <td><?php ewd_make_form_field('select','sale_type','Private Garage Both');?></td>
  </tr>
  <tr>
   <td valign="top">Extra details:</td>
   <td><?php ewd_make_form_field('textarea','additional',isset($_POST['additional']) ? $_POST['additional'] : '');?>(eg. Engine cc: 1.1 to 1.4)</td>
  </tr>
  <tr>
   <td colspan="2" align="center">
    <?php ewd_make_form_field('submit','submit','Send');?>
    <?php ewd_make_form_field('hidden','country','Ireland');?>
   </td>   
  </tr>
</table>
</form>

PHP Image Uploading-Resizing

Thursday, October 18th, 2007

The other day I was on the look out for a solution to speed up the process of uploading images on the server.
We had the code in place already, and everything was running smooth (resizing, thumbnail creation), but there was just one problem when the user will upload something over 1024 x 800.
It was taking too long and the user will either get a server error, or just run out of patients, cancelling the upload or just close the browser.

Dealing with users that have no knowledge of adjusting the digital camera to take o lower quality / size picture, or just they don’t want to or…, made me think.
I needed a solution that will not break apart in the middle of doing its job, will be fast and doesn’t require too much of my time.
So looking at what I have.
  1. 1 x products table
  2. 1 x product images table, related to the products table by product id
  3. 1 x folder that stores the images

So the solution I came up with was:
  1. Duplicate product images table and add an extra field (status, 1=done, 0 = to be processed)
  2. Create a new folder to store the temporary images
  3. When the user uploads an image, we store the details into the duplicated table, and upload the image into the temporary folder without doing any work on them.
  4. Create a new page that will look into the duplicated table, gets all the records where the status=0, then using while… statement, the following work was carried out:
    a. get the record details, store them into variables
    b. get the image path, check to see if the image exist in the temp folder
    c. check the size of the current image (we need to resize it to 800px, then again create thumbnail of 100px and ad small_ to the image name)
    d. save the images into the right folder this time
    e. add the record into the product images table 
    f. delete the original image from the temporary folder, we don’t need it anymore
    g. update the old record into the database as 1=done 
    h. send email of how many images has been processed.

Now everything looked good. Run few tests and it was all OK.

The problem:
  1. the page had to be called manually, by clicking on a link or typing the URL into the address bar in IE or FF
  2. call the page using an include statement into the home page (not really a solution)

The solution:
  1. I was so tired, just didn’t came to me at all, so i dropped everything and went to get myself a strong cup of coffee, when I clicked – CRON JOB
so by setting up a cron job to run every 5min. the job becomes automated.
I get an email if anything has been processed so I could if I want to, check it out. If no images are processed, no email arrives so I don’t give myself too much work, deleting emails – what’s the point of doing all that work for? 

Hope this helps others as much as it helped me.

PHP Friendly SQL Error message

Thursday, October 18th, 2007

No matter how much you try there will always be the day when you make a mistake in your sql accessing the database.
Sometimes queries are based on some sort of session which, if it times-out the next query to the database will show an error instead of getting the result expected. Sometimes the query comes from an old page in the Search Engines, the possibilities are unlimited.
Showing a Sql error to the visitor, could mean a lost customer, giving out too much details that are not meant to be seen, etc…

The biggest problem is “How do you know you have made a mistake?

The solution is to send yourself an email when that happens and instead of the error message displayed on the page, you can write a nice message to the visitor that he will accept quicker then “The page can not be displayed“. 
Not many visitors knows how to go back to your Home Page if there are no links that will redirect them there.

There is a simple example bellow that will do just that.

function ewd_db_connect($HOST,$USER,$PASS,$DB) {
 $conn = @mysql_connect($HOST, $USER, $PASS) or die(ewd_error($sSql="No Connection to the database"));
 @mysql_select_db($DB) or die(ewd_error($sSql="No Connection to the database"));
 return $conn;
}  

function ewd_db_close($conn){
 mysql_close($conn);
}
function ewd_query($strsql,$conn) {
 $rs = mysql_query($strsql,$conn);
return $rs;
}
function ewd_num_rows($rs) {
 return @mysql_num_rows($rs);
}
function ewd_fetch_array($rs) {
 return mysql_fetch_array($rs);
} function ewd_free_result($rs) {
 @mysql_free_result($rs);
}
function ewd_data_seek($rs,$cnt) {
 @mysql_data_seek($rs, $cnt);
}     

#this is where the fun begins
#if we get a sql error, will show a friendly message then email the error to the webmaster or yourself 

function ewd_error($sSql) {
 echo "We have encounter a problem accessing the database. An email has been send to the Administrator.\n
 We hope to bring the website back on line very soon.\n
 To go back to the home page Click Here (link to your home page)";
 #send email
 $to = "your_email_address";
 $subject = "Error on Website name";
 $headers = "Content-type: text/plain\r\n";
 $body = "Connection Error:". mysql_error();
 $body.="\n\n\nSql Error: ".$sSql;
 $body.="\n\n\nPage: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
 $body.="\n\n\nReferer".$_SERVER['HTTP_REFERER']."\n\nIP Address: " .$_SERVER['REMOTE_ADDR'];
 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
   ini_set("SMTP","localhost");
   ini_set("smtp_port","25");
 }
  #send email
  mail($to, $subject, $body, $headers);
}
//define your connection settings 

define("HOST", "localhost"); //domain
define("USER", "user_name"); //user name
define("PASS", "password"); //password
define("DB", "database_name"); //database name  

// Open connection to the database
$conn = ewd_db_connect(HOST, USER, PASS,DB);

Example how to use it:


$sSql= " Select , Update, Insert statement here ";
$rs = ewd_query($sSql,$conn) or die(ewd_error($sSql)); //this is where the magic happens
if (ewd_num_rows($rs) > 0){
  while($row = ewd_fetch_array($rs)){//do the loop
    //...display data
    //....................................................................................
    //....................................................................................
  } //end while
} //end if
ewd_free_result($rs); // free rs
ewd_db_close($conn);//close connection
Links...

Chicklets...
  • http://www.eire-webdesign.ie/blog/feed/
    http://www.eire-webdesign.ie/blog/feed/
    Google Reader or Homepage
    Add to My Yahoo!
    Subscribe with Bloglines
    Subscribe in NewsGator Online
    add to msn
    Add to My AOL
    Add to Technorati Favorites!
    pageflakes
    windows live