2

I use the following script to generate a temporary password.

before I get a lecture, I AM aware that this isn't crypto secure, and that I should use something like openssl_random_pseudo_bytes. But my question is not regarding 'being secure'.

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!£$%^&*()?';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
         $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

I used PHPMailer connected to gmail SMTP to email the password to the user. The problem I have is that when my boss did a demonstration of this whilst in another country, the following characters were sent as the temp pw:

New Password: Il%KÂUyÂ?F

notice the accented A's are not in my string of selectable chars. This has only happened once, however shouldn't happen at all. As a result of this - the relevant hashes didn't match either, and so the temporary password didn't work. I'm using password_hash($string, PASSWORD_DEFAULT) with field length of 255.

Surely the fact that he was in a different country when he tested the function shouldn't have any bearing on the chars sent seeing as they are generated from the server, which obviously has a static location.

$key = generateRandomString();
$msg.="New Password: ".$key."<br><br>";
$mail->Body = $msg;
2
  • No, but a charset might depending on how the data was being displayed Commented Feb 5, 2016 at 11:56
  • Can you shed more light on this? The data was displayed in an email (ms exchange outlook). I have looked in the actual gmail sentbox, and the chars exist in there, so it must be something between php and the email that did it. Commented Feb 5, 2016 at 12:07

1 Answer 1

2

I have tried it myself and the function works perfectly, so I think your problem is about encoding.

First of all make sure your string is UTF-8 encoded, using

utf8_encode($key); 

You can use mb_detect_encoding on $msg and $key to check it just to be sure.
If you still have problems try:

$mail->CharSet = 'UTF-8';  

PHPmailer can be a pain with encoding sometimes.
Hope this helps :)

Sign up to request clarification or add additional context in comments.

1 Comment

Nice one, thanks very much! I still don't understand why it actually happened, though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.