PHP function to create SEO friendly URL, Unix friendly file names

 

This is a useful function for creating SEO friendly URL's.  It's also handy for creating Unix friendly file names.  

It simply removes anything that isn't a number or a letter and replaces it with a hypen (or any other character you pass... such as an underscore.) 

function seome($str, $char = '-')
{
  // convert non-alphanumeric to dashes
  $str = preg_replace("([^A-Za-z0-9])", $char, $str);

  // replace 2 or more dashes with single dashes
  $str = preg_replace("/(-){2,}/m", $char, $str);

  // remove any trailing or leading dashes
  $str = trim($str, $char);

  return $str;
}

November 6, 2011 at 04:47:44 PM / 1 comments / Code, General Web Programming, PHP

prevent browser caching with PHP

 

<?php

function bustcache()
{
  if(headers_sent())
  {
    trigger_error('Already sent HTTP headers, not busting the cache', E_NOTICE);
  }
  else
  {
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
  }
}

?> 

The above is a very simple function for preventing a browser from caching content.  This isn't recommended on static sites, but is exceptionally helpful when building dynamic applications. Simply call this function before any output.

October 21, 2011 at 03:48:06 AM / 1 comments / Code, General Web Programming, PHP

ways to make your website easier to maintain using php

 

This is nowhere near an all inclusive list of things you can do to make your life easier when having to maintain a website.  These are just a few tips and tricks worth knowing.

1) Never use absolute paths.  Use relative paths instead.

For example, this is a no-no:

include('/home/user/public_html/some/file');

Instead, try this:

include($_SERVER['DOCUMENT_ROOT'] . '/some/file');

Or even this:

include('../../some/file');

Then if (when!) you migrate to a new server, and your base web dir changes, you won't have to update your file paths throughout your code.

2) Use a config file.

Don't hard code your email address throughout your site.  define() it in a config file that you include() everywhere.  Same goes for mysql credentials, or any other text which may need to change at some point.  Putting everything in an external config makes a migration much easier.

Example:

define('EMAIL','my@email.com');
define('DB_USER','mydbusername');
define('DB_PASS','mydbpassword'); 

Or, use global variables:

$GLOBALS['EMAIL'] = 'my@email.com';
$GLOBALS['DB_USER'] = 'mydbusername';
$GLOBALS['DB_PASS'] = 'mydbpassword'; 

3) Place re-used web page code into external files. include() them.

Got a navigation menu that appears on every page?  Place it into a file (e.g. navigation.php) and include() it on every page.

Google Analytics?  Same deal--- include() it.

Doing so makes site maintenance MUCH easier.


October 10, 2011 at 08:22:47 AM / 1 comments / General Web Programming, Perl, PHP

How To: Generate a random pause delay in your PHP script

 

If you have a script that requires a random pause delay --- for example, perhaps a web scraper --- here's a super simple way to do it.

usleep(rand(1000,3000));

The rand() function is being fed two numbers; the lowest number to generate, and the highest.

The usleep() function causes a script to pause for a specified number of microseconds.

So the code above is saying "randomly sleep between 1000-3000 microseconds", which means 1-3 actual seconds.

Simple, and effective!

October 6, 2011 at 02:02:59 AM / 1 comments / General Web Programming, PHP

How To: Generate a random number in Javascript

 

This is one I forget all the time, so I figure I may as well document it here.

var randomnumber=Math.floor(Math.random()*1001)

"1001" means any number between 0 and 1000 will be generated. So for instance, change it to 101 if you want to use 0-100 as a range. And so forth.

October 6, 2011 at 01:59:11 AM / 1 comments / General Web Programming, Javascript

handy .htaccess trick - restrict by IP address

 

AuthName "whatever"
AuthType Basic
<Limit GET POST>
order deny,allow
deny from all
allow from [whatever ip address]
</Limit>

January 26, 2010 at 08:25:50 AM / 1 comments / General Web Programming, Web Application Security

SQL injection by example

 

I decided to look around the Internet for some example code to jump start a project I was working on. I found the following PHP code.  Seeing sample code like this makes me not only cringe, but makes me want to reach out and slap the developer that wrote it.

if(isset($_POST[queryString]))
{
  $queryString = $_POST[queryString];
  if(strlen($queryString) >0)
  {
    $query = "SELECT blog_tags FROM blog_entry WHERE blog_tags LIKE $queryString% LIMIT 10";
    $result = mysql_query($query) or die("There is an error in database please contact support");
    while($row = mysql_fetch_array($result))
    {
      echo $row[blog_tags];
    }
  }
}

This code would allow any attacker to inject SQL code into the query string, thus allowing them to run commands in your MySQL database.  They can do so simply by sending POST data like:

' OR 1; SELECT * FROM mysql.User

Scary, eh?  Using this code I can easily view all users in your MySQL database.

#1 Rule of Web Application Programming:  NEVER trust user input.

This includes POST data, GET data, COOKIES, etc --- basically anything that your script is reading from the client side.

SQL injection is simple to protect against.  PHP has built in functions to do so (addslashes(), mysql_real_escape_string(), etc.)  PHP also has the ability to use prepared statements, which automatically escape/filter any user input.

Simply put, if you take on the mindset that any one sending any sort of data to your program is a potential hacker, you will write more secure code.

More information on SQL injections can be found at OWASP's website
 

 

October 20, 2009 at 08:11:24 AM / 0 comments / General Web Programming, PHP, Web Application Security