Asked  7 Months ago    Answers:  5   Viewed   36 times

I know that the rand function in PHP generates random integers, but what is the best way to generate a random string such as:

Original string, 9 chars

$string = 'abcdefghi';

Example random string limiting to 6 chars

$string = 'ibfeca';

UPDATE: I have found tons of these types of functions, basically I'm trying to understand the logic behind each step.

UPDATE: The function should generate any amount of chars as required.

Please comment the parts if you reply.



Well, you didn't clarify all the questions I asked in my comment, but I'll assume that you want a function that can take a string of "possible" characters and a length of string to return. Commented thoroughly as requested, using more variables than I would normally, for clarity:

function get_random_string($valid_chars, $length)
    // start with an empty random string
    $random_string = "";

    // count the number of chars in the valid chars string so we know how many choices we have
    $num_valid_chars = strlen($valid_chars);

    // repeat the steps until we've created a string of the right length
    for ($i = 0; $i < $length; $i++)
        // pick a random number from 1 up to the number of valid chars
        $random_pick = mt_rand(1, $num_valid_chars);

        // take the random character out of the string of valid chars
        // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
        $random_char = $valid_chars[$random_pick-1];

        // add the randomly-chosen char onto the end of our string so far
        $random_string .= $random_char;

    // return our finished random string
    return $random_string;

To call this function with your example data, you'd call it something like:

$original_string = 'abcdefghi';
$random_string = get_random_string($original_string, 6);

Note that this function doesn't check for uniqueness in the valid chars passed to it. For example, if you called it with a valid chars string of 'AAAB', it would be three times more likely to choose an A for each letter as a B. That could be considered a bug or a feature, depending on your needs.

Wednesday, March 31, 2021
answered 7 Months ago

Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

If you do not need it to be absolutely unique over time:

md5(uniqid(rand(), true))

Otherwise (given you have already determined a unique login for your user):

md5(uniqid($your_user_login, true))
Wednesday, March 31, 2021
answered 7 Months ago

Much as I am loathed to use regex for something which is on the face of it very simple, in order to guarantee exactly n replaces I think it can help here, as it allows use to easily use array_rand(), which does exactly what you want - pick n random items from a list of indeterminate length (IMPROVED).


    function replace_n_occurences ($str, $search, $replace, $n) {

        // Get all occurences of $search and their offsets within the string
        $count = preg_match_all('/b'.preg_quote($search, '/').'b/', $str, $matches, PREG_OFFSET_CAPTURE);

        // Get string length information so we can account for replacement strings that are of a different length to the search string
        $searchLen = strlen($search);
        $diff = strlen($replace) - $searchLen;
        $offset = 0;

        // Loop $n random matches and replace them, if $n < 1 || $n > $count, replace all matches
        $toReplace = ($n < 1 || $n > $count) ? array_keys($matches[0]) : (array) array_rand($matches[0], $n);
        foreach ($toReplace as $match) {
            $str = substr($str, 0, $matches[0][$match][1] + $offset).$replace.substr($str, $matches[0][$match][1] + $searchLen + $offset);
            $offset += $diff;

        return $str;


    $str = 'I like blue, blue is my favorite colour because blue is very nice and blue is pretty';

    $search = 'blue';
    $replace = 'red';
    $replaceCount = 2;

    echo replace_n_occurences($str, $search, $replace, $replaceCount);

See it working

Wednesday, March 31, 2021
answered 7 Months ago

Number 1:

file_put_contents("foobar.csv", $yourString);

Number 2:

$c = curl_init("http://"...);  
curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "@foobar.csv"));
$result = curl_exec($c);

note the @ before the filename

Saturday, May 29, 2021
answered 5 Months ago

Well, you'll have to first create the zipfile, using the ZipArchive class.

Then, send :

  • The right headers, indicating to the browser it should download something as a zip -- see header() -- there is an example on that manual's page that should help
  • The content of the zip file, using readfile()

And, finally, delete the zip file from your server, using unlink().

Note : as a security precaution, it might be wise to have a PHP script running automatically (by crontab, typically), that would delete the old zip files in your temporary directory.

This just in case your normal PHP script is, sometimes, interrupted, and doesn't delete the temporary file.

Thursday, July 29, 2021
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :