Create different random password for each loop record

Asked

Viewed 288 times

1

I have a loop that you should enter a random password for each record, and when you finish the loop (have created different password for each record), list the results by viewing the password.

 <?php
ob_start();
session_start();

//conexão com banco
include ("conn.php");

//definição de variáveis
$tabela = "chatoperator";
$campos = "operatorid, vclogin, dtmlastvisited, istatus, vcpassword"; 
$quant = 10; //número de ações que será realizada de cada vez 
$sec = 10; //tempo entre o envio de um pacote e outro (em segundos) 
$ok = 0;
$inicio = 0;
$fim = $inicio + $quant; 
$acentos = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";

//verifica se a senha confere com a da sessão
echo $acentos;

$sql = "select $campos from $tabela where istatus = 0 limit $inicio,$fim" or die (mysql_error($sql)); 
$query = mysql_query($sql,$conexao); 
$registros = mysql_num_rows($query); 

if($registros==0){
    mysql_query("update $tabela set istatus = 0" or die (mysql_error($conexao))); 
        echo("<font face=’tahoma’>todas as senhas foram alteradas!</font>"); 
    $ok = 1;
}else{
    while($result = mysql_fetch_array($query)) {
        $operatorid = $result[0]; //operatorid
        $vclogin = $result[1]; //vclogin
        $dtmlastvisited = $result[2]; //dtmlastvisited
        $istatus = $result[3]; //istatus
        $vcpassword = $result[4]; //vcpassword

        //gera senha aleatória
        function geraSenha(){
        //caracteres que serão usados na senha randomica
            $chars = 'abcdxyswzABCDZYWSZ0123456789';
            //ve o tamnha maximo que a senha pode ter
            $max = strlen($chars) - 1;
        //declara $senha
            $senha = null;

        //loop que gerará a senha de 8 caracteres
            for($i=0;$i < 8; $i++){
            $senha .= $chars{mt_rand(0,$max)};
    }
    return $senha;          
}
$senha_randomica   =  geraSenha();
$senha = md5($senha_randomica);

mysql_query("update $tabela set istatus = 1 AND vcpassword = '$senha_randomica' where    operatorid = $operatorid") or die (mysql_error($conexao));
    echo("
<table width='100%' border='1'>
    <tr>
        <th>Identificador do Usuário</th>
        <th>Login do Usuário</th>
        <th>Data do Último Acesso</th>
        <th>Status do Acesso</th>
        <th>Senha do Usuário</th>
   </tr>
   <tr>
        <td> $operatorid </td>
        <td> $vclogin </td>
        <td> $dtmlastvisited </td>
        <td> $istatus </td>
        <td> $senha_randomica </td>
  </tr>
 </table>");
      }
   }
    mysql_free_result($query); 
    mysql_close($conexao);

    if(!$ok){
        echo("<meta http-equiv=\"refresh\" content=\"" . $sec . "\">"); 
}
?>
  • What is your difficulty?

  • The script is generating the SAME password for all records, the idea is that a different password would be generated for each record. Thanks for the feedback @bigown

  • Without indentation it’s hard to understand what’s going on. If you~e [Edit] the question with better formatting of the code, who knows even you find some error.

1 answer

4


The problem seems to be just that the function geraSenha is inside the loop. Put it before all this code.

function geraSenha() {
    //caracteres que serão usados na senha randomica
    $chars = 'abcdxyswzABCDZYWSZ0123456789';
    //ve o tamnha maximo que a senha pode ter
    $max = strlen($chars) - 1;
    //declara $senha
    $senha = null;
    
    //loop que gerará a senha de 8 caracteres
    for ($i=0;$i < 8; $i++) {
        $senha .= $chars{mt_rand(0,$max)};
    }
    return $senha;          
}
$i = 0;
while ($i < 10) {
    echo geraSenha() . "\n";
    $i++;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The question clearly speaks in problem to create password and in fact without the above change I tested and only generates one. Now in the comments the problem seems to be another. There is an error also in saving the data. It would need to be so (if I understood the intention).

mysql_query("update $tabela set istatus = 1, vcpassword = '$senha_randomica' where    operatorid = $operatorid") or die (mysql_error($conexao));

Then you’d be like this (there’s no way I can test a code that doesn’t follow the MVCE.

<?php
function geraSenha(){
    $chars = 'abcdxyswzABCDZYWSZ0123456789';
    $max = strlen($chars) - 1;
    $senha = "";
    for($i=0;$i < 8; $i++){
        $senha .= $chars{mt_rand(0,$max)};
    }
    return $senha;          
}

ob_start();
session_start();

//conexão com banco
include ("conn.php");

//definição de variáveis
$tabela = "chatoperator";
$campos = "operatorid, vclogin, dtmlastvisited, istatus, vcpassword"; 
$quant = 10; //número de ações que será realizada de cada vez 
$sec = 10; //tempo entre o envio de um pacote e outro (em segundos) 
$ok = 0;
$inicio = 0;
$fim = $inicio + $quant; 
$acentos = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />";

//verifica se a senha confere com a da sessão
echo $acentos;

$sql = "select $campos from $tabela where istatus = 0 limit $inicio,$fim" or die (mysql_error($sql)); 
$query = mysql_query($sql,$conexao); 
$registros = mysql_num_rows($query); 

if($registros==0){
    mysql_query("update $tabela set istatus = 0" or die (mysql_error($conexao))); 
        echo("<font face=’tahoma’>todas as senhas foram alteradas!</font>"); 
    $ok = 1;
}else{
    while($result = mysql_fetch_array($query)) {
        $operatorid = $result[0]; //operatorid
        $vclogin = $result[1]; //vclogin
        $dtmlastvisited = $result[2]; //dtmlastvisited
        $istatus = $result[3]; //istatus
        $vcpassword = $result[4]; //vcpassword

        $senha_randomica   =  geraSenha();
        $senha = md5($senha_randomica);

        mysql_query("update $tabela set istatus = 1, vcpassword = '$senha_randomica' where    operatorid = $operatorid") or die (mysql_error($conexao));
        echo("
<table width='100%' border='1'>
    <tr>
        <th>Identificador do Usuário</th>
        <th>Login do Usuário</th>
        <th>Data do Último Acesso</th>
        <th>Status do Acesso</th>
        <th>Senha do Usuário</th>
    </tr>
    <tr>
        <td> $operatorid </td>
        <td> $vclogin </td>
        <td> $dtmlastvisited </td>
        <td> $istatus </td>
        <td> $senha_randomica </td>
    </tr>
</table>"
        );
    }
}
mysql_free_result($query); 
mysql_close($conexao);

if(!$ok){
    echo("<meta http-equiv=\"refresh\" content=\"" . $sec . "\">"); 
}
?>
  • thanks for the return, but your solution generates 10 passwords (or how many I parameterize) but it does not generate one for each record within the loop, can help with this? Thank you

  • 1

    My solution generates as many as you want. just take out the function geraSenha from inside the loop. I have no way to show your code working so I adapted it to show it works. I saw that you cannot identify the code correctly, so if you tested my solution with your code you must have changed part of the wrong code. Without you clearly understanding where something starts and ends, it is difficult to know which parts of the code are giving problem and which need to be moved. The function should be moved to the beginning of the code, nothing else.

  • Well, indenting the code correctly is just a matter of visualization, it does not reflect the know or not of something, but okay, I did not change anything of its code, in fact it is the same that I had tested previously, however, even outside the loop/loop the password is generated, but the problem is to insert one in each record, not the same in all records. If you need any more information to understand MY question to help me, just let me know, thanks @bigown

  • Yeah, that’s the problem, it’s a question of understanding what you’re doing. And that’s what I’m telling you, if you understand the code, you’ll see where it has to change in yours. I have no way to show your working because it depends on your site. So you have to fix yours on your own, I showed you how to generate one for each. If you put a code that works and doesn’t depend on your website to work, I can help more. Here’s how to do it: http://answall.com/help/mcve

  • 2

    @Eduardo, if the solution presented did not solve your case, I think you better detail your difficulty, because testing with a simplified code here the passwords do not repeat. And I hope you don’t understand how critical, but it took me longer to read your code than to test the mustache solution. I understand that it’s your right to use a very messy code, but since you’re looking for help, you might want to indent the code to make it easier for people who are willing to help. Even the more organized the programmer, the more chance to find or not even make mistakes.

  • The final phrase of Bacco is the fundamental one. Even because it trains the brain to always work looking for the right one. People ignore the cognitive power this has.

  • I didn’t say passwords repeat themselves, I said they don’t generate one for each record. Another thing is the question of visualizing, my code here is well organized, because I learned this way, but as I always try to learn, thanks for the comments, I do not see them otherwise, but in this site I was not very happy with the indentation. My difficulty is very detailed in the initial question, the problem is not the generation of the password, but save one for registration. Thanks to @bigown also for the words.

  • 1

    @Eduardocorreia I edited to put the part of the problem that you had not mentioned before in any location.

  • Well, I didn’t change the title and much less the text of the original question, I don’t know why this statement that in the comments that I had not cited before the doubt or that in the comments would be another friendly problem, I’m sorry, if there was your interpretation of the text was not mine, because I maintain from the beginning that the problem is not the generation of the password, or the amount of it, but rather that it does not record a different one for each record. As for the query correction I had not even seen, why it serves such a service is not? Thank you, I will test.

  • I have shown that my code generates a different one each time. I have already told you that using my code adapted to yours will solve your problem. If you want me to give show more adapted to your do http://answall.com/help/mcveqI told you. I can show you a working example, but it has to be something that works independently of your website, that doesn’t need pages and that doesn’t need a database. I do password generation as you need and I get all necessary information.

  • Well, let’s get to the facts: my code or yours generates the random password. My code loops but inserts into the bank the same password for everyone, not a random one for each record. You claim that adapting your code to mine will work, but it is precisely because you do not know how to do this that I posted the question here. My question is whether you can (anyone) help make it work for real, that’s all.

  • The best I can do is post this latest issue, I have no way to test it but it’s supposed to work. Note that correctly indented code makes it easier to read and understand it. The solution is given and applied to your case. As I said there may be something else wrong, but the purpose of the site is to give solutions to the question asked and not solve all the problems of the code that the person posted. Now, if it doesn’t work, you need to see what you need to adapt or ask a new question with the specific new problem you’re having.

  • @bigown, it was perfect! I thank the attention and all those who also got involved. The loop rotated, saved a different password for each record, and printed the listing until the end of the loop. I hope this script (and the content of this post) helps someone else. This script is simple and generated a lot of discussion, I think this is cool because there is interactivity and help spirit. I know the level of this script is basic, but very useful for a certain situation for me. Thank you

Show 8 more comments

Browser other questions tagged

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