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

Easy way to check if HTTPS / SSL is being loaded (PHP)

 

<?php 

function httpscheck($url = '')
{
  if($_SERVER['HTTPS'] != "on" || $_SERVER['HTTP_PORT'] != 443)
  {
    if(strlen($url) == 0)
    {
      $url = $_SERVER['REQUEST_URI'];
    }
    if(headers_sent())
    {
      trigger_error('SSL redirect failed as HTTP headers were previously sent to the browser', E_NOTICE);
    }
    else
    {
      die(header('Location: ' . $url));
    }
  }
}

October 21, 2011 at 03:55:25 AM / 1 comments / Code, PHP

PHP - simple cookie checking script

 

<?php

if(isset($_GET['set']) && $_GET['set'] != 'yes')
{
  // Set cookie
  setcookie('test', 'test', time() + 60);

  // Reload page
  header("Location: cookie.php?set=yes");
  exit ;
}
else
{
  // Check if cookie exists
  if(isset($_GET['set']) && ! empty($_COOKIE['test']))
  {
    echo "Cookies are enabled on your browser";
  }
  else
  {
    echo "Cookies are <b>NOT</b> enabled on your browser";
  }
}
?>

October 21, 2011 at 03:53:16 AM / 1 comments / Code, PHP

cURL error codes PHP array

 

<?php

$curl_errors = array();
$curl_errors[0] = "CURL_OK";
$curl_errors[1] = "CURL_UNSUPPORTED_PROTOCOL";
$curl_errors[2] = "CURL_FAILED_INIT";
$curl_errors[3] = "CURL_URL_MALFORMAT";
$curl_errors[4] = "CURL_URL_MALFORMAT_USER";
$curl_errors[5] = "CURL_COULDNT_RESOLVE_PROXY";
$curl_errors[6] = "CURL_COULDNT_RESOLVE_HOST";
$curl_errors[7] = "CURL_COULDNT_CONNECT";
$curl_errors[8] = "CURL_FTP_WEIRD_SERVER_REPLY";

?>

October 21, 2011 at 03:51:03 AM / 1 comments / Code, 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