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

PHP Form creation and basic validation

Saturday, January 2nd, 2010

As a developer and web designer,  the most frustrating part I have found  is when working with forms.
Long time ago (about 2 years now) I start putting togheter few PHP function trying to make my life a lot easier, but never got the time to finish it off.

Finally I have put everything on the side and got cracking on this due to a new project that involves the making a few very long forms.

The thought of writing all the html code (tables or DIVs) and validate them made me go back to this little project and decided to give it more thoughts.

This is the first release of the PHP code for this project so, if you would like to give it a bash and make use of it please do so…

A sample can be found here: SAMPLE PHP FORM

Some of the features:

  • Choice of using TABLE or DIVs for layout
  • You can create more than one form on the same page making sure the right one is validated on submission
  • Basic form validation
  • Option to make the field required or not
  • Show ERROR message  beside the required field – standard
  • Option to set the ERROR message text – set to REQUIRED in the sample form
  • Show ERROR message at the top of the form as well - optional
  • Cuts form creation time in more than half
  • Automatically sets the values of the field after posting the form
  • Option to add javascript code to the field (e.g. for use with ajax, etc)
  • and much more…

If you find any errors and anything that could help improve the functionality of this project, please leave a comment and I’ll make sure it gets done ASAP.

Monitor changes made to the .htaccess file

Thursday, March 19th, 2009

After what happened to “Grandad”  @ Head Rambles recently, got me thinking in finding a way to monitor any changes made to the .htaccess file.

Grandad’s .htaccess file, was injected with some malicious code, checking for the USER_AGENT, in turn redirecting “Googlebot, Slurp, msnbot” to another website.

This can be easily achieved as the server itself  updates the date & time of the file/s changed by adding a timestamp to it.
Keeping track is not that hard, once we have this value stored for later comparison.

The solution I came up with, is to create a directory where a new text file is created, which in turn will store the existing file timestamp.

With a bit of PHP coding, we can read the contents of the text file created and compare it with the existing timestamp of the file itself.
If the current timestamp is not equal to what we have stored, an ALERT email will be sent to the website administrator, who can verify the content of the file itself, making sure no malicious changes were made as per example given above.

The code can be downloaded from here >>

and please let me know if you encounter any problems….

Debugging Live Website

Thursday, April 3rd, 2008

Debugging a live website it’s a pain in the neck, especially if you are working on changing database queries.
You can’t “echo” the SQL query to find out how is formatted and why the result are not the right ones, but you CAN “Email” it to yourself and check it out when it arrives in your inbox.

This is exactly what the php function below will do:
( just change the myemail@server.com to your email address )

function ewd_email_sql($sSql){  $my_email = "myemail@server.com";//set your email address

  $my_subject = "SQL Query Email";//email subject

  $my_message = !empty($sSql) ? $sSql : "SQL Query was empty";

  $my_ip = ""; //enter your IP ADDRESS to make sure you only send the email when you view this page

$mime_boundary = "<<<--==+X[".md5(time())."]\r\n\r\n";// Generate a boundary string

  $headers = "From:".$my_email."\r\n".

                "To:".$my_email."\r\n".

                 "MIME-Version: 1.0\r\n" .

                 "Content-Type: text/plain;\r\n".

                 "boundary=\"".$mime_boundary."\"\r\n";

  if(!empty($my_ip) && $_SERVER['REMOTE_ADDRESS'] == $my_ip){

    mail($my_email,$my_subject,$my_message,$headers);

  }

  return;

}

//usage e.g

$sSql = "SELECT * FROM table_name WHERE something='".addslashes("something_else")."'";

  //email it

  ewd_email_sql($sSql);//call function

..............

//rest of the code below

Hope it helps…

Sitemap generator class

Thursday, February 21st, 2008

This php class will help you generate a sitemap for your website automatically.

// sitemap generator class
class Sitemap{  // constructor receives the list of URLs to include in the sitemap  

  function Sitemap($items = array()){  

    $this->_items = $items;  

  } // add a new sitemap item  

  function addItem($url, $lastmod = '', $changefreq = '', $priority = '', $additional_fields = array()){  

  $this->_items[] = array_merge(array('loc' => $url, 'lastmod' => $lastmod,'changefreq' => $changefreq,'priority' => $priority), $additional_fields);  

  }  

// get Google sitemap  

  function getGoogle(){  

    ob_start();  

    header('Content-type: text/xml');  

    echo '';  

    echo '';  

  foreach ($this->_items as $i){  

      echo '';  

  foreach ($i as $index => $_i){  

        if (!$_i) continue;  

  echo "<$index>" . $this->_escapeXML($_i) . "";  

      }  

      echo '';  

    }  

    echo '';  

    return ob_get_clean();  

  }  

// get Yahoo sitemap  

 function getYahoo(){  

 	ob_start();  

 	header('Content-type: text/plain');  

  foreach ($this->_items as $i){  

 		  echo $i['loc'] . "\n";  

 		}  

 	return ob_get_clean();  

 }  

// escape string characters for inclusion in XML structure  

 function _escapeXML($str){  

 	$translation = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);  

  foreach ($translation as $key => $value){  

  $translation[$key] = '&#' . ord($key) . ';';  

 		}  

  $translation[chr(38)] = '&';  

  return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($str, $translation));  

 }  

}

Usage:

$s = new Sitemap(); 
 $s->addItem("http://www.websiteurl.com", date("Y-m-d"), 'weekly', '1.0');  

 $s->addItem("http://www.websiteurl.com/link2", date("Y-m-d"), 'weekly', '1.0');  

 $s->addItem("http://www.websiteurl.com/link3", date("Y-m-d"), 'weekly', '1.0');

This class can create two type of sitemaps for you – XML for Google and TEXT for Yahoo

if(isset($_GET['target'])){  

  if(($target = $_GET['target']) == 'google'){  

  echo $s->getGoogle();//xml sitemap  

  }elseif($target == 'yahoo'){  

  echo $s->getYahoo();//txt sitemap  

  }  

}

This class wasn’t designed by me but by Jaimie Sirovich & Cristian Darie and the reason I put it up here is to help others that are trying to get this done without the headache of creating a new code.

URL rewrite tips and solutions

Friday, December 7th, 2007

Due to server setup and having no access to the php.ini file to change your server settings, we will resume to the .htaccess file for rewriting the URL, removing or adding the www. and removing the PHPSESSID from the URL itself to prevent duplicated content into the Search Engines, so here are few tips to get you started:

First lets create a new file and name it .htaccess (only if you don’t already have one), and ad the following lines at the very top:

Options +FollowSymlinks
RewriteEngine on
RewriteBase /

Now we are going to check the URL making sure the www. is always there otherwise we will redirect to the right format URL:

# redirect if not www
RewriteCond %{HTTP_HOST} !^(www)\.domain-name\.ie  

RewriteRule ^(.*)$ http://www.domain-name.ie/$1 [R=301,L]

Now lets redirect the index.php or .html to the main URL as this creates duplicated content as well:

#redirect index.php or htm to /
RewriteCond %{THE_REQUEST} ^GET\ .*/index\.(htm|html|php)\ HTTP  

RewriteRule ^(.*)index\.(htm|html|php)$ /$1 [R=301,L]

Depending on your server settings, sometimes the PHPSESSID get attached to the end of your URL, which will also created duplicated content, so there is a solution written in php that will check for the PHPSESSID query-string and if found, we will remove it and do a 301 Permanent Redirect to the same page but without it:

//remove session id from url  

if (!empty($_GET['PHPSESSID'])) {  

  $clean_uri = preg_replace('/?PHPSESSID=[^&]+/','',$_SERVER['REQUEST_URI']);  

  $clean_uri = preg_replace('/&PHPSESSID=[^&]+/','',$clean_uri );  

    header('HTTP/1.1 301 Moved Permanently');  

  header('Location: http://'.$_SERVER['HTTP_HOST'] . $clean_uri );  

    exit();  

}  

//

Please Note: The above solution is not part of the .htaccess file, but has to be added to a common include file available across the site.

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