Home > Mobile >  uniqid() in PHP altered the last string to something else
uniqid() in PHP altered the last string to something else

Time:03-12

I'm having a problem with the uniqid. I'm trying to save the uniqid in the database and create a QR code with it. The last string, as I noticed, was not the same.

Example: This is the code 622b47895d332 that has been inserted in the database while the filename of the stored QR code is 622b47895d333.png.

How is it possible that the data in the database doesn't match the filename of the QR code?

Here's the code that I'm currently using in generating a QR code..

$text = uniqid();
$path = 'temp/';
$file = $path.uniqid().".png";
$ecc = 'L';
$pixel_Size = 10;
$frame_Size = 5;

QRcode::png($text, $file, $ecc, $pixel_Size, $frame_Size);

Here's the full PHP code on how I insert it in the database

include 'db_connect.php';

    $conn = OpenCon();

      if (isset($_POST['submit'])) {

        $text = uniqid();
        $path = 'temp/';
        $file = $path.uniqid().".png";
        $ecc = 'L';
        $pixel_Size = 10;
        $frame_Size = 5;

        // Generates QR Code and Stores it in directory given
        QRcode::png($text, $file, $ecc, $pixel_Size, $frame_Size);

        $fname = $_POST['fname'];
        $mname = $_POST['mname'];
        $lname = $_POST['lname'];
        $suffix = $_POST['suffix'];
        $dept = $_POST['dept'];
        $user_type = $_POST['user_type'];
        $stat = 1;

        $sql = "INSERT INTO users (qr, fname, mname, lname, suffix, dept, user_type, stat) VALUES ('$text','$fname','$mname','$lname','$suffix','$dept','$user_type','$stat')";

        $result = $conn->query($sql);

        if ($result == TRUE) {

          echo '
          <div >
          User has been added!
          <button type="button"  data-bs-dismiss="alert" aria-label="Close"></button>
          </div>
          ';

        } else {

          echo "Error:". $sql . "<br>". $conn->error;

        }

      $conn->close();

      }

CodePudding user response:

You need to generate uniqid() only ONCE, and then reuse it:

$uniqueid = uniqid();
$text = $uniqueid;
$path = 'temp/';
$file = $path.$uniqueid.".png";
$ecc = 'L';

or as a shorter alternative:

$text = uniqid();
$path = 'temp/';
$file = $path.$text.".png";
$ecc = 'L';

You wrongly expect to get the same UniqueID from a function which generates/returns "UNIQUE" IDs every time it is called

  • Related