PHP - Avoiding Duplicate File Names
I've got a script where the client can upload pictures. The pictures are then resized, thumbnailed, and added to the database. In the process I'm trying to search the database for a duplicate file name and create a new name if necessary:
Code: [Select] $userfile = 'userfile' . $i; $tmpLoc = $_FILES[$userfile]['tmp_name']; $name = $_FILES[$userfile]['name']; $error = $_FILES[$userfile]['error']; $type = $_FILES[$userfile]['type']; $temp = 'album' . $i; $album = $_POST[$temp]; if($error > 0) { echo "Error on $name: "; switch ($error) { case 1: echo "File exceeded upload_max_filesize"; break; case 2: echo "File exceeded max_file_size"; break; case 3: echo 'File only partially uploaded'; break; case 4: echo 'No file uploaded'; break; } echo "</div>"; exit; } // Check for name duplicates and deal with $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if($result) $dup = true; while($dup) { echo "Duplicate file name $name <br />"; $ext; if($type == 'image/gif') $ext = '.gif'; else if($type == 'image/jpeg') $ext = '.jpg'; else if($type == 'image/png') $ext = '.png'; else die("Error: Unsupported file type"); $x = 0; $name = $x . $ext; echo "Checking $name <br />"; $query = "SELECT * FROM pictures WHERE src = $name"; $result = mysql_query($query); if(!$result) { $dup = false; echo "File successfully renamed to $name to avoid duplicate <br />"; } $x++; } I don't get any errors of any sort, it just never enters the loop Similar TutorialsHi all, This is my very first post here, so I will try and make it count Very recently I have been working with php and I found this simple little script that allows users to upload files. I tweaked some things to only make it upload .doc files but now I have a slight problem. Every time someone uploads a word file with the same name, it gets replaced. I tried looking for other examples here on the forum, but was unable to apply it to my own script. It would be a big help if someone could provide a simple add-on to this existing script. Thanks in advance. Script: <? $locatie="upload/"; $toegestaan = "doc"; $max_size = 1000000; set_time_limit(0); if(isset($_POST['upload'])) { if(is_uploaded_file($_FILES['bestand']['tmp_name'])) { $extensie_bestand = pathinfo($_FILES['bestand']['name']); $extensie_bestand = $extensie_bestand[extension]; $extensies_toegestaan = explode(", ", $toegestaan); for($i = 0; $i < count($extensies_toegestaan); $i++) { if($extensies_toegestaan[$i] == "$extensie_bestand") { $ok = 1; } } if($ok == 1) { if($_FILES['bestand']['size']>$max_size) { echo "Het bestand is te groot, de maximale grootte is: <b>$max_size</b>"; exit; } if(!move_uploaded_file($_FILES['bestand']['tmp_name'], $locatie.$_FILES['bestand']['name'])) { echo "het bestand kan niet worden verplaatst"; exit; } echo "Het bestand ".$_FILES['bestand']['name']." is geupload<br> <a href='".$locatie."".$_FILES['bestand']['name']."' </a>"; } else { echo "Verkeerde extentie, de toegestane extensies zijn: <b>$toegestaan</b>"; } } else { echo "Het uploaden is mislukt, probeer het opnieuw"; } } ?> <title>test tittle</title> <style type="text/css"> <!-- body { margin-top: 0px; } --> </style></head> <body> <table width="1216" height="1191" border="0" cellpadding="0" cellspacing="0" background="back"> <tr> <td height="317" colspan="2"> </td> </tr> <tr> <td height="381"> </td> <td><p> </p> <form method="post" action="<?=$_SERVER['PHP_SELF']?>" enctype="multipart/form-data"> <table width="398" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="180"> </td> <td width="218"><input type="file" name="bestand" /> <input type="submit" name="upload" value="uploaden" /></td> </tr> <tr> <td> </td> <td> </td> </tr> </table> </form></td> </tr> <tr> <td width="420"> </td> <td width="796"> </td> </tr> </table> I have the following code:
$fp = fopen(“path_to_file”, ‘a’); flock($fp, LOCK_EX); fwrite($fp, $string); flock($fp, LOCK_UN); fclose($fp);If I try to lock the file in two different places at the same time, this will cause a race condition. How can I prevent this? I know in Java, for example, it has a concurrent library which contains reentrant lock, which basically tries to get the lock and if can't waits. What can I do in PHP? I was wondering how I would go about doing a sorting of a new element being added on the page. This element would have to be alphabetically sorted into the existing elements onto the page. For example: I am making a file manager, so when a user creates a new file, it would be sorted into the already existing files and displayed in the spot that it should.
All necessary details would be provided by PHP, so I would only need help with the JavaScript part.
Honestly, I have no clue how I would get around to doing that. I was thinking earlier that it would involve looping through each class of file_name and getting the text() value. Then add all of the values into an array and sorting it somehow. Then it would be getting the <tr> of which file_name is before it, and then append under it somehow.
I'm not asking for any free code, but I was wondering which (JavaScript/JQuery) functions I would be looking for. I was also wondering if the idea I had would be beneficial or not, or if there were any other ways. Here is how the files are displayed as is:
<?php // There may be undefined variables, this is only part of it $return = '<table id="manager" class="table table-bordered"> <thead> <tr class="table_header"> <th><input id="select" type="checkbox"></th> <th>Name</th> <th>Size</th> <th>Last Modified</th> <th>Type</th> <th>Permissions</th> <th></th> </tr> </thead> <tbody>'; $path = $_SERVER['DOCUMENT_ROOT']; // Scan the directory and remove the paths from the result $files = array_diff(scandir($path), array(".", "..")); // Get the number of files in the directory $num_files = count($files); // If there are no files in the directory, return the empty directory variable we defined earlier if($num_files == 0) return $empty_dir; $directory_array = array(); $file_array = array(); foreach($files as $file) { // Set the path correctly $file_path = $path."/".$file; // If the item is a directory if(is_dir($file_path)) $directory_array[] = $file; // The item is a file else $file_array[] = $file; } // Sort each of the arrays alphabetically sort($directory_array); sort($file_array); // Merge the directories and files into one array - directories shown first $files = array_merge($directory_array, $file_array); // Loop through the items foreach($files as $file) { $file_name = $file; // Set the path correctly $file = $path."/".$file; // Get the information for the file if(is_dir($file)) $file_size = "--"; else $file_size = @filesize($file); if($file_size === false) { $checkbox = '<input id="files_check" type="checkbox" name="files[]" value="'.htmlentities($file_name).'">'; $file_name = htmlentities($file_name). " - <b>Fatal Error Reading</b>"; $file_size = "--"; $last_modified = "--"; $type = "--"; $permissions = "--"; $actions = "--"; } else { $finfo = finfo_open(FILEINFO_MIME_TYPE); $checkbox = '<input id="files_check" type="checkbox" name="files[]" value="'.htmlentities($file_name).'">'; if(is_dir($file)) { $file_name = '<i class="icon-folder-open"></i> <a href="manager.php?path='.htmlentities($file_name).'/">'.htmlentities($file_name).'</a>'; } else { $file_name = '<i class="icon-file"></i> <a href="manager/view_contents.php?file=/'.htmlentities($file_name).'&token='.htmlentities($_SESSION['secure_token']).'">'.htmlentities($file_name).'</a>'; } $file_size = htmlentities(get_appropriate_size($file_size)); $last_modified = htmlentities(get_appropriate_date(filemtime($file))); $type = htmlentities(finfo_file($finfo, $file)); $permissions = htmlentities(substr(sprintf('%o', fileperms($file)), -4)); $actions = '<i class="actions"></i>'; } $return .= "<tr> <td>{$checkbox}</td> <td class='file_name'>{$file_name}</td> <td>{$file_size}</td> <td>{$last_modified}</td> <td>{$type}</td> <td class='permissions'>{$permissions}</td> <td class='action'>{$actions}</td> </tr>"; } $return .= '</tbody> </table>'; return $return; ?> I have been developing applications for over 2 years now. In one of my domains I see some strange php files all created on 20th of April 2011 and named like this : IwA8ZSIhJ.php,QvDBnXYevm.php,LXgU1kf16y.php etc etc Any idea what could be the potential reason of creating such files in my hosting ? Thanks Sadan Masroor. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348587.0 As you can see here I have the following code Code: [Select] <?php session_start(); session_register('hazard2'); //INITIALIZE ERROR VARIABLES $errorFound = false; $errorIcon['hazard2'] = ''; if (isset($_POST['submitbutton'])) { //SET SESSION VARIABLES $_SESSION['hazard2'] = $_POST['hazard2']; //TEST FORM INFORMATION if(count($_POST['hazard2']) != 3) { $errorFound = true; $errorIcon['hazard2'] = 'Error Question 2'; } //IF NO ERRORS WERE FOUND, CONTINUE PROCESSING if (!$errorFound) { header( "Location: hazardresult.php" ); } } ?> It's lazy I know, but the script is on a file called hazard2.php, is there anyway to have all of the hazard2's in the code come from the file name. So when I make hazard3, I don't have to change all the hazard2's to hazard3's Thank you Can anyone tell me, how the temporary file names (name of the file which is created in the 'tmp' dir ) generated by PHP when the files are uploaded ? Are there any algorithms used ? I can get files to upload to folder and add a new row for each in to a mysql db using the code below, how do I get all the filles in one row with multiple uploads Code: [Select] //Check if the form was submitted. if(isset($_POST['uploadButton'])) { //Specify folder path where the file is going. $path = 'uploads/'; //Upload file one by one. foreach($_FILES['file']['name'] as $key => $val) { if($val != '') { $file_name = $_FILES['file']['name'][$key]; //Get file name. $file_tmp = $_FILES['file']['tmp_name'][$key]; //Get temporary file name. $file = $path . $file_name; mysql_query("INSERT INTO images (img1) VALUES('$file');") or trigger_error('Unable to INsert: ' . mysql_error()); //Move uploaded file if(move_uploaded_file($file_tmp, $file)) { echo 'File was succesfully uploaded to: ' . $file . '<br />'; } else { //Display error message if there was a problem uploading file. echo 'Error uploading file "' . $key . '."<br />'; } echo $target_path; } } } ?> 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 is this possible? Hi, I want to store files to variable array using glob() like $files[0] = xyz.txt $files[1] = pqr.txt . . . $files[n] = nfile.txt I know how to list files from directory using glob() Code: [Select] <?php foreach (glob("*.txt") as $filename) { echo "$filename size " . filesize($filename) . "\n"; } ?> How can I do that ? 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. In querying my database, I'm Selecting nameFirst and nameLast, and it produces a name like Joe Smith. I'm trying to match a photo with the name. Right now I'm uploading photos into a folder naming the file (e.g. SmithJoe.jpg). For reasons that involve writers being able to upload and access photos, I'm trying to use an image plugin. When uploading photos, it strips capital letters, so SmithJoe,jpg goes in as smithjoe.jpg, and it's not matching my database query. Here is the code I'm working with that works quite well with this one exception: $query = 'SELECT * FROM wp_playerRank'; $results = mysql_query($query); while($line = mysql_fetch_assoc($results)) { if ($line['wpID'] == $wp_tagID) { echo '<div class="player">'; // Here is the code that produces the image. I need to get rid of capital letters for ease of use echo '<div><img src="/wp-content/uploads/' . $line['nameLast'] . $line['nameFirst'] . '.jpg"></div>'; echo '<div class="playerData">' . $line['height'] . ' '; if ($line['position'] == 'PG') {echo 'Point Guard';} elseif ($line['position'] == 'SG') {echo 'Shooting Guard';} elseif ($line['position'] == 'SF') {echo 'Small Forward';} elseif ($line['position'] == 'PF') {echo 'Power Forward';} elseif ($line['position'] == 'C') {echo 'Center';} echo '</div>'; echo '<div class="playerData">' . $line['hschool'] . '</div>'; echo '<div class="playerData">' . $line['summer'] . '</div>'; echo '<div class="playerData">Class of ' .$line['year'] . '</div>'; if ($line['committed'] == 'y') { echo '<div> <br>Committed to <strong>'. $line['college'] . '</strong></div> ';} } } 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 am trying to build an app which will scan a site multple times, the only problem is the 403 error, how do I get around this. Searching seems to imply curl or user_agent, but can't get it working. Any suggestions? Thanks Excuse the beginner question. Though, how do you avoid the processing of HTML when text becomes inputted, without stripping away the tags, or trimming the text in any way, simply leaving it as is? As the title says, I have a .txt file with about 30,000+ lines of data presented in a pipe delimited list, which i'm parsing and inserting into my database. Problem is, my server seems to always time out every time I try to parse the whole file at once. I'm sure naturally it would work with out any timeout errors, but i'm ensuring the data is xss clean before it's being inserted and i'm doing that on about 15 items on each line, which means i'm calling the xss clean function over 450,000 times in one execution. So my friend suggested I break the files down maybe into each file having 5,000 lines of code, which would mean i'd generate about 6 files (if I had 30,000 lines of data). I've managed to code a script that breaks the main file into several files. Now what I want to do is pass each of those files to my parser method, but i'd like to do them one by one, rather than in one execution as I want to avoid the timeout error. Any ideas? When user submits data through a textarea input and he then refreshes the page, the data will be re-submitted and inserted into the database a second time. I used to avoid this with a header redirect, but this solution is not an option to me anymore, since I need to echo out in the header.php, which I have to put before the submission area. Another weak point with the header redirect solution is that the user could go a page back and then hit refresh. I'm wondering how are other sites avoiding resubmission? When you post a comment on YouTube it will simply freeze the submit button after you've posted, I'm guessing they have achieved that with JavaScript, is that solution recommended? And which type of other techniques are people generally using to avoid resubmission on page refresh? If I have a web page located he www . company . com / how-to-repair-your-computer.html
And I decide to re-structure my website like this www . company . com / articles / how-to-repair-your-computer.html
How do I make sure that people don't search and end up at the old, now broken, link?
It seem inevitable that as a website grows, that you will want to re-organize things. What is the best way to make sure that anyone who searches or clicks on an old link - say from an email from a friend - doesn't get a 404 error?
Also, how do you avoid ruining a web pages rank on Google after you move things? (I think if the URL changes, Google makes you start all over as far as getting listed on page-1 and all of that?
Is this something I have to hande on my end, or is it a Google issue, or something else?
I have questions but I also have some good info to share about putting your software in the cloud. The situation: Some of you may have read about the nightmare stories. A developer had a infinite loop in his code that ran all night. This code did things inefficiently that devoured CPU in each iteration. This developer, greatly skilled, opened his email the next morning and saw a email bill from his cloud provider totaling for $75K. True story. Most cloud providers let you define CPU usage thresholds that, when breached, send you a warning but these thresholds, if I understand them, are per account. It would seem the claim that cloud resources are available in whatever amounts you need, CPU, disk space, enough RAM to never have to wait on a page faults, etc... the claim that the cloud provides you with infinitely elastic resources in an "all you can eat for one price" contract smells just a like a little like 💩 I did cloud development for many years with ServiceNow starting when it was a help desk and I watched it evolve into one of the best cloud development platforms out there. At one customer site I installed and managed it it out of the cloud and saw its insides and I can tell you its core code is not so terribly efficient. IMHO the cloud DOES take away 90% of a developer's worries about app performance.. If you call ServiceNow tech support and your problem is diagnosed as a performance issue with your code the first thing they will ask you is "did you follow the developer best practices"? They will politely say "sorry. Here's a link to them implying "fix your code". Questions: PHP Functions that devour CPU and where there is a better way? What PHP functions or code techniques waste CPU? I am using similar_text and it does the job but it is slow. Better way? What is the best way to measure CPU used by a PHP script or by a particular code module, defined as a set of related functions that fulfill a common purpose or by a single line of code? The purpose being to identify inefficient modules of code and improve them and even if the code is damn near perfect then at least can know what code modules are the most expensive. CPU killin users (and developers too), how can they be identified? I need to store data on cumulative CPU usage for any of the above and compare it with the free amount they give you and warn CPU hogs before they breach a threshold and generate $75K bills that were not in the plan. Any info you have on avoiding surprise $75K CPU bills from a cloud provider are welcome
It would seem the |