PHP Security
PHP Security Codes – Code, Program & Snippets Collection – Free Code Script for Students project & practise provided by Tutorials Class.
Partially hide email address in PHP
There are following reasons why we need to hide partially hide email address when displaying on website.
- If you reset password using username, and you want to provide a hint about registered email id.
- Sometimes, you provide a link to email but do not display emails to users or Spam Bots.
- If you want to display some information to user’s mail and want to show it but hide partially to prevent public access.
Code Solution:
To Partially hide email address in PHP, you can take half characters of email username and replace with certain characters. Here is the PHP function that you can use for your project to hide email address.
<?php
function hide_email($email) {
// extract email text before @ symbol
$em = explode("@", $email);
$name = implode(array_slice($em, 0, count($em) - 1), '@');
// count half characters length to hide
$length = floor(strlen($name) / 2);
// Replace half characters with * symbol
return substr($name, 0, $length) . str_repeat('*', $length) . "@" . end($em);
}
echo hide_email("contactus@gmail.com");
// Output: cont****@gmail.com
?>
Try and Run Code: https://paiza.io/projects/zMahQUVs7CCSDiHPslKWzQ
Why we should not hide fixed character length?
Because if we hide fix character (suppose 5) for each email, some email might have less than 5 characters and then all characters will get hide. Therefore, it is good to practise to take half of whatever length is there.