0

I am trying to make a 12 digit password but the PHP variable sometimes prints only 1 or 3 digits but when I count the string of variable it shows 12.

 $caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $special = '!@#$%^&*<>?';
    $small = 'abcdefghijklmnopqrstuvwxyz';
    $digit = '0123456789';

    $capsLength = strlen($caps);
    $specialLength = strlen($special);
    $smallLength = strlen($small);
    $digitLength = strlen($digit);

    $randomString = '';
    for ($i = 0; $i < 3; $i++) {
        $randomString .= str_shuffle($caps[mt_rand(0, $capsLength - 1)] . $special[mt_rand(0, $specialLength - 1)] . $small[mt_rand(0, $smallLength - 1)] . $digit[mt_rand(0, $digitLength - 1)]);

    }
    echo strlen($randomString).'</br>';
    echo $randomString;
4
  • 3
    Are you viewing this in a browser? If your string contains < then it's probably trying to render it as an HTML tag. Try viewing the source of the page instead, they should be there. If you want it to display properly then you'll need to escape it. Commented Jan 28, 2021 at 9:31
  • 1
    Yes, or var_dump() the string. Commented Jan 28, 2021 at 9:32
  • 2
    or try with echo htmlspecialchars($randomString); Commented Jan 28, 2021 at 9:42
  • Thanks, @ADyson. That was the issue. Now it's working. Commented Jul 24, 2021 at 6:03

1 Answer 1

2

The problem here is that there are some characters like <> that the browser could interpret as HTML tags and try to render them as elements of the DOM.

The solution is to use htmlspecialchars to convert these special characters to HTML entities as @ADyson suggested.

You just have to change this line:

echo $randomString;

To this:

echo htmlspecialchars($randomString);
Sign up to request clarification or add additional context in comments.

Comments

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.