PHP - Upload Filename Using Rand() & Insert Filname To Sql
I want to use the following code to upload images to my server (below code works great)
Code: [Select] <?php $rand = rand(1,99999999999999); $member_id = $_SESSION['SESS_MEMBER_ID']; if(isset($_FILES['uploaded']['name'])) { $target = "gallery/"; $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $target = $target . $fileName; $errors = array(); // Get the extension from the filename. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Check if the filetype is allowed. if(in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> The file {$fileName} has been uploaded<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file: <input name='uploaded' type='file' /><br />\n"; echo "<input type='submit' value='Upload' />\n"; echo "</form>\n"; //Echo Tests! echo "<br /><br />Random FileName: "; echo $rand; echo "<br />"; echo "member ID: #"; echo $member_id; } ?> i then want it to rename the files for example: "test.png" is uploaded and name changed to "92997863_321.png" (where first number is using my $rand then the "_" then second number is my $member_id) the script already got these pieces of information and also gets the file extension using the $ext code. can this be done, and can i also upload the new filename to my sql table? Similar TutorialsI have 2 sites here that does what i need them to do but i dont know how to put the 2 codes together i got it to upload all files and used rand() to give the files a # but it ends up giving them all the same # lol so they overwrite them selfs lol This site shows how to upload mltiple fiels with php. http://www.ehow.com/how_6345068_upload-multiple-files-php.html This site shows how to rename only 1 file uploaded with rand() http://php.about.com/od/advancedphp/ss/rename_upload.htm i pray this is not to hard to do and if any one gets bored after words can you show how to block a file type from being uploaded ? like php/exe types PS)i would call my self a php newbe lol and ty you for your time and help Code from http://php.about.com/od/advancedphp/ss/rename_upload.htm Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> //This function separates the extension from the rest of the file name and returns it function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //This applies the function to our file $ext = findexts ($_FILES['uploaded']['name']) ; //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. $ran = rand () ; //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended. $ran2 = $ran."."; //This assigns the subdirectory you want to save into... make sure it exists! $target = "images/"; //This combines the directory, the random file name, and the extension $target = $target . $ran2.$ext; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; } The code from http://www.ehow.com/how_6345068_upload-multiple-files-php.html Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> <input type="submit" name="submit" value="Upload"/> </form> $destpath = "upload/" ; while(list($key,$value) = each($_FILES["file"]["name"])) { if(!empty($value)){ f ($_FILES["file"]["error"][$key] > 0) { echo "Error: " . $_FILES["file"]["error"][$key] . "<br/>" ; } else { $source = $_FILES["file"]["tmp_name"][$key] ; $filename = $_FILES["file"]["name"][$key] ; move_uploaded_file($source, $destpath . $filename) ; echo "Uploaded: " . $destpath . $filename . "<br/>" ; } } } I'm experiencing a very strange issue, and I'm not 100% sure it's PHP-related, but I'd like to at least rule it out if it's not. I've setup a test page he http://www.linkboard.org/test/ Included on that page are two bookmarks files exported from a browser: one contains data-URI encoded favicons, and the other does not. Uploading both files via the above URL should work just fine in any browser (an array dump of characters should be the result). However, if you change the above URL to include the 'index.php', uploading the file with favicons in it no longer works - it results in a browser time out. If i change the name of the test page to something else, i.e. 'test.php', it will never work since I would always have to specify the page filename in the URL. So, anybody have any ideas? Could this be a server config issue? It doesn't appear to be a browser problem because I experience the exact same issue in Chrome, Firefox, and IE. Edit: Here's the code I'm using on the page: Code: [Select] <?php if (isset($_POST['submit'])) { if (is_uploaded_file($_FILES['bookmarks_file']['tmp_name'])) { $file = fopen($_FILES['bookmarks_file']['tmp_name'], "r"); if ($file != false && $_FILES['bookmarks_file']['type'] == 'text/html') { $charArray = array(); while (!feof($file)) { $charArray[] = fgetc($file); } fclose($file); var_dump($charArray); } } } ?> <h2>Test Import</h2> <p><a href="bookmarks_4_24_12-favicon.html">Bookmarks file <strong>with</strong> Favicons</a><br /> <a href="bookmarks_4_24_12.html">Bookmarks file <strong>without</strong> Favicons</a></p> <p>Upload one of the above files with this form. If successful, the program will print out file contents.</p> <form enctype="multipart/form-data" action="<?php echo $PHP_SELF; ?>" method="POST"> <input type="file" name="bookmarks_file" /><br /><br /> <button type="submit" name="submit">Submit</button> </form> Hi guys, I am wirting a script to upload an image file, but I get the error: copy() [function.copy]: Filename cannot be empty in Obviouly it has something to do with the copy() function - (copy($HTTP_POST_FILES['product_img']['tmp_name'], $path)) I think it is not copying from my temp folder or something. Can anyone help me out? Code is: Code: [Select] //IMAGE FILE $file_name = $_FILES['product_img']['name']; echo '<p>File Name:' . $file_name . '</p>'; //IMAGE UPLOAD // random 4 digit to add to file name $random_digit=rand(0000,9999); //combine random digit to file name to create new file name //use dot (.) to combile these two variables $new_image_name = $random_digit.$file_name; echo $new_image_name; //SET DESINATION FOLDER $path= "uploads/".$new_image_name; echo '<p>Path:' . $path . '</p>'; if($product_img !=none) { if(copy($HTTP_POST_FILES['product_img']['tmp_name'], $path)) { echo "Successful<BR/>"; echo "File Name :".$new_file_name."<BR/>"; echo "File Size :".$HTTP_POST_FILES['product_img']['size']."<BR/>"; echo "File Type :".$HTTP_POST_FILES['product_img']['type']."<BR/>"; } else { echo "Image upload Error<BR/>"; } } Any help would be greatly appreciated! Thanks files that upload during insert/submit form was gone , only files upload during the update remain , is the way query for update multiple files is wrong ? $targetDir1= "folder/pda-semakan/ic/"; if(isset($_FILES['ic'])){ $fileName1 = $_FILES['ic']['name']; $targetFilePath1 = $targetDir1 . $fileName1; //$main_tmp2 = $_FILES['ic']['tmp_name']; $move2 =move_uploaded_file($_FILES["ic"]["tmp_name"], $targetFilePath1); } $targetDir2= "folder/pda-semakan/sijil_lahir/"; if(isset($_FILES['sijilkelahiran'])){ $fileName2 = $_FILES['sijilkelahiran']['name']; $targetFilePath2 = $targetDir2 . $fileName2; $move3 =move_uploaded_file($_FILES["sijilkelahiran"]["tmp_name"], $targetFilePath2); } $targetDir3= "folder/pda-semakan/sijil_spm/"; if(isset($_FILES['sijilspm'])){ $fileName3 = $_FILES['sijilspm']['name']; $targetFilePath3 = $targetDir3 . $fileName3; $move4 =move_uploaded_file($_FILES["sijilspm"]["tmp_name"], $targetFilePath3); } $query1=("UPDATE semakan_dokumen set student_id='$noMatrik', email= '$stdEmail', surat_tawaran='$fileName', ic='$fileName1',sijil_lahir='$fileName2',sijil_spm= '$fileName3' where email= '$stdEmail'");
im doing smting basically wrong Code: [Select] <form action="" method="post"> <?php $x=1; $images = $_GET['images']; for( $i=0; $i<$images; $i++ ) { echo '<input name="ID" type="hidden" value="1234" /> <br> <input name="ImageURL['.$i.']" type="file" value=""/><br><br>'; } ?> <input name="submit" type="submit" /> <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_query("SET NAMES 'utf8'"); mysql_select_db("international", $con); if (isset($_POST['submit'])) for( $i=0; $i<$images; $i++ ) { $query=mysql_query("INSERT INTO images (ID,ImageURL) VALUES ('$_POST[ID]','$_POST[ImageURL]')"); exit; mysql_close($con); } ?></form> Hi all, I have an issue with an image upload script. So far the script will upload the image to the server and rename it with a random 5 digit number on the end. I then INSERT this data into a table for sourcing the image later on. the only problem is that the data in the table is the image's original name not the new one. how do I get it to change that name too? Thanks. 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 } } error_reporting (E_ALL ^ E_NOTICE); $usr = "user"; $pwd = "pword"; $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']); $SQL = " INSERT INTO mhhire "; $SQL .= " (logo) VALUES "; $SQL .= " ('$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(); } ?> Code I'm using if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Successfully uploaded image!"; if (file_exists("img/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "img/" . $_FILES["file"]["name"]); echo "<a href='img/$filename'>Your File</a>; } } } else { echo "Invalid file"; } mysql_query("INSERT INTO $tbl (body, name, subject, ip, timestamp, img) VALUES ('$body', '$name', '$subject', '$ip', '$timestamp', '$imglink')"); mysql_query("INSERT INTO total (ip, subject, name, board) VALUES ('$ip','$subject','$name','$dfg')"); echo "<font color='red'><font size='15'><strong><center>Successfully posted to /$tbl/"; //print("<meta http-equiv='REFRESH' content='0;url=index.php?board=$tbl'>"); If I have the query on the top it runs, and the upload img doesn't && vice versa Okay, so I found this code on-line that uploads images via a form, inserts them in to MySQL and displays the images on the page. It works great! Problem is, I spent a long time hacking this script to make it work with my site just to realize it did not re-size the image after it uploaded (dumb me). I have found other code that do this but I really do not want to start over at this point and my level of expertise with PHP are a step below what I need to figure this out. I am attaching the "original" code. If anyone knows how to add the necessary lines of code to make every image re-size (reduce) itself. I would very much appreciate it. Thanks <?php $con=mysql_connect("localhost", "root", "rootwdp")or die("cannot connect"); mysql_select_db("student",$con)or die("cannot select DB"); if(isset($_POST['upload'])) { $img=$_FILES["image"]["name"]; foreach($img as $key => $value) { $name=$_FILES["image"]["name"][$key] ; $tname=$_FILES["image"]["tmp_name"][$key]; $size=$_FILES["image"]["size"][$key]; $oext=getExtention($name); $ext=strtolower($oext); $base_name=getBaseName($name); if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){ if($size< 1024*1024){ if(file_exists("upload/".$name)){ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'"; $res=mysql_fetch_array(mysql_query($qry)); $id=$res['id']; $qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id"; mysql_query($qry); echo "Image '$name' updated<br />"; } else{ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');"; mysql_query($qry); echo "Image '$name' uploaded<br />"; } } else{ echo "Image size excedded.<br />File size should be less than 1Mb<br />"; } } else{ echo "Invalid file extention '.$oext'<br />"; } } } function getExtention($image_name){ return substr($image_name,strrpos($image_name,'.')+1); } function getBaseName($image_name){ return substr($image_name,0,strrpos($image_name,'.')); } ?> <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script type="text/javascript"> function addItems() { var table1 = document.getElementById('tab1'); var newrow = document.createElement("tr"); var newcol = document.createElement("td"); var input = document.createElement("input"); input.type="file"; input.name="image[]"; newcol.appendChild(input); newrow.appendChild(newcol); table1.appendChild(newrow); } function remItems() { var table1 = document.getElementById('tab1'); var lastRow = table1.rows.length; if(lastRow>=2) table1.deleteRow(lastRow-1); } </script> <style type="text/css"> <a class="tooltip" and them url href="/http.www.anyurl.com" </a> a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;} a.tooltip span {display:none; padding:2px 3px; margin-left:8px; width:150px;} </style> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <table align="center" border="0" id="tab1"> <tr> <td width="218" align="center"><input type="file" name="image[]" /></td> <td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td> <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td> </tr> </table> <table align="center" border="0" id="tab2"> <tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr> </table> </form> <table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center"> <iframe style="display:none" name="if1" id="if1"></iframe> <? $qry="select * from img where img_status='Y' order by id"; $res=mysql_query($qry); $i=0; if(mysql_num_rows($res)){ ?> <div align="center"><ul style="width:650px; border: 0px"> <? while($fetch=mysql_fetch_array($res)){ $hratio=120/$fetch['img_height']; $wratio=120/$fetch['img_width']; $ratio=($hratio < $wratio) ? $hratio : $wratio; $hth=$fetch['img_height']*$ratio; $wth=$fetch['img_width']*$ratio; ?> <li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br /> <? if($i==0) $fp=fopen("fileInfo.txt",'w'); else $fp=fopen("fileInfo.txt",'a'); fwrite($fp,"Image : ".++$i ."\r\n"); fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n"); fwrite($fp,"width X height : ".$fetch['img_width']." X ".$fetch['img_height']."\r\n"); fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n"); fwrite($fp,"____________________________________\r\n"); fclose($fp); echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />'; echo $fetch['img_width'].' X '; echo $fetch['img_height'].'<br />'; echo round($fetch['size']/1024,1) .'Kb'; ?> </li> <? }?> </ul> </div><? }?> </td></tr></table> </body> </html> i need to upload files to a different folder dependint on option in form, make thumbnails, and store title and src for image and thumb in database table dependant on category. i think i'm pretty close, but there's still something wrong. Here is my upload form : Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Photo: <input type="file" name="photo"><br> Category: <select name="cat"> <option value="weddings">Weddings</option> <option value="music">Music</option> <option value="portraits">Portraits</option></select> Title: <input type="text" name="title"><br> <input type="submit" value="Upload photo"> </form> form processed by upload.php : Code: [Select] <?php require "db.php"; //Get form info $name=$_POST['name']; $title=$_POST['title']; $category=$_POST['cat']; $pic=($_FILES['photo']['name']); //set target dir source file width height $target = $cat."/"; $src = $target . basename( $_FILES['photo']['name']); $destination = $cat."/thumbs"; $thumbsrc = $destination . basename( $_FILES['photo']['name']); $width = 200; $height = 200; header("content-type: image/jpeg"); $src_img = imagecreatefromjpeg("$src"); $srcsize = getimagesize("$dest"); $dst_img = imagecreatetruecolor($width, $height); imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $width, $height, $srcsize[0], $srcsize[1]); imagejpeg($dst_img); //Unstert into db mysql_query("INSERT INTO `$category` VALUES ('$name', 'Stitle', '$src, $thumbsrc')") ; //move photo if(move_uploaded_file($_FILES['photo']['tmp_name'], $fulltarget)) { //Ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { //not ok echo "Sorry, there was a problem uploading your file."; } ?> call a script from main page Code: [Select] <div class="gallery"> <?php include "weddings/get.php" ?> </div> <div class="gallery"> <?php include "music/get.php" ?> </div> get.php displays links Code: [Select] <?php include "db.php"; $cat = weddings; $q = "SELECT id, title, src, thumbsrc FROM $cat"; $result = $mysqli->query($q) or die(mysqli_error($mysqli)); if ($result) { echo "<ul id='photos'> \n"; while ($row = $result->fetch_object()) { $title = $row->title; $src = $row->src; $thsrc = $row->thumbsrc; $id = $row->id; echo "<a href='$src' class="lightbox" rel="$cat" title="$name - $title"><img src='$thsrc' id='$id' alt='$name' /></a>": } echo "</ul>"; } ?> I think i'm going along the right sort of path, but i'm not sure. Hello everybody, I just have a quick question. I am trying to develop a webpage for dice rolling (to use for myself when i play dnd) Now, I know a lot of the random functions is computer languages are not truly random, and thus have some areas that the value will be the result more than others. What would be a good way to try to make it as "random" as possible, or am I just over-thinking it? what am i doing wrong? I can't see it... I want to catch the rand variable but it doesn't. So I print an extra print at the bottom. So there should be two rand prints. Here's the code.
<html> <head><title></title> </head> <body> <form action='random.php' method='post'> <?php if(isset($_REQUEST['rand'])){ $rand = $_REQUEST['rand']; print $rand . "<br /><br />"; } else { print "rand: empty<br /><br />"; } $rand = rand(1,1000); print $rand."<br /><br />"; print "<input type='hidden' value='$rand' />"; ?> <input type='submit' value='scramble' /> </form> </body> </html>I forgot to tell ya that the if statement returns rand: empty. Help... I have this in my code: $dr =rand(0, 100); echo $dr; Here are the last 5 refreshes: 997 6336 6144 1110 2914 similar results when I use mt_rand()... Hi,
I basically want a function that takes a parameter which is a percentage chance of the functioning returning true.
A user can move from tier 1->10 and at tier 1 there's a 70% chance to move to tier 2, from tier 2 there's a slightly less chance to move up, and so on.
I tried with the following piece of code:
public function rollTheDice($winnerPercentage) { $number = rand(1, 100); if ($number <= $winnerPercentage) return true; return false; }The above code makes logical sense to me: 1. Pick a random number between 1 and 100. 2. If that number is less than or equal to the percentage, then we passed (example, if the random number is less than or equal to 70.. there must be a 70% chance of this?) This however does not seem to work, in fact it appears that when simulating a roll, 70% fails at the very first step (where there is a 70% chance of winning..) To actually make it to tier 10, has yet to be accomplished, so by simulating this with unlimited attempts for 120 seconds straight doesn't seem to "win". I tried (just for fun) and change the if-statement so: if ($number >= $winnerPercentage) This seems to be working quite well, as the simulator quickly reaches tier 10 this way. Any suggestions to code changes, or can someone explain why it is working way better when exchanging less than with greater than? Hey, This is my [faulty] PHP $input3 = array("BB, BB, BB, BB, BB, BB, BB, BB, BB, bb"); $rand_keys3 = array_rand($input3, 2); $BB1 = $input3[$rand_keys3[0]] . "\n"; $BB2 = $input3[$rand_keys3[1]] . "\n"; $input4 = array("HD, HD, HD, HD, HD, hd"); $rand_keys4 = array_rand($input4, 2); $HD1 = $input4[$rand_keys4[0]] . "\n"; $HD2 = $input4[$rand_keys4[1]] . "\n"; $input5 = array("DD, DD, DD, DD, DD, DD, DD, dd"); $rand_keys5 = array_rand($input5, 2); $D1 = $input5[$rand_keys5[0]] . "\n"; $D2 = $input5[$rand_keys5[1]] . "\n"; $input6 = array("CC, CC, CC, CC, CC, cc"); $rand_keys6 = array_rand($input6, 2); $C1 = $input6[$rand_keys6[0]] . "\n"; $C2 = $input6[$rand_keys6[1]] . "\n"; $input7 = array("HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, hg"); $rand_keys7 = array_rand($input7, 2); $HG1 = $input7[$rand_keys7[0]] . "\n"; $HG2 = $input7[$rand_keys7[1]] . "\n"; And this is the error I'm getting: Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 48 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 54 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 60 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 66 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 72 I've checked back over it all and looked up the function in various places to check what they say about it, but can't see which bit I'm going wrong wit! :[ If anybody has any advice as to what to do to fix it, it would be much appreciated. Cheers. Hi there, I have one question about the function rand(), What if i want to have an number between 0 and 360 Without 90 to 180 so 91,92,93,94.....180 can't be the number how can i do that? btw, I know its possible through if,while,for and so on. But is there an other way to do this? Really need a hand from someone mysql query is pretty basic. I have been ask to add a random order to this query. $query = "SELECT rd.user_id FROM {$regions_data_table} rd WHERE rd.field_id = {$regions_field_id} AND rd.value LIKE %s AND rd.user_id NOT IN (SELECT um.user_id FROM {$wpdb->base_prefix}usermeta um WHERE ((um.meta_key='wp_ul_disabled' AND um.meta_value=1) OR (um.meta_key='wp_ul_inactive' AND um.meta_value=1)) GROUP BY um.user_id)"; I have tried so many options but cannot seem to get it to work i am trying to insert order by rand(). Any help please? Hey guys, I don't know what to do. I've got a script used for gamble: $gamble_rand = rand($number_of_tickets,$gamble_chance); if($gamble_chance == $gamble_rand){ If $number_of_tickets is set by 99 and $gamble_chance is set by 100 the chance is 1:100 that the If-Clause is not true. But it seems to me that PHP is making its on "random". Independent of the values PHP is interpreting that 20 times of 100 times the correct logic is false... If $number_of_tickets is set by 1 there's no big different. Its just a little bit less, but not the chance that it has to be. Thanks for helping and Merry Christmas :-) Hi,
I'm having a bit of trouble. I want to order the same 9 results by RAND(). Currently I have them ordered by 'avg' (average views) and that's working fine, but when I add a sub query to make those 9 results scatter by random it's causing some trouble.
Code I currently have that works:
$sql = "SELECT *, views / HOUR(TIMEDIFF(NOW(), date)) as avg FROM content WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND NOW() - INTERVAL 2 HOUR AND views > 600 AND live = '0' ORDER BY avg DESC LIMIT 9"; This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=326563.0 Okay, so I'm kind of a PHP noob.
But out of context, for this site that I'm designing, it's easiest if I make a directory in the temporary folder PHP uses. In my case, /tmp/ because I am on Linux.
I want to use rand() to generate a random name for the page. But I then realized something, rand() could produce duplicates. How do I prevent PHP from trying to make the same directory at the same time? I know there are functions that will check if a file exists but I'm assuming it'll fail if that directory is currently being created, right?
How do I assure thread safety?
I willing to change my idea and not use rand(). Is there a way to get a unique key for each anonymous user on my site?
|