Create random code by loading the PHP page

Asked

Viewed 332 times

-2

I’m creating a system for a real estate company, I need to create a random code for each insertion.

Examples are: C for home = C5241a4d / T for land = T77d4a1r

I want to play this code in an input, to create the folder that will receive the files, among other things.

I believe to be something like the example below:

    <?
$num = rand(1, 10);
  echo "O número gerado foi: " . $num;
?>

I would like instructions.

  • I would like to understand the negative point.

  • 3

    It was not I who denied, but it was not very clear what instructions you want. I answered some things based on what I understood.

  • People should explain, rather than just negatively. Lack of sense this.

  • I understand your point, it’s revolting to take a negative without an explanation. But sometimes some users do so for fear of reprisals (which unfortunately has happened a lot [including already happened and happens to me])

  • 1

    @Once I formulated a reply https://answall.com/a/314187/3635, the ideal way to avoid failures or conflicts is to use the ID of the property registered (assuming you use auto_increment in the table), so I left an example more or less to generate the folders.

  • @Wallacemaxters, I get upset, but ball forward... I work well on the front, but I suffer a little in the backend... anyway...

Show 1 more comment

2 answers

1


I would not do this in any way, there are no guarantees of "integrity", names can be repeated mixing files, folders that will be empty can be created and stay there without link with the bank, other problems can occur like this (depending on the system).

You can solve everything based on the ID of the item in the database table, when you create a table in a reasonable format, usually in most types of database you have the ID column, which is usually AUTO_INCREMENT, ie using this id will already solve the problem.

So when registering the property, take the ID, for example at the time of registering the property you use Insert, then right after use LAST_INSERT_ID, something like:

INSERT INTO imoveis (categoria, descricao) VALUES ('casa', 'foo bar baz');
SELECT LAST_INSERT_ID();

Then you can create a folder name based on this ID.

Of course, since you are using the PHP API so you could do everything yourself, you can create a function just to generate the ID-based folder:

function GerarPasta($categoria, $id, $target) {
    $prefixo = strtoupper($categoria{0}); // Gera C (casa), T (terreno), A (apartamento)

    $path = $prefixo . str_pad($id, 10, '0', STR_PAD_LEFT);

    if (!is_dir($path)) mkdir($path, 0755);
}

The use would be:

GerarPasta(<categoria>, <id do banco do imovel>, <pasta aonde vai criar as pastas>);

In this function I did not generate strings with url format youtube, but rather based only on ID, so properties with ids like 1, 2, 3, 4 and 100 will generate:

GerarPasta('casa', 1, '/foo/bar/');        // Gera pasta: /foo/bar/C0001
GerarPasta('terreno', 2, '/foo/bar/');     // Gera pasta: /foo/bar/T0002
GerarPasta('apartamento', 3, '/foo/bar/'); // Gera pasta: /foo/bar/A0003
GerarPasta('casa', 4, '/foo/bar/');        // Gera pasta: /foo/bar/C0004
GerarPasta('casa', 100, '/foo/bar/');      // Gera pasta: /foo/bar/C0100

Which I believe already suits your case well, but if you really want a string scheme I think you should use the function like this:

function GerarPasta($categoria, $id, $target) {
    $prefixo = $categoria{0}; // Gera C (casa), T (terreno), A (apartamento)

    //Usando L gera em 32bit combinado com o "repetidor *"
    $packb64 = base64_encode(pack('L*', $id));

    //Remove qualquer caractere diferente de A-Z e 0-9
    $foldername = preg_replace('#[^\da-z]#i', '', $packb64);

    $path = $prefixo . $foldername;

    if (!is_dir($path)) mkdir($path, 0755);
}

Note: I haven’t tested the function, I don’t know if she can conflict

Examples generate something like:

GerarPasta('casa', 1, '/foo/bar/');        // Gera pasta: /foo/bar/CAQAAAA
GerarPasta('casa', 2, '/foo/bar/');        // Gera pasta: /foo/bar/CAGAAAA
GerarPasta('casa', 3, '/foo/bar/');        // Gera pasta: /foo/bar/CAWAAAA
GerarPasta('casa', 1000, '/foo/bar/');     // Gera pasta: /foo/bar/C6AMAAA
GerarPasta('casa', 1000000, '/foo/bar/');  // Gera pasta: /foo/bar/CQEIPAA
GerarPasta('casa', 10000000, '/foo/bar/'); // Gera pasta: /foo/bar/CGJAYAA

Example of use:

I don’t know how you did the code, but if you used preparedstatment it must be something similar to this:

if (isset($_POST['categoria'], $_POST['descricao'])) {

    $categoria = $_POST['categoria'];
    $descricao = $_POST['descricao'];

    if (!$connection->prepare('INSERT INTO imoveis (categoria, descricao) VALUES (?, ?)')) {
       if ($prepared->bind_param('ss', $categoria, $descricao)) {
            if ($prepared->execute()) {
                 //Aqui pega a ID
                 $id_inserido = mysqli_insert_id($link);

                 GerarPasta($categoria, $id_inserido, '/home/user/public_html/'); //Cria a pasta
            } else {
                echo 'Falha ao executar a query';
            }
       } else {
            echo 'Falha nos parametros passados';
       }

       $prepared->close();
    } else {
         echo 'Falha no prepare';
    }
}
  • I thank you for your time. Actually, to explain what I need to do, it’s simple. I’ve been looking for a code to adapt from a "multi-upload" to set up this real estate scam. I already do an INSERT with PDO, I have an upload of only one file, and it works perfectly. I thought that by creating the folder and linking it to the bank, I could solve this issue. Regarding the code posted, being C0001 for home, for example, already serves me enough, because I can create a sequential. I just did not do it in AUTO INCREMENT, because I couldn’t use letters with numbers, as you mentioned earlier.

  • Anyway, to finish, I will try to make the application and test. I promise that I will come back with results, since I need to deliver everything by tomorrow. Once again, thank you for your time, @Guilherme.

  • @Agêncialabarba but your tables have Ids already, or not? Independent of the upload system.

  • Yes, there’s the ID. I’m breaking my head here, but I think I should do it separately INSERT, using SESSION maybe... enter the details, and then send the photos. I have a multiple upload system, which register in a new table, but each photo with a ID different.

  • So mixing session and doing things like that just complicates and will fall for what I said, you will lose integrity integridade, will be very suggestible to problems. So I worked out the solution like this.

  • I’ll take it easy, I told you what I thought once, but I changed my mind after your instruction.

Show 1 more comment

1

I’ll give an opinion:

I want to play this code in an input, to create the folder that will receive the files, among other things.

Really? You will really trust information coming from the customer (understand "browser").

It’s not a good idea to use a value from input to create a folder based on a value from that input.

But objectively answering the question: You can generate unique values through some PHP functions like uniqid.

   $valor = uniquid()

You can pass in the first parameter a value to be the prefix of the generated code, and in the second parameter to "leave more unique still", if necessary.

If you want to put that in an input, just do something like:

<input type="hidden" value="<?= uniquid() ?>" name="codigo_aleatorio">

But with sincerity, distrusting for the end that will be used, I would not advise.

If you want to have a unique code to create a folder after form submission, use a session value, or generate it at the time of upload, or anything else, except rely on what comes from the client to do this, for safety reasons.

  • Thanks for the explanations. I need to create a code, even if I only use it for property reference, using this logic: if it’s a house, C74521201 (random number). I’ll take your advice, not use it for other purposes. I have a problem to finish the multiple upload, I thought this as an alternative, play in a folder and pull after... but, let’s just consider the code, so I save the property. Thank you!

  • Wallace and @Agêncialabarba I personally would not do this, but rather take the bank ID which is auto-increment and encode at the time of displaying, with something similar to https://answall.com/a/266209/3635 - of course in this case could pick up the first letter of the property type using $row['categoria']{0} (variable would imagine). So this way would probably avoid conflicts.

  • 1

    To include Wallace in another question was even what Bacco suggested: https://answall.com/questions/281700/d%C3%Bavida-gerar-string-aleat%C3%B3ria-de-6-characters-in-php#comment575181_281700 - then - use the ID, so you’re on right? If Bacco said it’s true :)

  • Just so your solution doesn’t get too dangerous. On the form page, create a session with a token inserted. Something like $Rand(1,10) $token = sha1($Rand); $_SESSION['token'] = $token; . This is all inserted into an Hidden HTML From there on the form receipt page, you create a business rule to deny invalid tokens. If $_POST['token'] is different from $_SESSION['Toke'] {// Do this};

  • Remembering that uniqid repeats itself if calling the function with very short interval of time (more than one thread/instance despite the internal gambiarra to make delay of the implementation) or if there is qq weirdness with the machine clock control (went off schedule, and an ntp adjustment without drift took place).

  • Perfect all comments. I will follow the instructions, thank you for your time. As soon as I resolve this issue, I come to bring what has been done, to make reference to the whole community. Thank you!!

Show 1 more comment

Browser other questions tagged

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