PHP Ordinal Numbers. 3rd, 4th, 1st, etc.

Here is a little function you can use to get the proper ordinal. Works for negative numbers too:

     function ordinal($number) {

    // when fed a number, adds the English ordinal suffix. Works for any
    // number, even negatives

    if ($number % 100 > 10 && $number %100 < 14):
        $suffix = "th";
    else:
        switch($number % 10) {

            case 0:
                $suffix = "th";
                break;

            case 1:
                $suffix = "st";
                break;

            case 2:
                $suffix = "nd";
                break;

            case 3:
                $suffix = "rd";
                break;

            default:
                $suffix = "th";
                break;
        }

    endif;

    return "${number}$suffix";

}

Usage:
Just call it with ordinal(179) and you will get back, 179th
Cool eh?

No Comments

Dreamweaver GetSQLValueString function enhancements

I’ve been using Dreamweaver’s GetSQLValueString function as part of my code for a long time. Over the last few projects, I’ve made some enhancements that you may find useful. It formats phones, SSN, does datetime (instead of just date) and of course you can add your own. Here it is, I hope you enjoy it.

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")	{
if (PHP_VERSION &lt; 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
 case "text":
   $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
   break;
 case "long":
 case "int":
   $theValue = ($theValue != "") ? intval($theValue) : "NULL";
   break;
 case "double":
   $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
   break;
 case "date":
   $theValue = ($theValue != "") ? "'" . date("Y-m-d",strtotime($theValue)) . "'" : "NULL";
  break;
 case "datetime":
   $theValue = ($theValue != "") ? "'" . date("Y-m-d H:i:s",strtotime($theValue)) . "'" : "NULL";
   break;
 case "displaydate":
   $theValue = ($theValue != "") ?  date("m/d/Y h:i:s A",strtotime($theValue)) : "NULL";
   break;
 case "ssn":
   $theValue = ($theValue != "") ? "'" . substr($theValue,0,3)."-".substr($theValue,4,2)."-".substr($theValue,6,9) . "'" : "NULL";
   break;
 case "unssn":
   $arrfind = array(" ","-","/","\");
   $arrrepl = array("","","","");
   $theValue = ($theValue != "") ? "'" . str_replace($arrfind,$arrrepl,$theValue) . "'" : "NULL";
   break;
 case "phone":
   $phone = preg_replace("/[^0-9]/", "", $theValue);
    if(strlen($phone) == 7)
     return "'".preg_replace("/([0-9]{3})([0-9]{4})/", "$1-$2", $phone)."'";
   elseif(strlen($phone) == 10)
     return "'".preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "($1) $2-$3", $phone)."'";
   else
     return "'".$phone."'";
   break;
 case "null":
   $theValue = "NULL";
   break;
 case "defined":
   $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
   break;
}
 return $theValue;
}

Here is how you use it: Want a cleaned up phone number? Call it with this:
GetSQLValueString($yourval,"phone")
Need a good null?
GetSQLValueString("NULL","null")
How about a datetime?
GetSQLValueString($mydateval,"datetime")
You get it now, go on with your bad self.

, ,

No Comments

Select a menu

This post is specifically to answer a twitter question:

PHP was more designed to control your HTML rather than the other way around. What you are trying to do could be handled with Javascript, but PHP is a better solution. See if this makes a little more sense…
<?php if ($_SERVER['PHP_SELF'] == "bluepage.php") {
               include('bluemenu.php');
         }
          if ( $_SERVER['PHP_SELF'] == "redpage.php") {
               include('redmenu.php');
         }
?>

But the better way is to use the “switch” like this:
<?php
          $page = $_SERVER['PHP_SELF'];
               switch ( $page ){
                      case "bluepage.php":
                           include ('bluemenu.php');
                      break;
                     case "redpage.php":
                            include ('redmenu.php');
                      break;
                      default: //will execute if we didnt match any above
                        include ('standardmenu.php');
                      break;
                 }
?>

I hope that helps some

,

No Comments

To Twitter or Not to Twitter

Yes, Twitter. I set it up yesterday, kinda digging it. I wouldn’t have done it except Friday and Saturday I was bombed with requests to look at Twitter integration on some different projects…

And so it was.

No Comments

Wordpress SSL

In case you ever need it this how you can make wordpress (or any other site for that matter) respond to being viewed as https:

In the header include or start of page, turn on buffering:

// start output buffering for https link checking in application_bottom.php
ob_start();

In the footer include or at end of the page:

// Filter certain content for http reference on https pages
$page = ob_get_contents();
ob_end_clean();

if ($_SERVER["HTTPS"] != “on”)?echo $page:else echo; preg_replace(’/((?:<link|<script|<img|SWFobject)[^>\)]+?)http:\/\//’,'$1https://’,$page);

Not much to it but it works.

, ,

No Comments

Use php to add iptables rules to block hack attempts

Did you ever sit there, tailing your secure log and see 100 attempts a minute trying to SSH login to your box? Yes, it is a brute-force attack, they are trying to figure out your password! These automated programs are easy to spot because your server will log each attempt and until they get the password, those attempts stay in your log file. Now there is a way to stop those attacks.

Create a script that opens and parses your secure log, looks for those attempts and automatically adds a rule to your IPTABLES script to block the IP’s associated with them. This script should work on Fedora and CentOS Linux variants. You could pretty easily modify it to work on just about any other Linux OS.

<?php
$badguys = array();
$recent_count = 0;
$older_count =0;
$dropped =0;
$start_time = strtotime("-1 minute");  // Change this if the cron interval is different
echo "Looking for failures since ".date("m/d/Y h:i:s",$start_time)."\n";
/* here is where we go open the log file. (/var/log/secure) in this case. Change that path if your log is located elsewhere */
exec("grep -i 'failed password for invalid user' /var/log/secure",$badguys);
echo count($badguys)." failed password records\n";
$badips =array();
foreach($badguys as $line) {
if(strtotime(substr($line,0,15))>$start_time) {
$recent_count++;
preg_match('/from ([0-9.]*)/',$line,$match);
$ip = $match[1];
//    echo "$ip\n";
     if(array_key_exists($ip,$badips)) $badips[$ip]++;
       else $badips[$ip]=1;
   }else {
     $older_count++;
   }
}
echo $recent_count." failures occured in last minute.\n";
echo $older_count." failures were prior to that.\n";
if(count($badips)>0) {
//    echo "Here are the ip's to be added to the drop list:\n";
foreach($badips as $ip=>$count) {
echo "$count failed attempts from $ip\n";
/* here, we are saying if there were more than 5 bad password attempts in one minute, then go add that ip to the currently running firewall script. Change this number if you think you yourself could possibly screwup logging in more that 5 times in a single minute. */
if($count > 5) {
exec("iptables -I INPUT -s $ip -j DROP");
/* Note that adding the rule in this way does not make the change permanent, you are not adding it to your startup script, just to the running config. If you want to permanently block those IP addresses, you will need to go to a command shell, and issue the following command:
# service iptables save
or add this command to this script at the very end:
exec("service iptables save");
without one of those commands, the IP blocking effect will be lost at reboot.  */
echo "dropping $ip\n";
$dropped++;
}
}
}
echo $dropped." ips were dropped.\n";
?>

Now, just because you have this script, doesn’t mean anything will happen, now you have to call it from some where. How do you do that? Here is an idea…

Add it to cron set to run every minute. An even better idea would be to add it to cron on a different server on a different network. Here’s how you do the basic cron entry…

From a command prompt, type:

crontab -e

This opens a vi style editor to edit the crontab file. Use your arrow keys to go to the end of the file and hit your <insert> key. (This puts you into insert mode). The following should be on one line, this site wraps it to two lines. Type:

0-59     *     *     *    *     php -f /path/to/script.php

Now, hit your <esc> key, to get out of edit mode, now type:

:wq

Now you should get a message that says “Installing crontab”
thats it, you’re done!

, ,

No Comments