2018-12-23 Pujan Niroula 1 Minute(s) Read

How To Partially Hide Email Address in PHP

img-partially hide email with php.jpg

Perhaps you may noticed twitter, facebook, google partially hide email address during forgot password process. To reduce risk of user enumeration vulnerability. If you want to do same in your PHP web application then this post is for you.

twitter email partially hidden screenshot

In this tutorial I will show step by step method to hide email address partially. It will display just few character of email address and email domain.

Hide Email Address Partially in PHP

Lets do it, First we will verify email is valid or not then we replace each except first two character with '*'.

function hide_email($email)
    if(filter_var($email, FILTER_VALIDATE_EMAIL))
        list($first, $last) = explode('@', $email);
        $first = str_replace(substr($first, '2'), str_repeat('*', strlen($first)-2), $first);
        $last = explode('.', $last);
        $last_domain = str_replace(substr($last['0'], '1'), str_repeat('*', strlen($last['0'])-1), $last['0']);
        $hide_email = $first.'@'.$last_domain.'.'.$last['1'];
        return $hide_email;
$email = "contact@gmail.com";
echo hide_email($email); //co*****@g****.com

At first we validate email with PHP's pre-loaded function filter_var and FILTER_VALIDATE_EMAIL

After that I broke email into array with explode function. The first part of email is before '@' sign and second part of email is after '@' sign. Strlen() function returns length of string.

Str_replace() will replace first parameter with second parameter in third parameter.

Substr() will remove all character after given second parameter in the string. Similarly str_repeat() repeats the given string.

Finally I collected all strings on $hide_email and return it.

Hope you like this tutorial, I will be happy to see you in comment section below.

Comments (0) Add New Comment
No comments, Be first one to commment!