Generate single random value with php

Asked

Viewed 2,472 times

1

I need to generate a random value with letters and numbers in PHP, always starting with the letter A and having numbers and letters mixed with the value. Refers to the "control code" field contained in this script:

    <?php require("header.php");?>
<?php require("menu.php");

if(isset($_POST['bt_save_df']))
{
$nome = $_POST['nome'];
$arquivo = $_POST['arquivo'];
$codigo = $_POST['codigo'];
$codcontrol = $_POST['codcontrol'];
$tipo = $_POST['tipo'];
$material = $_POST['material'];
$denominacao = $_POST['denominacao'];

$uploaddir = 'desenhos/arquivos/';
$pastadestino = 'desenhos/arquivos/';
// Pega a extensão do arquivo
$dividir2 = end(explode(".", $_FILES['imagem1']['name']));

// Gera um nome aleatório
$nome = time();
$nome_imagem2 = $nome . '1.' . $dividir2;
$uploadfile = $uploaddir . $nome . '1.' . $dividir2;
if (move_uploaded_file($_FILES['imagem1']['tmp_name'], $uploaddir . $nome_imagem2)) {

}

$arquivo = $pastadestino.$nome_imagem2;


$sql = 'INSERT INTO tbl_desenho (nome, arquivo, codigo, codcontrol, tipo, material, denominacao)';
$sql .= ' VALUES (:nome, :arquivo, :codigo, :codcontrol, :tipo, :material, :denominacao)';

try{

    $create = $db->prepare($sql);
    $create->bindValue(':nome', $nome, PDO::PARAM_STR);
    $create->bindValue(':arquivo', $arquivo, PDO::PARAM_STR);
    $create->bindValue(':codigo', $codigo, PDO::PARAM_STR);
    $create->bindValue(':codcontrol', $codcontrol, PDO::PARAM_STR);
    $create->bindValue(':tipo', $tipo, PDO::PARAM_STR);
    $create->bindValue(':material', $material, PDO::PARAM_STR);
    $create->bindValue(':denominacao', $denominacao, PDO::PARAM_STR);

    if($create->execute() ){
        echo '<script type="text/javascript" >
                alert( "Registro Cadastrado com Sucesso!"); location.href="ger_arquivos.php";
        </script>';

    }


} catch (PDOException $e) {
        echo "Erro ao Cadastrar Registro! - " . $e->getMessage();
    }
}

?>


            <!-- BEGIN Main Content -->
            <div class="row-fluid">
                <div class="span12">
                    <div class="box">
                        <div class="box-title">
                            <h3><i class="icon-reorder"></i> Cadastro de Desenhos</h3>
                            <div class="box-tool">
                                <a data-action="collapse" href="#"><i class="icon-chevron-up"></i></a>
                                <a data-action="close" href="#"><i class="icon-remove"></i></a>
                            </div>
                        </div>
                        <div class="box-content">
                            <form action="cad_arquivo.php" class="form-horizontal" id="validation-form" method="post" enctype="multipart/form-data">   
                                <div class="control-group">
                                    <label class="control-label" for="nome">Titulo:</label>
                                    <div class="controls">
                                        <div class="span12">
                                            <input type="text" name="nome" id="nome" class="input-xlarge" />
                                        </div>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label class="control-label" for="titulo">Código:</label>
                                    <div class="controls">
                                        <div class="span12">
                                            <input type="text" name="codigo" id="codigo" class="input-xlarge" />
                                        </div>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label class="control-label" for="titulo">Código de Controle:</label>
                                    <div class="controls">
                                        <div class="span12">
                                            <input type="text" name="codcontrol" id="codcontrol" class="input-xlarge" />
                                        </div>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label class="control-label" for="select">Tipo:</label>
                                    <div class="controls">
                                        <div class="span12">
                                            <select name="tipo" id="tipo">
                                                <option value=""> -- Selecione --</option>
                                                <option value="1">Produção</option>
                                                <option value="2">Kits</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label class="control-label" for="titulo">Material:</label>
                                    <div class="controls">
                                        <div class="span12">
                                            <input type="text" name="material" id="material" class="input-xlarge" />
                                        </div>
                                    </div>
                                </div>

                                <div class="control-group">
                                    <label class="control-label" for="titulo">Denominação:</label>
                                    <div class="controls">
                                        <div class="span12">
                                            <input type="text" name="denominacao" id="denominacao" class="input-xlarge" />
                                        </div>
                                    </div>
                                </div>


                                <div class="control-group">
                                  <label class="control-label">Arquivo</label>
                                  <div class="controls">
                                     <div class="fileupload fileupload-new" data-provides="fileupload">
                                        <div class="input-append">
                                           <div class="uneditable-input">
                                              <i class="icon-file fileupload-exists"></i> 
                                              <span class="fileupload-preview"></span>
                                           </div>
                                           <span class="btn btn-file">
                                               <span class="fileupload-new">Selecione o arquivo</span>
                                               <span class="fileupload-exists">Alterar</span>
                                               <input type="file" class="default" name="imagem1" id="imagem1"/>
                                           </span>
                                           <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
                                        </div>
                                     </div>
                                  </div>
                               </div>



                                <div class="form-actions">
                                    <input type="submit" class="btn btn-primary" name="bt_save_df" value="Salvar">
                                    <a href="ger_arquivos.php"><button type="button" class="btn">Voltar</button></a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <!-- END Main Content -->

It should be generated automatically as I will delete the "control code" part of this option.

In this case, the codcontrol variable should be automatically supplied with these rules, as I could do, totally eliminating this input?

  • What is the control code structure? What is the maximum and minimum size? Do you have access to the file system? Is the code running on Linux? Do you have access to SSL libraries? Is the control code required to be cryptographically secure? These data are important in order to provide an answer.

  • There is no security required, it is just an identification value. Up to 9 digits is enough, the server is in linux. The minimum size can be 2. I don’t have access to SSL libraries.

3 answers

3

1

You can use a function like this:

function valorAleatorio($qtdSorteio = 5) {
    $letras = array('A','a','B','b','C','c','D','d','X'); // precisa ter 9 itens
    $resultado = '';
    while($qtdSorteio > 0) {
        $resultado .= rand(0,9); // sorteia valores entre 0-9
        $resultado .= $letras[$qtdSorteio]; // retorna do array a letra pela chave
        $qtdSorteio--;
    }

    return 'A'.$resultado;
}
  • I like your scheme, but in case I capture this result to supply the variable I need?

  • This method generates an ID but does not guarantee unique Ids, as its formation is random it may have repeated combinations. Here I take the test of how many times the ID is repeated in a loop of 10,000 iterations http://ideone.com/869XXG and this one showing that with uniqid the ID will actually be unique in the same loop of 10,000 interactions http://ideone.com/WGeurd

1


A different way is to split the list of characters and use a lot of str_shuffle.

Here’s an example:

$id = 'A'.substr(
    str_shuffle(
        str_shuffle('ghijkl').
        str_shuffle(6543).
        str_shuffle('ABCDEFGHI').
        str_shuffle('012').
        str_shuffle('fedcba').
        str_shuffle('ZYXWVUTSRQ').
        str_shuffle('mnopqr').
        str_shuffle(789).
        str_shuffle('JKLMNOP').
        str_shuffle('zyxwvuts')
    ),

    mt_rand(0,53),
    mt_rand(2,9)
);

The variable $id will have a key Random size Random strings arranged so Random.

Strings used can be changed in the way that is preferable.

  • Good if it doesn’t need unique Ids because it has the same problem of the other answer it can generate more than once the same id http://ideone.com/k3Vz5J

  • @Adirkuhn Can you read this comment: http://answall.com/questions/59779/gerar-valor-aleat%C3%b3rio-unico-com-php/59821? noredirect=1#comment123248_59779 Moreover, it is quite trivial to check whether a key already exists. And these are the results for the distribution of values based on these strings defined by me. They can be changed to taste. If I had access to the trust system, I’d do better.

  • or avoid all these lines of code by a native PHP function that ensures unique ID (uniqid) as it is in the question title, without having to do extra database query to see if the key already exists.

  • @Adirkuhn As it is in the commentary: "Não tenho acesso as bibliotecas SSL."

  • SSL? Dude you read? Let me quote the php manual here "There is no installation needed to use These functions; they are part of the PHP core." That is, part of the core does not need to install anything or have SSL.

  • @Adirkuhn So it doesn’t exist "uma função nativa do PHP que garante ID único". Read http://php.net/manual/en/function.openssl-random-pseudobytes.php. to see what I’m talking about.

  • http://php.net/uniqid native PHP function that ensures unique ID in this application because it is only on a server (it does not guarantee global uniqueness because it is generated based on millionths of a second and it can happen that different servers generate the same code). But as I said in this case will always be unique. But ok you won

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.