内存过载没有警告

I am creating a script to generate a custom alphanumeric checksum from a numeric one and it works perfecly fine except sometimes where it runs without stopping. To avoid that, I have placed some "checks" of the used memory. But even with that sometimes it continues executing until the execution limit. So do you have any idea to solve the problem please ? (Using WAMP on windows with PHP 5.5.12) The script :

function generateChecksum($checksum) {
    // The string where the characters of the checksum will be taken
    $securityStr = "frKRHndwmB2CyvWMVJek0GEOQUiaFjAL7zxZT8cNuI1s6pS3t4h9PXDoY5lbqg";
    // We declare the variables
    $cs = "";
    $sum = 1;
    // We reduce the size of the numeric checksum
    $checksum = $checksum % 30;
    // We generate the alphanumeric checksum
    while ($sum!=$checksum) {
        if ($sum<$checksum) {
            $rand=rand(0,24);
            $c=substr($securityStr, $rand, 1);
            $sum+=$rand;
            $cs.=$c;
            while ($sum>$checksum) {
                $sum-=$rand;
                $cs = substr($cs, 0, -1);
                $rand = rand(0, $rand);
                $sum+=$rand;
                $cs.=$c;
                // A first check of memory use
                if (memory_get_usage()>200000) {
                    throw new Exception("Memory overload");
                    exit;
                }
            }
        }
        // A second one
        if (memory_get_usage()>200000) {
            throw new Exception("Memory overload");
            exit;
        }
    }
    // If the checksum is too big or too short we generate another one
    if (strlen($cs)>15||strlen($cs)<5) {
        // Another one
        if (memory_get_usage()>200000) {
            throw new Exception("Memory overload");
            exit;
        }
        return generateChecksum($checksum);
    }
    return $cs;
}
// We set a time limit
set_time_limit(10);
// And we call the function
var_dump(generateChecksum(37854));

Thanks for your help, and sorry about my English.