PHP - Unique Rand() Directory Names In Temp Folder
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?
Similar TutorialsCode: [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><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> </head> <body> <?php $hostname='xxx'; $username='xxx'; $password='xxx'; $dbname='xxx; $usertable=xxx; $myconn=mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.'); if ((($_FILES["file"]["type"] =="image/gif") || ($_FILES["file"]["type"] =="image/jpeg") || ($_FILES["file"]["type"] == "image/png")) && ($_FILES["file"]["size"]< 200000)) { if ($_FILES["file"]["error"] >0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br/>"; } else { if (file_exists("uploads/" . $_FILES["file"]["name"])) { echo "File already exists. Choose another name."; } else { move_uploaded_file($_FILES["file"]["tmp_name"],"uploads/" . $_FILES["file"]["name"]); } } } else { echo "Invalid file"; } $path="uploads/" . $_FILES["file"]["name"]; $desc=$_POST["desc"]; if (!myconn) { die ('Could not connect: ' . $mysql_error()); } $db_selected=mysql_select_db('xxx',$myconn); if (!$db_selected) { die ('Can\'t use xxxx : ' . mysql_error()); } mysql_query("INSERT INTO partners (desc,photopath,state) VALUES ('$desc','$path','$state')"); mysql_close($myconn); ?> </body> </html> This topic has been moved to PHP Installation & Configuration. http://www.phpfreaks.com/forums/index.php?topic=343981.0 I have data similar to below. I am doing a MySQL query and doing a JOIN based on instructor name. I am echoing classes and linking the instructor name to another page with their BIO. All is working great, however I want to use the ID's for something else. How do I differentiate the ID between the Instructors table and the Classes Table without changing the column name in the database?
For instance, I want to echo the Instructor ID and then echo the Classes ID, but they are both the same column name in the database and since they are joined, how will that work?
Instructors:
ID | Instructor | Title | Bio |
1 | Bob Smith | Chef | bob smith is a chef with... |
2 | Jane Doe | Professor | Jane doe is an instructor that... |
Classes:
ID | Instructor | Class Title | Class Description |
4 | Bob Smith | Baking | this is a baking class where you learn.... |
5 | Jane Doe | Food Safety | Food safety is very important... |
How do I get directory names to display with spaces. My script sticks them into arrays just fine, but when trying to echo from a checkbox selection, it only displays the first word. How would I fix this? I want to remove the file extension - I have done that.
I want to remove the trailing slash. - I have done that
But I cannot for the life of me get the the regular page to display instead of the folder which show a tree of files within it.
site.com/website-tips.php site.com/website-tips/increase speed.php The extension drops off and the trailing slash too but when I navgate back through the vreadcrumb to website-tips (without php in html code) it gives me the folder and shows the file tree (files within website tips folder) How would I solve this? right now if I access the website-tips.php file, it shows the directory and its interior pages Pls hlp out. Hello I have a problem. I have been trying to copy my music folders structure but not copying the mp3s; instead using the file names as a file name for a .txt file and inserting the URL to the file in the .txt file. Eg. E:\My Music folder 1 folder 1.1 file.mp3 folder 2 folder 3 to G:\My Music folder 1 folder 1.1 file.txt folder 2 folder 3 and inside "file.txt" would be one line saying "http://www.xxx.com/my_music/file.mp3 Hello All, I have a contact directory database. It has all the employees of my company (name, phone, email, department, building, etc). Say on one page I have the Marketing Department, and I want to say: "The Marketing Department Director is ________" How would I assign that value from the database? Do I want to put in a unique "keyword" field in the database, but then how would I store all the values automatically on the page? I see pages where I would want to list the Marketing Director, and his secretary, then another page with the Sales Director, and his secretary, etc.... all with being able to change the values in the database, and it changing across all the pages instantly. Do I need to say on every page "select * from database where keyword = marketingdirector" and then store that result as a variable? It seems unpractical to repeat that a few times for each different person I want to list. Is there a better way to do this then I'm thinking? Thanks all! I have a PHP script that reads the image files in a folder and displays them for viewing. When originally tested with three images, it seemed to be displaying them in alphabetical order by name (as desired). Now, with more image files added, it is displaying the pictures in a seemingly random order. Can I use a SORT command similar to the method for organizing data from a database in my script (to organize the files by name)? if ($d = opendir("uploads")) { while ($file = readdir($d)) { if ($file != "." && $file != ".." ) // if( is_file($file) ) { $files[] = $file; } } closedir($d); }if ($file != "." && $file != ".." $file != ???????? ) just a bit stuck here I have been looking around and have not been able to find any useful information on this. I am trying to transfer files from a folder in the directory to a table in a database. Eventually they will be images but for right now I am just trying to get text files to transfer. Any help/code/ideas would be a lot of help. This is going to be triggered a button on a page by the way. I've tried this code and a few others, but it only displays 0. I'd like the simplest working way to display the number of files in a directory. Thanks for the help! $directory = "../images/team/harry/"; $filecount = count(glob("" . $directory . "*.*")); echo $filecount; I have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp. I have added another column called `'unique_code' (varchar(64), utf8_unicode_ci)`. What I would very much appreciate assistance with is; a) Generating a 5 digit alphanumeric code, ie: 5ABH6 b) Check all rows the 'unique_code' column to ensure it is unique, otherwise re-generate and check again c) Insert the uniquely generated 5 digit alphanumeric code into `'unique_code'` column, corresponding to the email address just entered. d) display the code on screen. What code must I put and where? **My current php is as follows:** Code: [Select] require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('You are already on the notification list.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } My Php Buddies, I have mysql tbl columns these:
id: Now, I want to display their row data by excluded a few columns. Want to exclude these columns: date_&_time account_activation_code account_activation_status id_verification_video_file_url password
So, the User's (eg. your's) homepage inside his account should display labels like these where labels match the column names but the underscores are removed and each words' first chars CAPITALISED:
Id: 1
For your convenience only PART 1 works. Need help on Part 2 My attempted code:
PART 1 <?php // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Query to get columns from table $query = $conn->query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'members' AND TABLE_NAME = 'users'"); while($row = $query->fetch_assoc()){ $result[] = $row; } // Array of all column names $columnArr = array_column($result, 'COLUMN_NAME'); foreach ($columnArr as $value) { echo "<b>$value</b>: ";?><br><?php } ?> PART 2 <?php //Display User Account Details echo "<h3>User: <a href=\"user.php?user=$user\">$user</a> Details</h3>";?><br> <?php $excluded_columns = array("date_&_time","account_activation_code","account_activation_status","id_verification_video_file_url","password"); foreach ($excluded_columns as $value2) { echo "Excluded Column: <b>$value2</b><br>"; } foreach ($columnArr as $value) { if($value != "$value2") { $label = str_replace("_"," ","$value"); $label = ucwords("$label"); //echo "<b>$label</b>: "; echo "$_SESSION[$value]";?><br><?php echo "<b>$label</b>: "; echo "${$value}";?><br><?php } } ?> PROBLEM: Columns from the excluded list still get displayed. Edited November 19, 2018 by phpsaneI got this script: But it give me error, file_get_contents cannot open stream. I need to add the FTP connection with user/pass paramaters. then look in set http url, to get the file contents(images) and transfer to ftp server location. Can Anyone take alook and tell me if I am going down the right path and how to get there. Please Code: [Select] function postToHost($host, $port, $path, $postdata = array(), $filedata = array()) { $data = ""; $boundary = "---------------------".substr(md5(rand(0,32000)),0,10); $fp = fsockopen($host, $port); fputs($fp, "POST $path HTTP/1.0\n"); fputs($fp, "Host: $host\n"); fputs($fp, "Content-type: multipart/form-data; boundary=".$boundary."\n"); // Ab dieser Stelle sammeln wir erstmal alle Daten in einem String // Sammeln der POST Daten foreach($postdata as $key => $val){ $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n"; } // Sammeln der FILE Daten if($filedata) { $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$filedata['name']."\"; filename=\"".$filedata['name']."\"\n"; $data .= "Content-Type: ".$filedata['type']."\n"; $data .= "Content-Transfer-Encoding: binary\n\n"; $data .= $filedata['data']."\n"; $data .= "--$boundary--\n"; } // Senden aller Informationen fputs($fp, "Content-length: ".strlen($data)."\n\n"); fputs($fp, $data); // Auslesen der Antwort while(!feof($fp)) { $res .= fread($fp, 1); } fclose($fp); return $res; } $postdata = array('var1'=>'today', 'var2'=>'yesterday'); $filedata = array( 'type' => 'image/png', 'data' => file_get_contents('http://xxx/tdr-images/images/mapping/dynamic/deals/spot_map') ); echo '<pre>'.postToHost ("localhost", 80, "/test3.php", $postdata, $filedata).'</pre>'; 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? I am trying to split a simple string from my db it is in the format #/# 1/5 2/5 3/3 4/2 etc... I have the following: Code: [Select] echo $value.'<BR>'; $temp=explode('/',$value['field']); print_r($temp); echo '<br>'; when I execute the above (it's in a for loop) I get the following output 1/5 Array ( => 1 ) 2/5 Array ( => 2 ) 3/3 Array ( => 3 ) 4/2 Array ( => 4 ) I am expecting 1/5 Array ( => 1 [1] => 5) for the first entry and so on down the line showing both values after the explode. I set up functionality for a client that got moved to their server after I wrote and tested the functionality. It does not work on their server and I am trying to trouble shoot the problem as I do not have ftp access to the server.
I believe that I have narrowed it down to either I do not know how to access the temp files on their server, Windows IIS, OR the security on the server is not allowing me to upload to the temp files.
Here is the form used to upload to the server.
<form enctype="multipart/form-data" action="#" method="post" > <input type="hidden" name="upload_csv" value="TRUE" /> <p><label for="userfile">Upload CSV:</label> <input type="hidden" name="MAX_FILE_SIZE" value="45000000" /> <input type="file" id="userfile" name="userfile" title="userfile" value="" /></p> <p><input type="submit" name="upload_csv" value="Upload CSV" /></p> </form> Here is the test code: <?php $csvfile = $_FILES['userfile']['tmp_name']; $size = $_FILES['userfile']['size']; if($_POST['upload_csv']){ //---------------------------------validation code here if($problem){ echo '<div class="error">Did not pass validation</div>'; include("upload_csv.inc.php"); }else{ if (($handle = fopen($csvfile, "r")) !== FALSE) { //--------------------------------------------------------------this is where the code that imports the data from the csv and to the database goes echo '<div class="message"><p>CSV has been opened!</p></div>'; }elseif(!$csvfile){ echo '<div class="error">Problem #1</div>'; }else{ echo '<div class="error">Problem #2</div>'; } } }else{ include("upload_csv.inc.php"); } ?> This code generated the error message: Problem #2. One more bit of information: the permissions on the server is set so that nothing can be uploaded by an external script. I do not know much about servers, but it seems to me that because the security is so tight on the server, the security is the reason that this does not work...??? I appreciate help with this. I just am not knowledgeable on how the $_FILES['userfile']['tmp_name'] code actually works? From the beginning, the user accesses my website and uploads an image. Currently I'm using SimpleImage.php available at http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php to resize uploaded pictures. I create two copies, a regular size and a thumbnail size. Then I transfer the converted files through FTP to my storage server. The regular size works great, but the thumbnail transfers as a blank file. I don't want to save the files on the non-storage server at all, so I'm trying to work with temporary files. include('./SimpleImage.php'); // A few variables $file_name = basename($_FILES['photo1']['name']); $random_digit=mt_rand(111111111,2147483647); // New file name $new_file_name = $userInfo['id'].'_'.$random_digit.$random_digit.'_'.substr($file_name, -5); // Paths to temporary files $target_path = $_FILES['photo1']['tmp_name']; $thumb_path = tmpfile(); // Start SimpleImage and load temp file $simImage = new SimpleImage(); $simImage->load($target_path); // Get the temp image dimensions list($width, $height) = getimagesize($target_path); // Resize the file if it's too tall if ($height > $var['maxPhotoHeight']) { $simImage->resizeToHeight($var['maxPhotoHeight']); $simImage->save($target_path); } // Get the newly resized image dimensions list($width, $height) = getimagesize($target_path); // Resize the image if it's too wide if ($width > $var['maxPhotoWidth']) { $simImage->resizeToWidth($var['maxPhotoWidth']); $simImage->save($target_path); } // Resize for thumbnail width $simImage->resizeToWidth($var['thumbWidth']); $simImage->save($thumb_path); // Get thumbnail dimensions list($width, $height) = getimagesize($thumb_path); // Resize the thumbnail if it's too tall if ($height > $var['thumbHeight']) { $simImage->resizeToHeight($var['thumbHeight']); $simImage->save($thumb_path); } // Was told this was important, but I've tried with and without it and got the same result fseek($thumb_path,0); // Perform File Transfer ftpTransfer($target_path, "$new_file_name"); ftpTransfer($thumb_path, "thumbs/$new_file_name"); // My Simple FTP Transfer Function: function ftpTransfer($source, $name) { global $ftp; $ftpMeta = "ftp://" . $ftp['user_name'] . ":" . $ftp['user_pass'] . "@" . $ftp['server'] . $ftp['dir'] . $name; $ftpData = file_get_contents($source); file_put_contents($ftpMeta, $ftpData); } Like I said, the regular sized image works great!! the thumbnail file is only created on the storage server but it has a 0kb file size. I'm sure it has to do with me working with a temporary file. tmpfile() claims to remove the file after it's closed, so maybe by using the Save feature in SimpleImage, it's closing the file and then the server automatically removes the temporary file? SimpleImage has a feature where I can write the image output [possibly to a file] using $simImage->output() for the data. If that helps with a solution? I don't know. I know it might be complicated, but any help is appreciated! I'm trying to figure out how to create a temporary table of a query join, so I can paginate the results. I kind of made half of this up as i was going along - which is dangerous for a beginner like me. I'm getting this error, and no results on the page: Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource on line 179 also, is there a way to combine the two queries (create temp and insert from/into) Code: [Select] $sql2 = "CREATE TEMPORARY TABLE temp_search (plant_id INT PRIMARY KEY AUTO_INCREMENT, scientific_name VARCHAR(75), common_name VARCHAR(75), leaf_shape VARCHAR(75))"; $sqlx = "SELECT descriptors.leaf_shape ,plantae.scientific_name, plantae.common_name FROM descriptors INNER JOIN plantae ON (descriptors.plant_id = plantae.plant_name) WHERE descriptors.leaf_shape LIKE 'auriculate' AND descriptors.leaf_venation LIKE '%$select3%' AND descriptors.leaf_margin LIKE '%$select4%' INTO temp_search (leaf_shape, scientific_name, common_name)"; $sql = "SELECT * FROM temp_search ORDER BY scientific_name ASC LIMIT $start, $limit"; $result = mysql_query($sql); while($row = mysql_fetch_array($result)) { echo $row['scientific_name'] . $row['common_name'] . $row['leaf_shape'] ; } 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()... |