PHP - Random String Generation?
I'm looking for a function that creates a random string that contains random letters, numbers and symbols.
Also it needs to generate it in a way that there are no repeating characters. Any ideas? Similar TutorialsHi all, sorry cos there is no code. please how can i generate pairs (in twos, threes, fours or five) from a given set of numbers. the numbers are to be typed in the form text field and when click generate(submit button) it brings out the pair of numbers. thanks in advance my form Code: [Select] <form id="form1" name="form1" method="post" action=""> <table width="100%" border="0" cellspacing="2" cellpadding="1"> <tr> <td width="21%">Input Numbers : </td> <td width="79%"><input name="numbers" type="text" id="numbers" size="50" /></td> </tr> <tr> <td> </td> <td><input name="generate" type="submit" id="generate" value="Generate" /></td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> <tr> <td colspan="2"> </td> </tr> </table> </form> Hi, I'm having trouble generating random string with 8 characters, when I refresh I sometimes get 6 characters and sometimes 8. "-" not included as character. Wrong: 6JW-F7W Correct: (should always generate random like this) DVMF-F36V I know I'm trying to achieve this in wrong methods but it's the only way I know. Hope someone can help. function getReference() { $length = 8; $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return strtoupper(substr($string, 0, -$length/2)."-".substr($string, $length/2-1, -1)); } i have to tables... forums & subscription i would like to insert a random character string into 'forums' to be used as a subscription id. and then have the same random string to be inserted into 'subscription' Hey all, I'm looking to produce a random 10 character string like: abcABC0123 when the below method is called: <?php function randomize(){ $chars = explode(' ',(range("a","z"))) . explode(' ',(range("A","Z"))) . explode(' ',(range("0","9"))); $pass = ""; for($i = 0; $i < $len; $i += 1){ array_push($pass,$chars[rand(count($chars)-1)]); } return $pass; } var_dump(randomize(10)); ?> But the randomize method is not returning desired result. Any idea what I'm doing wrong? Thanks for response. In the PHP script I'm using, in the Upload Form the user selects an image to Upload, the Form renames it like so:
$allowedExts = array("gif", "jpeg", "jpg", "pdf", "png"); $temp = explode(".", $_FILES["file"]["name"]); $extension = strtolower( end($temp) ); if (!in_array($extension,$allowedExts)) { echo ("Error - Invalid File Name"); } $length = 20; $randomString = (time()); $thumbnail = $randomString . "." . $extension;The random string works successfully, but I'd like to add the user_id to the beginning of it and a dash, like this: user_id - So, the new file name would be something like: user_id-randomString.extension Can you please help me add that? 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 everyone Well I've started learning php yesterday and now I encountered my first problem, I looked around but I don't really know what to search for if I want my answer so here I come Code: [Select] <html> <body> <?php $names = array('Peter','Quagmire','Joe'); $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $who = rand(0,2); $who2 = $names[$who]; echo "$names[$who] is $ages[$who2] years old"; ?> </body> </html> This is the script I have, and there is the kind of script I expected: Code: [Select] <html> <body> <?php $names = array('Peter','Quagmire','Joe'); $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $who = rand('Peter','Quagmire','Joe'); echo "$who is $ages[$who] years old"; ?> </body> </html> But after some search I concluded that rand is only used for random numbers So, my question is, which function should I use to achieve my goal? Is there any randstring('string1','string2',etc) command? Tnx for your time currently using function gen_chars($length = 6) { // Available characters $chars = '0123456789abcdefghjkmnoprstvwxyz'; $Code = ''; // Generate code for ($i = 0; $i < $length; ++$i) { $Code .= substr($chars, (((int) mt_rand(0,strlen($chars))) - 1),1); } return $Code; } // Usage $var = gen_chars(12); echo $var; However ide like to know if theres a more efficient way of generating this since this is going to be using a lot. Thanks Hello everyone, I have this very short script I wrote with help from a book using arrays and the rand function. Basically it changes the images randomly on browser load or refresh. However, I am trying to add an additional, not sure what to call it, a string or another caption for each images. Instead of this being a caption, it will be a link, so a link will appear under each caption that goes to another page when it is clicked on. I tried adding another caption and adding a like to it but getting syntax error. Thanks everyone! Here is the code: Code: [Select] <?php $images = array( array('file' => 'image1', 'caption' => 'Caption 1'), array('file' => 'image2', 'caption' => 'Caption 2'), ); $i = rand(0, count($images)-1); $selectedImage = "graphics/{$images[$i]['file']}.png"; $caption = $images[$i]['caption']; ?> And here is where the images are written to the page: Code: [Select] <div id="stage"> <img src="<?php echo $selectedImage; ?>" alt="Random image" /> <p id="caption"><?php echo $caption; ?></p> </div> IC Hi guys, this is very urgent. Can anyone help me out..... I want to generate reports using php and MySQL. I have one table which includes customer_id, full_name, name_with_initials, address, contact_number and gender fields. I want to print the details of all the records of the table. It should be good if results will come on a PDF format. Thanks, Dear All, Below is a php file for my website invitacoach.com I need to issue passwords myself to members who have already paid up for my services...of which they will then be able to access the advantages of a members area which include Videos, Audios and other publications. Which part of my code am i to edit Below is the SQL and register.php code. SQL CREATE TABLE users ( userid int(25) NOT NULL auto_increment, first_name varchar(25) NOT NULL default '', last_name varchar(25) NOT NULL default '', email_address varchar(25) NOT NULL default '', username varchar(25) NOT NULL default '', password varchar(255) NOT NULL default '', info text NOT NULL, user_level enum('0','1','2','3') NOT NULL default '0', signup_date datetime NOT NULL default '0000-00-00 00:00:00', last_login datetime NOT NULL default '0000-00-00 00:00:00', activated enum('0','1') NOT NULL default '0', PRIMARY KEY (userid) ) TYPE=MyISAM COMMENT='Membership Information'; REGISTER.PHP <? include 'db.php'; // Define post fields into simple variables $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $email_address = $_POST['email_address']; $username = $_POST['username']; $info = $_POST['info']; /* Let's strip some slashes in case the user entered any escaped characters. */ $first_name = stripslashes($first_name); $last_name = stripslashes($last_name); $email_address = stripslashes($email_address); $username = stripslashes($username); $info = stripslashes($info); /* Do some error checking on the form posted fields */ if((!$first_name) || (!$last_name) || (!$email_address) || (!$username)){ echo 'You did not submit the following required information! <br />'; if(!$first_name){ echo "First Name is a required field. Please enter it below.<br />"; } if(!$last_name){ echo "Last Name is a required field. Please enter it below.<br />"; } if(!$email_address){ echo "Email Address is a required field. Please enter it below.<br />"; } if(!$username){ echo "Desired Username is a required field. Please enter it below.<br />"; } include 'join_form.html'; // Show the form again! /* End the error checking and if everything is ok, we'll move on to creating the user account */ exit(); // if the error checking has failed, we'll exit the script! } /* Let's do some checking and ensure that the user's email address or username does not exist in the database */ $sql_email_check = mysql_query("SELECT email_address FROM users WHERE email_address='$email_address'"); $sql_username_check = mysql_query("SELECT username FROM users WHERE username='$username'"); $email_check = mysql_num_rows($sql_email_check); $username_check = mysql_num_rows($sql_username_check); if(($email_check > 0) || ($username_check > 0)){ echo "Please fix the following errors: <br />"; if($email_check > 0){ echo "<strong>Your email address has already been used by another member in our database. Please submit a different Email address!<br />"; unset($email_address); } if($username_check > 0){ echo "The username you have selected has already been used by another member in our database. Please choose a different Username!<br />"; unset($username); } include 'join_form.html'; // Show the form again! exit(); // exit the script so that we do not create this account! } /* Everything has passed both error checks that we have done. It's time to create the account! */ /* Random Password generator. http://www.phpfreaks.com/quickcode/Random_Password_Generator/56.php We'll generate a random password for the user and encrypt it, email it and then enter it into the db. */ function makeRandomPassword() { $salt = "abchefghjkmnpqrstuvwxyz0123456789"; srand((double)microtime()*1000000); $i = 0; while ($i <= 7) { $num = rand() % 33; $tmp = substr($salt, $num, 1); $pass = $pass . $tmp; $i++; } return $pass; } $random_password = makeRandomPassword(); $db_password = md5($random_password); // Enter info into the Database. $info2 = htmlspecialchars($info); $sql = mysql_query("INSERT INTO users (first_name, last_name, email_address, username, password, info, signup_date) VALUES('$first_name', '$last_name', '$email_address', '$username', '$db_password', '$info2', now())") or die (mysql_error()); if(!$sql){ echo 'There has been an error creating your account. Please contact the webmaster.'; } else { $userid = mysql_insert_id(); // Let's mail the user! $subject = "Your Membership at invitacoach.com!"; $message = "Dear $first_name, Thank you for registering at our website, http://www.invitacoach.com You are two steps away from logging in and accessing our exclusive members area. To activate your membership, please click he http://www.invitacoach.com/test/activate.php?id=$userid&code=$db_password Once you activate your membership, you will be able to login with the following information: Username: $username Password: $random_password Thanks! Invita Coach Hi i am using a script to upload an image and resize it twice first to create the large image and then again to create a thumbnail. The large image is being created fine and is uploading ok. I'm using the following code to then make the thumbnail but it does not appear to be working ( well nothing is in the thumbnail image folder i expect it to be anyways) can anyone see anything obvious that i am doing wrong ? Many Thanks /////////////////////////// Create a Thumbnail of the Image //////////////////////////////////// list($width, $height) = getimagesize($upload_image); // this is the large image which has apready been uploaded $ratio = $height/$width; if($ratio >= '1') // portret { $ht_tmb = 150; $br_tmb = 150/$ratio; } else { // landscape $ht_tmb = 150*$ratio; $br_tmb = 150; } // create thumb $source = imagecreatefromjpeg($upload_image); // The large image already uploaded //--- resize uploaded file $resize = imagecreatetruecolor($br_tmb, $ht_tmb); imagecopyresized($resize, $source, 0, 0, 0, 0, $br_tmb, $ht_tmb, $width, $height); imagejpeg($resize, "gallery_images/small/" .$filenamefd); $image = imagecreatefromjpeg("gallery_images/small/" .$filenamefd); imagejpeg($image, "gallery_images/small/" . $filenamefd); // end of making thumb ///////////////////////////////////////////////////////////////////////////////////////////////// I have set this up with a form on another page so that they can generate a runescape stat signature, although there is something wrong, if they do not select a font it comes up with an error. Here is the Code: Code: [Select] <?php header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); $user = ""; $img = ""; $fnt = ""; if(isset($_GET['user'])) { if(!empty($_GET['user'])) { $user = $_GET['user']; } } if(isset($_GET['img'])) { if(!empty($_GET['img'])) { $img = $_GET['img']; } else{$img='blue';} } else{$img='blue';} if(isset($_GET['fnt'])) { if(!empty($_GET['fnt'])) { $fnt = $_GET['fnt']; } else{$fnt='arial';} } else{$img='blue';} if(isset($_POST['user'],$_POST['img'],$_POST['fnt'])) { if(!empty($_POST['user'])) { $user=$_POST['user']; } if(!empty($_POST['img'])) { $img = $_POST['img']; } if(!empty($_POST['fnt'])) { $fnt=$_POST['fnt']; } } //Skill Grabs $order = array("Overall", "Attack", "Defence", "Strength", "Hitpoints", "Ranged", "Prayer", "Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecraft", "Hunter", "Construction", "Summoning", "Dungeoneering"); $get = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=$user"); $get = explode("\n", $get); $i = 0; foreach ($order as $key => $value) { $value = strtolower($value); $temp = explode(",", $get[$i]); $temp = array("rank" => $temp[0], "level" => $temp[1], "exp" => $temp[2]); $stats[$value] = $temp; $eval = "\$$value = array(\$temp[\"rank\"], \$temp[\"level\"], \$temp[\"exp\"]);"; eval($eval); $i++; } //End Skill Grabs $image = imagecreatefrompng("http://slay2day.x10.mx/highscores/signatures/".$img.".png"); $font = "/fonts/".$fnt.".ttf"; $color = imagecolorallocate($image, 255,255,255); ImageTTFText ($image, "7", 0, 280, 10, $color, "/fonts/arial.ttf","Slay2day"); ImageTTFText ($image, "12", 0, 240, 55, $color, $font,$user); if(is_numeric($overall[0])) { if($overall[0]==-1) { ImageTTFText($image, "11", 0, 230, 105, $color, $font,"2000000+"); } else { ImageTTFText($image, "11", 0, 240, 105, $color, $font,$overall[0]); } } else { ImageTTFText($image, "11", 0, 230, 105, $color, $font,"2000000+"); } ImageTTFText ($image, "10", 0, 27, 20, $color, $font,$attack[1]); ImageTTFText ($image, "10", 0, 27, 42, $color, $font,$strength[1]); ImageTTFText ($image, "10", 0, 27, 64, $color, $font,$defence[1]); ImageTTFText ($image, "10", 0, 27, 88, $color, $font,$hitpoints[1]); ImageTTFText ($image, "10", 0, 27, 114, $color,$font,$ranged[1]); ImageTTFText ($image, "10", 0, 70, 20, $color, $font,$prayer[1]); ImageTTFText ($image, "10", 0, 70, 42, $color, $font,$magic[1]); ImageTTFText ($image, "10", 0, 70, 64, $color, $font,$cooking[1]); ImageTTFText ($image, "10", 0, 70, 88, $color, $font,$woodcutting[1]); ImageTTFText ($image, "10", 0, 70, 114, $color,$font,$fletching[1]); ImageTTFText ($image, "10", 0, 117, 20, $color, $font,$fishing[1]); ImageTTFText ($image, "10", 0, 117, 42, $color, $font,$firemaking[1]); ImageTTFText ($image, "10", 0, 117, 64, $color, $font,$crafting[1]); ImageTTFText ($image, "10", 0, 117, 88, $color, $font,$smithing[1]); ImageTTFText ($image, "10", 0, 117, 114, $color,$font,$mining[1]); ImageTTFText ($image, "10", 0, 162, 20, $color, $font,$herblore[1]); ImageTTFText ($image, "10", 0, 162, 42, $color, $font,$agility[1]); ImageTTFText ($image, "10", 0, 162, 64, $color, $font,$thieving[1]); ImageTTFText ($image, "10", 0, 162, 88, $color, $font,$slayer[1]); ImageTTFText ($image, "10", 0, 162, 114, $color,$font,$farming[1]); ImageTTFText ($image, "10", 0, 212, 20, $color, $font,$runecraft[1]); ImageTTFText ($image, "10", 0, 212, 42, $color, $font,$construction[1]); ImageTTFText ($image, "10", 0, 212, 64, $color, $font,$hunter[1]); ImageTTFText ($image, "10", 0, 212, 88, $color, $font,$summoning[1]); ImageTTFText ($image, "10", 0, 212, 114, $color,$font,$dungeoneering[1]); header("Content-type: image/png"); imagepng($image); imagedestroy($image); //Logging $url = getenv("HTTP_REFERER"); // connect to the database include('connect-db.php'); //variables date_default_timezone_set('Pacific/Auckland'); $datepickerbox = $_POST['datepickerbox']; $datepickerbox = date("Y-m-d H:i:s", time($datepickerbox)); echo $datepickerbox; // save the data to the database mysql_query("INSERT signature SET user='$user', img='$img', time='$datepickerbox', url='$url', font='$fnt'") or die(mysql_error()); //End Logging ?> if they do not have a font i get: Code: [Select] Warning: imagettftext() [function.imagettftext]: Could not find/open font in /home/slay2day/public_html/highscores/signatures/signature.php on line 130 but of they dont choose a font i want it to use arial... Hello everyone, I am interested in creating a site with similar capabilities to this one: http://www.inkpixi.com/item/Classic+University/A223/295/item.html On this site, enter your name name and hit "Preview". The artwork is created using your name as a variable and other parameters to define how the artwork looks. I have a bunch of variables and I want to generate images (dynamically) using these variables. Any ideas or suggestions on how they do this on InkPixi.com? Thank you in advance, Tim I have this little snippet of code that runs when a user updates their password: fetch_user_salt_new(): Code: [Select] function fetch_user_salt_new($length = 5) { $salt_a = ''; for ($i = 0; $i < $length; $i++) { $salt_a .= chr(vbrand(33, 126)); } return $salt_a; } Code: [Select] $salt = fetch_user_salt_new(); $salt_processed = mysql_real_escape_string($salt); Now, occasionally when a user changes their password (or anything that inserts the salt into the database, such as registration), the salt length stored in the database becomes 6 or 7 instead of 5. As in, 99% of salts are only 5 digits long, but some salts are longer... The longer salts normally have odd components, such as \', \", or \\ leading to salts increasing by 1 or 2 digits in length. My idea is that mysql_real_escape_string() is putting a \ in front of quotes which is not what I intended when adding that piece of code in. By adding mysql_real_escape_string() in, I intended for quotes (' or ") to not be factors affecting the Query. Prior to instituting mysql_real_escape_string(), a ' or " would close the query and mess up the insertion of the salt. (Original Topic: http://www.phpfreaks.com/forums/index.php?topic=356368.0 ) It seemed to work but not doesn't Any help is very appreciated, Mark Hi guys i am facing a problem in my php code and i dont know how to figure out so i search on google and i have started searching for a php forums and i found this community. The problem is i made three pages in page1 i create a simple form with one text field and add two buttons one name is "add more fields" and one is "submit" when i click on add more fields button a text field is generate by using javascript functions. Let say i create 3 fields and enter names and submit the form by having form action "page2" In page2 i just simply get all values i entered in fields and print them on screen and also there is a link of "page3" that says edit your information and the session is start. In "page3" i made changes to values and submit them again again. Its all working. But i i also want "add more fields" button in page3 so that i can generate more fields also on page3 and this this the point where i stucked and i didn't figure out how can i do this task to create add more fields button. Can you guys help me in this regard thanks. Page1 Code: Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script> function addonemore() { var tot = document.getElementById('count').value; tot = parseInt(tot)+1; document.getElementById('count').value=tot; var newhtml = 'student '+tot+' <input type="text" name="val'+tot+'" id="val'+tot+'" /><br/>'; document.getElementById('mydiv').innerHTML += newhtml; } </script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form action="page2.php" method="post" enctype="application/x-www-form-urlencoded"> student 1 <input type="text" name="val1" id="val1" /> <div id="mydiv"></div> <input type="button" id="addnew" name="addnew" value="Add more" onclick="addonemore()" /> <input type="submit" id="submit" name="submit" value="submit" /> <input type="hidden" name="count" id="count" value="1" /> </form> </body> </html> Page2 Code: Code: [Select] <?php session_start(); $_SESSION['count'] = $_REQUEST['count']; for($i=1;$i<=($_REQUEST['count']);$i++) { $html .= 'student '.$i.':'.$_REQUEST['val'.$i].'<br/>'; $_SESSION['val'.$i] = $_REQUEST['val'.$i]; } echo $html; echo "<br/><a href='page3.php'>click here to edit</a>"; ?> Page3 Code: Code: [Select] <html> <head> <script> function addonemore() { var tot = document.getElementById('count').value; tot = parseInt(tot)+1; document.getElementById('count').value=tot; var newhtml = 'student '+tot+' <input type="text" name="val'+tot+'" id="val'+tot+'" /><br/>'; document.getElementById('mydiv').innerHTML += newhtml; } </script> </head> <body> <?php session_start(); $html = '<form action="page2.php" method="post" enctype="application/x-www-form-urlencoded">'; for($i=1;$i<=($_SESSION['count']);$i++) { $html .= 'student '.$i.':<input type="text" name="val'.$i.'" id="val'.$i.'" value="'.$_SESSION['val'.$i].'" />'; } $html .='<input type="submit" id="submit" name="submit" value="submit" /><input type="hidden" name="count" id="count" value="'.$_SESSION['count'].'" /></form>'; echo $html; ?> <?php $html = '<form action="" method="post" enctype="application/x-www-form-urlencoded">'; $html .= '<input type="button" id="addnew" name="addnew" value="Add more" onclick="addonemore()" /></form>' ?> </body> </html> Well, I have been tryna figure this out for days but it wont seem to work. The base image appears fine but it wont write the text or the avatar on it. Code: [Select] <?php //Do Not Cache header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); //Getting Variables $user = "Dusaro"; $rank = "Administrator"; $a = "0"; if(isset($_GET['a'])) { if(!empty($_GET['a'])) { $a = $_GET['a']; } } if(isset($_GET['u'])) { if(!empty($_GET['u'])) { $user = $_GET['u']; } } if(isset($_GET['r'])) { if(!empty($_GET['r'])) { $rnk = $_GET['r']; } else{$rnk='Administrator';} } else{$rnk='Administrator';} if(isset($_POST['u'],$_POST['r'],$_POST['a'])) { if(!empty($_POST['u'])) { $user=$_POST['u']; } if(!empty($_POST['r'])) { $rnk = $_POST['r']; } if(!empty($_POST['a'])) { $a = $_POST['a']; } } //Setting up Image $image = imagecreatefrompng("base.png"); $avatar = imagecreatefrompng($a.".png"); $font = "US101.TTF"; imagecopymerge($image, $avatar, 0, 0, 0, 0, 100, 100, 100); $color = imagecolorallocate($image, 0,0,0); ImageTTFText ($image, "15", 0, 230, 0, $color, $font,$user); ImageTTFText ($image, "14", 0, 257, 96, $color,$font,$rnk); //Displaying Image header("Content-type: image/png"); imagepng($image); imagedestroy($image); imagedestroy($avatar); ?> can any1 help? I'm praying there's a function somewhere out there that: generates a html form based on the fields of a particular table within a DB (namely mySQL) generates the appropriate form input based on the fields type or notes (ie. for field: avatar_img, it knows to generate a file input) uses the POST method to submit generates and submits SQL insert query to database In addition to that, a similar function that generates a form that allows the editing of records. It doesn't take too long to write these each time myself, but if there's a function that you provide the formname, database driver, table name, whether your form is to insert or edit, that would be quite nifty i think. ie. generateForm(addUser, mySQL, tUsers, insert) Seen any such thing? Many thanks. |