Generate code aletaorously to an input

0

What friends can I do to generate a random code and show it in an input (it would have to be 13 digits) and that some format can be applied, for example that always start at 7 is for barcode and that This in turn does not repeat itself, and always be random.

<div class="form-group <?php echo !empty(form_error('codigo_barras')) ? 'has-error':'';?>">
    <label for="codigo_barras">Codigo de Barras:</label>
    <input type="text" class="form-control" id="codigo_barras" name="codigo_barras" required value="<?php echo set_value('codigo_barras');?>">
    <?php echo form_error("codigo_barras","<span class='help-block'>","</span>");?>
</div>

    
asked by WilsonicX 25.10.2018 в 18:10
source

1 answer

-1

To generate a random string you can create a class with the following code:

 class tools{

    public function randomCode() {
                $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
                $pass = array();
                $pass[]="7"; 
                $alphaLength = strlen($alphabet) - 1; 
                for ($i = 0; $i < 12; $i++) {
                    $n = rand(0, $alphaLength);
                    $pass[] = $alphabet[$n];
                }
                return implode($pass); 
    }
}

In addition to this code you can make another class, so that it makes a query to the database (if you keep this code in database, and thus validate if it already exists, and if it already exists, generate a new one).

And well, to insert it in your input it could be like this:

formulario.php

<!DOCTYPE html>
<html>
<head>
    <title>

    </title>
</head>
<body>
    <?php 

        require_once "tools.php";

        $instancia = new tools();
        $codigo = $instancia->randomCode();
     ?>
    <div class="form-group">
    <label for="codigo_barras">Codigo de Barras:</label>
    <input type="text" class="form-control" id="codigo_barras" name="codigo_barras" required value="<?php echo $codigo?>">

</div>
</body>
</html>

The result would be this:

    
answered by 25.10.2018 в 18:31