PHP - How To Generate A Unique Random Number In Php???
How to generate a unique random number in php??? Any one who can help me?
Similar TutorialsI am looking to generate a random number for every user contribution as a title of the contribution. I could simply check the database each time with a query and generate a number which does not equal to any of the entries of the database. But I imagine this as inefficient and it could become slow if the database is big in my opinion. Also I'd have to contain all the numbers of the database somewhere to manage the "not equals to", in an array or something similar but that can end up as a giant one. Excuse the layman's speech I am new to this. Any suggestions how this can be solved efficiently without straining the resources too much? You can explain it linguistically and do not have to provide me any scripts, I will figure it out. hi!, is it possible to use rand() to generate unique number that will be saved in a database as a primary key? Since i dont want to have numbers like 00001 incrementing on the table. They dont look like real account numbers... i need something like 45642 or 95452 and the like. thanks in advance. This might be a bit hard to explain! I have a grid, 32x32 which is actually 1024 mySQL rows in a table, you can see the table he http://interbitlotto.com/grid each cell is a row in the database, top left is ID 1, bottom right is id 1024. get it? right well its a battle ship game, and im stuck on the automatic battle ship placement script. I have displayed the generated boats as misses so we can see them. The problem i am having, is that the random number generater chooses a cell too close to the side so the boat ends up wrapping to the other side. I cant think of a way to detect if its going to wrap, if it is then choose another cell... The code below chooses the orientation of the boat, then chooses a random cell... but as you can see, no code for "across" to stop it choosing one too close to the side. Any ideas? Code: [Select] $orientation = rand(1,2); //get random orientation - 1 = down, 2 = across. if ($orientation == 1){ $multiply = 32; //cells till next row $max = 1024 - (32 * $boatlength); //prevents it from choosing a cell too close to the bottom $startcell = rand(1,$max); }else{ $multiply = 1; //across, so next cell $max = 1024; $startcell = rand(1,$max); } Hello, Do you guys have any idea how to start an Automatic Order Number System in PHP? I have an service Website, where you can purchase something, and i want after the redirect to "Success.php" to generate an order number, to be shown to the buyer and saved in Date Base for me. Any solutions helps. I´m beginner so don´t mind
hi, im trying to create a website and only now started thinking about the security part(noob mistake). say for example i have home.php page and an index.php page. index.php is where users would sign up/log in. the login and sign up processes are all done but i was thinking of creating a unique id of some sort for when the user logs in. or something like this site (forum.phpfreaks) when we sign in, you are signed but the url stays the same = forums.phpfreaks.com. like if we were signed out we will be permanantly signed out and typing in forums.phpfreaks.com would just land us at the main page where we need to sign in.
right now ,my home.php can be accessed with or without logging in even with sessions.
hope im making sense, thanks in advanced!
**haha that rhymed.
i tried adding:
<?php echo $_SERVER[PHP_SELF] . '?name=' . $userData['name'];?> in the index.php:
<?php ob_start(); session_start(); if(isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['pass']; require "connection.php"; $emails = mysqli_real_escape_string($con, $email); $query = "SELECT id, name, email, password, salt FROM users WHERE email = '$emails';"; $result = mysqli_query($con, $query); if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again. { echo "<script>alert(\"User does not exist!\")</script>"; } $userData = mysqli_fetch_array($result, MYSQLI_ASSOC); $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) ); if($hash != $userData['password']) { echo "<script>alert(\"Incorrect Password!\")</script>"; }else{ session_regenerate_id(); $_SESSION['sess_user_id'] = $userData['id']; $_SESSION['sess_name'] = $userData['name']; session_write_close(); header('Location: home.php?user='); } } ob_flush(); ?> <!DOCTYPE html> <form name="login" method="post" action="<?php echo $_SERVER[PHP_SELF] . '?name=' . $userData['name'];?>">but i got access forbidden! Edited by noobdood, 19 May 2014 - 10:05 PM. My table looks like this.. `guns_id` int(255) NOT NULL auto_increment, `guns_name` varchar(255) collate latin1_general_ci NOT NULL, `guns_price` int(255) NOT NULL, PRIMARY KEY (`guns_id`) I want to add a product key that is unique through out the whole database as I have other products other than guns aswell. Hi Looking to create an ID which only contains alpha-numeric (no special chars). I looked to generate random bytes and then encode in base64 but base64 contains = + /. The below seems to do it but not sure if bin2hex can return non alpha numeric? bin2hex(openssl_random_pseudo_bytes(18)); Edited December 18, 2018 by mds1256 I'm not sure I'm in the right place, but I'm looking to create a unique URL that links to the same page every time I send an email after a form is submitted on my website and have it expire after 15 days. After expiring, the link would redirect to a default page. I'm still a beginner and realize this is probably going to be a tough task, but any resources or direction provided would be much appreciated. Thanks for the help in advance! As above, I have a lottery style site that picks a random number between 1-8 but my users complain for some reason that this is not enough. So i was told to look into using fopen and random.org to generate a random number. Anyone have experience of this and perhaps a code snippet for me to look at and possibly use? help will be appreciated. How do you generate a random number like say, 0 through 10? I want to select random sites from my database that have IDs 0 through 10. Hi, im trying to apply a random css class to a div so that a random image is generated on each refresh. This is the code i am using to apply the class. Code: [Select] <div class="<?php echo($randomimage); ?>"> Say i have an array of $image1 $image2 $image3 etc, how can i make $randomimage = 1 of these at random on each refresh? I've found lots of tutorials that generate a random number online but none that generate a random variable and am having trouble piecing this together. Any help would be hugely appreciated. Richard Hi there. I need a function that can generate 15 random numbers between (1,10) and then converts those numbers to Roman numbers. Anyone can help me? Hi, I have a script to add images to my tabel and and upload them to my server, I have managed to get the upload script to rename the image with a 5 digit random number on the end to prevent overwriting, the only problem I can't seem to be able to add the same name to my tabel. Any ideas? Thanks in advance. Code: [Select] <?php $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], $idir. basename($_FILES['fupload']['name'], $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Perm } } if (isset ($_FILES['fupload2'])){ //upload the image to tmp directory $url = $_FILES['fupload2']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload2']['type'] == "image/jpg" || $_FILES['fupload2']['type'] == "image/jpeg" || $_FILES['fupload2']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload2']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload2']['tmp_name'], "$idir" . $_FILES['fupload2']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload3'])){ //upload the image to tmp directory $url = $_FILES['fupload3']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload3']['type'] == "image/jpg" || $_FILES['fupload3']['type'] == "image/jpeg" || $_FILES['fupload3']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload3']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload3']['tmp_name'], "$idir" . $_FILES['fupload3']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload4'])){ //upload the image to tmp directory $url = $_FILES['fupload4']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload4']['type'] == "image/jpg" || $_FILES['fupload4']['type'] == "image/jpeg" || $_FILES['fupload4']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload4']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload4']['tmp_name'], "$idir" . $_FILES['fupload4']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } $usr = "user"; $pwd = "pass"; $db = "db"; $host = "host"; # connect to database $cid = mysql_connect($host,$usr,$pwd); if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); } if ($_POST['submit']) { $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $image1 = mysql_real_escape_string("$idir" . $_FILES['fupload2']['name']); $image2 = mysql_real_escape_string("$idir" . $_FILES['fupload3']['name']); $image3 = mysql_real_escape_string("$idir" . $_FILES['fupload4']['name']); $SQL = " INSERT INTO mhhire "; $SQL .= " image1, image2, image3, logo) VALUES "; $SQL .= " ('$image1', '$image2', '$image3', '$logo') "; $result = mysql_db_query($db,$SQL,$cid); $last=mysql_insert_id(); if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } header("location:thanks.php"); exit(); } ?> So I found this code from someone else on here who posted about creating a random string. I've copied the code for myself but when I upload php page to my server and view source... there is no php code. Essentially, i see no randomly generated text. what am i missing? Code: [Select] <?php function genRandomString() { $length = 5; $characters = array_merge(range(0,9),range('a','z'),range('A','Z')); $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, count($characters)-1)]; } return $string; } ?> hi, I am trying to create 7 lines, out of 49 numbers, each line must have unique numbers not seen in any other line so that every number out of 49 has been used in one of those lines, I also need them to be in order, lowest to highest except for the last number which needs to be completely any random ( as long as its not elsewhere in the 7 lines and its one of 49) I have made an attempt, <?php function code(){ for ($i=1; $i<=7; $i++){ $one = mt_rand(1, 49); echo $one; echo ' '; }} function lines(){ for ($i=1; $i<=7; $i++){ code(); echo '<br/>'; }} lines(); ?> but I am seriously failing at producing every number from 1 to 49 throughout those 7 lines and of course failing at ordering them with the random at the end that is not in order.. sorry if this sounds confusing but I would appreciate any help, thanks Hi, First off: I got a table with two columns and 100.000 rows. Some of the rows are duplicates (allowing me to "weight" the chance of some rows being hit the first time the script runs) Allright. This i what I want to do: When the user clicks a button: 1. Generate a random selected row from the table (this I allready accomplished using this code: Code: [Select] <?php //CODE FROM WWW.GREGGDEV.COM function random_row($table, $column) { $max_sql = "SELECT max(" . $column . ") AS max_id FROM " . $table; $max_row = mysql_fetch_array(mysql_query($max_sql)); $random_number = mt_rand(1, $max_row['max_id']); $random_sql = "SELECT * FROM " . $table . " WHERE " . $column . " >= " . $random_number . " ORDER BY " . $column . " ASC LIMIT 1"; $random_row = mysql_fetch_row(mysql_query($random_sql)); if (!is_array($random_row)) { $random_sql = "SELECT * FROM " . $table . " WHERE " . $column . " < " . $random_number . " ORDER BY " . $column . " DESC LIMIT 1"; $random_row = mysql_fetch_row(mysql_query($random_sql)); } return $random_row; } //USAGE $randomdata = random_row('MYTABLE', 'MYCOLUMN'); echo $randomdata[2]; // Where [2] is the data I want to extract. ?> This script works fine. The problem is that I want to exclude the results that have allready been shown. With me? Therefore, since I have duplicate rows of certain data, I need to exclude all the rows that are the same. I have a couple of solutions, but I can't seem to fit it into this script. (I will not use the ORDER_BY_RAND() query; it'll be too slow for a table with 100.000 rows) SO: Here's ideas I've come up with that might work, but because of my limited experience with PHP and MySQL, haven't been able to accomplish. 1) Insert a "temporary" column in the table which is filled with 1 and 0's where 1 indicates that the row has allready been taken? (If possible) 2) Use PHP sessions to store the previously generated rows? 3) Create a temporary table, which fills up with the allready generated rows by the random script? 4) Create a unique txt-file (e.g: _USERSIPADRESS__.txt) which can be used to save and extract data from the random script? (fopen, fwrite and so fourth) I hope you understand what I'm trying to do Any suggestions would be highly appreciated. Thank you. Hi All, I created this simple function to generate random doubles..... Please your opinions! function GetRandomFloatNumber($min = false, $max = false, $dec_min = false, $dec_max = false) { // Seed the generator mt_srand((double)microtime()*1000000); // Set the default min and max if no parameter has been passed if ($min === false) $min = 0; if ($max === false) $max = mt_getrandmax(); if ($dec_min === false) $dec_min = 0; if ($dec_max === false) $dec_max = mt_getrandmax(); // units $units = mt_rand($min, $max); // Decimals $decimals = mt_rand($dec_min, $dec_max); // Set double $doublenumber = $units.'.'.$decimals; // Return double return $doublenumber; } Hello........ Currently i am struggling with php script....... can any one tell me or guide me how to code Automatically generating random number with in the range of 19 to 90 and the number has to change with in 24 hours time duration......... It's urgent........ Thanks in advance..... Rooban.S How can you use PHP to generate a serial number? e.g. DF34-VB89-98AP-34NQ-QQUI-23AW |