Matthew K. Matthew K. - 6 months ago 9
HTML Question

How do I generate a list of random strings and hashes and output it in an HTML table?

I'm trying to generate a list of, let's say 10, random strings and it's SHA-256 hash in an HTML table.

I have found the following code submitted by another user to generate the random string:

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


How do I loop the function and how do I output the string and the hash of the string in an HTML table?

Answer

Try this code:

<?php
function generate($length)
{
    $string = '';
    if($length > 128)
    {
        $string .= generate($length-128);
    }
    else
    {
        $string = substr(hash('sha512',mt_rand()),0,$length);
    }
    return $string;
}

$table = '<table>%s</table>';
$item = '<tr><td>%s</td><td>%s</td></tr>';
$res = '';
for($i=0;$i<10;$i++)
{
    $str = generate(10);
    $hash = hash('sha256', $str);

    $res .= sprintf($item, $hash, $str);
}

echo sprintf($table, $res);
Comments