PHP - Random String
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)); } Similar TutorialsHey 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. 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? 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' 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; } ?> 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? 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 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 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 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. Hi, I am trying to make some adjustments to uploadify.php which comes with the latest version of uploadify (3.0 beta), so that it works with a session variable that stores the login username and adds it to the path for uploads. Here is uploadify.php as it currently looks: Code: [Select] <?php session_name("MyLogin"); session_start(); $targetFolder = '/songs/' . $_SESSION['name']; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $targetFile = rtrim($targetPath,'/') .'/'. $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('m4a','mp3','flac','ogg'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } } echo $targetFolder; ?> I added Code: [Select] echo $targetFolder; at the bottom so that I could make sure that the string returned was correct, and it is, i.e. '/songs/nick'. For some reason though, uploads are not going to the correct folder, i.e. the username folder, but instead are going to the parent folder 'songs'. The folder for username exists, with correct permissions, and when I manually enter Code: [Select] $targetFolder = '/songs/nick';all works fine. Which strikes me as rather strange. I have limited experience of using php, but wonder how if the correct string is returned by the session variable, the upload works differently than with the manually entered string. Any help would be much appreciated. It's the last issue with a website that was due to go live 2 days ago! Thanks, Nick Hey there, Thanks for taking the time to read my thread. My issue is that I can't think of a way to edit a XML file using PHP's XML functionality and then assign the edited contents to a string instead of saving the file. Because my issue is that I have to edit the XML file based upon a string brought from a remote location then give it back to that remote location using a string again, to be exact I am doing it via Linux command line utilizing SSH2. This is what I managed to complete on my own. function CheckIVMPConfig($ServerID) { global $Panel; if(is_numeric($ServerID) && $this->IsValidServer($ServerID)) { // We select the game server that the FTP account was created for. $Servers = mysql_query("SELECT * FROM control_servers WHERE server_id = '".mysql_real_escape_string($FTPAccount['ftp_server'])."'"); $Server = mysql_fetch_array($Servers); // Here we select the Box ID that the game server is on. $Boxs = mysql_query("SELECT * FROM control_machines WHERE machine_id = '".$Server['server_machine']."'"); $Box = mysql_fetch_array($Boxs); // Now we select the required package for the box. $Packages = mysql_query("SELECT * FROM control_packages WHERE package_id = '".$Server['server_package']."'"); $Package = mysql_fetch_array($Packages); // Retrive the file. $Config = $CProtocol->exec("cat /home/{$Server['server_id']}/{$Package['package_config']}"); $Parse = SimpleXMLElement($Config); foreach($Parse as $Entry) // loop through our books { if($Entry->port != $Server['server_port']) { // edit the value } else if($Entry->maxplayers > $Server['server_slots']) { // edit the value } } } } This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=326004.0 Hello all, I'm trying to change the end of a javascript call based on the end of the url string. The common part of all the url strings is sobi2Id=, I'm trying to do this with strstr but am having no luck. I'm new to php so my syntax knowledge is terrible! at the moment i've got Code: [Select] <?php $url = $_SERVER['REQUEST_URI']; $tag = strstr ($url, 'sobi2Id='); echo $tag; ?> but this returns an unexpected T_STRING, expecting ',' or ';' Can anyone debug this? I may well be being really silly! hey guys im trying to find a string inside a string which could be made up of different things eg... {$test}, {$test1}, {$test2} etc (but the varable inside could be called anything hence maybe using regex im not sure?) is this possible?...i hope you guys understand....thanks I have the following function, which takes a string with commas in it and attempts remove those commas. The way I have it here is that I use explode to take out the commas, which makes an array, and then iterate through that array to put a string back together without the commas. function tags_to_sort_by( $sortMeta ) { $sortByArray = explode(",", $sortMeta); $sortByCount = count($sortByArray); for ($i = 0; $i < $sortByCount; $i++) { $sortByString += $sortByArray[$i]; } return $sortByString; } What does not work is the following line: $sortByString += $sortByArray[$i]; Somehow that outputs a 0, which I don't understand. It should output something like: arrayItem1 arrayItem2 array3 etc. My question is if there either is an easier way to remove the commas from the original string or what I am doing wrong in this line: $sortByString += $sortByArray[$i]; // I am trying to concatenate each part of the array back into the string. Thanks a lot for help with this!
In PHP Version 8.0 shows error as : In previous versions of PHP it does not show any error. Please resolve the issue. Hello guys i am trying to figure out how to fwrite a string for example "Recommended Settings for Service Pack" under "Current Settings for Service Pack: 5.1.2600ServicePack3Build2600". I figure i cant use line number as an argument because the file report may be dynamic so i will need to use Current Settings as an argument. Please guide me if you have any ideas..thanks:) ! auditreport table ServicePackSetting Service Pack Requirement: Fail Current Settings for Service Pack: 5.1.2600ServicePack3Build2600 MajorAuditandAccountPolicies Maximum Password Age Requirement: Fail Current Settings for Maximum Password Age Requirement: 42 Minimum Password Length: Fail Current Settings for Minimum Password Length Requirement: 0 Ok... I had typed this post out ONCE already and when I clicked REFRESH IMAGE to get a diff captcha it ERASED MY POST LMAO this is not my night.... What I need help with is probably more simple then I can even think right now - ive been digging at this for 3 hrs now and im out of time for the night I have a DB Record storing ID's between PIPES | when the initial entry is made in DB it stores it like so |47| NOTE: the number could be different these are ID's number doesnt matter its just between Pipes When the second entry is added its added like so |47||67| say we have a total of 5 Entries |47||67||82||55||69| I need to find ID 82 in that string and it has to be between Pipes Find 82 in data between | and return that ID 82 I am putting between pipes because the ID's can be duplicate digits in different lengths so say I have 8 as my ID and down the string i have another id as 88 -- I cant possibly find the correct ID without some sort of seperation character so i used Pipes soo my end goal is the ability to search and if true or false do action if ($result == $find_id){ echo "ID is there"; }else{ echo "NOT THERE -- Adding it"; } Any help is appreciated guys Thanks SangrelX I need to know if a string exists within a string. I've tried using STRIPOS() but it returns zero or false if what I'm looking for is the first part of the string. I don't care what function I use, but I need to get a "true" when the needle string is present anywhere in the haystack string, even at location zero. Is there some way to set up the STRIPOS() statement? I've tried: if ((stripos($title, 'needle') > 0 ) if ((stripos($title, 'needle') = true ) and even if ((stripos($title, 'needle') >= 0 ) which returns true for everything, even when the needle string is NOT present. Any help appreciated. thanks, Tom |