Aaron Saray

open source programmer,
web developer

entrepreneur, author
and musician

My Blog

contains PHP, Web and business/entrepreneurial related content. Please join in the conversation!

How to Quickly Mask a Credit Card Number

So, often I have to show a masked credit card on the screen. However, I really want to go the extra mile and show the user a secure, fully masked credit card number that still reflects their original card. For example, if their credit card number is only 15 numbers long, I shouldn’t show a 16 character long string. So, I’ve developed this code snippet:

1
2
$cc='1234123412341234';
$masked = str_pad(substr($cc, -4), strlen($cc), '*', STR_PAD_LEFT);

This simply takes the credit card, substr() the last 4 digit into the str_pad() method as the input. Then, says the length of the output string should be strlen() of the actual input. The pad character is a *. Finally, pad everything on the left. This way, no matter what, the output length will be the same as the input string, and it will be padded correctly.

This entry was posted in PHP, programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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