Better Luhn Formula CC Validator for PHP

I was doing some work integrating with a payment gateway in a PHP application, and decided it would be a good idea to validate credit card numbers using a Luhn Algorithm formula prior to forwarding them to the payment gateway for processing. I looked for existing PHP ones, and found a few.

The more I found the less I liked any of them. Some of them actually had bugs or typos and did not work at all, and most of them would incorrectly validate a credit card number that was all zeros.

I wrote my own that I’m pretty happy with. It’s a good deal more efficient that most that I found. It does not repeat the same math on the same figures like some of them out there do.


<?php

/*
 *   Copyright 2011 Adrian Otto
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

function luhn_validate($s) {
  if(
0==$s) { return(false); } // Don't allow all zeros
  
$sum=0;
  
$i=strlen($s);     // Find the last character
  
while ($i-- > 0) { // Iterate all digits backwards
    
$sum+=$s[$i];    // Add the current digit
    // If the digit is even, add it again. Adjust for digits 10+ by subtracting 9.
    
(0==($i%2)) ? ($s[$i] > 4) ? ($sum+=($s[$i]-9)) : ($sum+=$s[$i]) : false;
  }     
  return (
0==($sum%10)) ;

?>

The function contains 7 lines of code. Can you make this function better without making it harder to read and understand? Please let me know.

You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

1 Comment »

 
 

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam protection by WP Captcha-Free