PHP - Saving Files For Users
I have a bunch of users in a database (id, name, etc).
I have a bunch of documents which belong to users (id, filename, users_id, etc), and expect 500 or less per user.
The documents will be renamed to the document_id, and X-Sendfile (since they are stored under the document root) will be used to retrieve them and a header will be used to return them to their original name.
Is it recommended to make a separate folder for each user and store each individual user's documents in that folder, or create one folder for all documents?
If I go with the one folder approach, I will need some method from keeping the total files per folder below some reasonable limit (1,000?). My thought is to estimate the maximum potential number of folders, and creating subfolders under the main document folder. I will likely hash the ID, and use the first character to create the first subfolder, the second character to create a second subfolder in the first subfolder, and continue as long as needed to accommodate the maximum potential documents (if there are 1,000,000 potential folders, then three levels will keep the maximum per folder under 244).
Please provide rational for one approach over the other.
Thank you
Similar TutorialsHello, Its my first day coding so please forgive me for some of the silly errors I might make.
I am writing a small upload script and I want to have some sort of orginazation by uploading images to a direcotry based on the day. The following is my code but it will fail to save the file Warning: file_put_contents(images/14-09-26/5425905a18bba.png): failed to open stream: No such file or directory This is becuase the directory with the data part is not created how should I go about first checking that this directory is there and then creating it ? <?php ini_set('display_errors',1); error_reporting(E_ALL); $today = date('y-m-j'); define('UPLOAD_DIR', 'images/' .$today. '/'); $img = $_POST['data']; $img = str_replace('data:image/png;base64,', '', $img); $img = str_replace(' ', '+', $img); $data = base64_decode($img); $file = UPLOAD_DIR . uniqid() . '.png'; $success = file_put_contents($file, $data); print $success ? $file : 'Unable to save the file.'; ?> Hi:
Am not sure if this is the best algorithm to go about saving a record and uploading (plus moving to another directory) files. I feel i need another algorithm?
if (self::post()->isPost()) { #check if there is any file if($this->request->hasFiles() == true){ $uploads = $this->request->getUploadedFiles(); $isUploaded = false; #do a loop to handle each file individually foreach($uploads as $upload){ #define a "unique" name and a path to where our file must go $path = 'temp/'.md5(uniqid(rand(), true)).'-'.strtolower($upload->getname()); #move the file and simultaneously check if everything was ok if($upload->moveTo($path)) { #Build an array to be sent to the API for moving the uploaded file to front end directory $files=""; $files = array( 'name' => $upload->getName(), 'link' => $this->di['url']->get('temp/' . $upload->getName()), 'direction' => 'adverts' ); $saveResult = self::request()->request('move-advert/', array('file' => $files), 'POST'); if($saveResult->response == 'success') $isUploaded = true; else $isUploaded = false; } } #if any file couldn't be moved, then throw an message if($isUploaded) { $save_response = self::request()->request('advert/' . $id, self::editValues(self::post()->getPost()), 'POST'); if ($save_response->response == 'success') { $this->flashSession->success('Advert Updated'); return $this->response->redirect('adverts/list-adverts'); } else { $this->flashSession->notice('Could not update Advert'); } } else { $this->flashSession->notice('Some error ocurred. Please try again'); } }else { $this->flashSession->notice('You must Choose an advert image'); } }Any suggestions? Hi I am creating an e-commerce website, where users who pay with their credit card are able to download pdf books. how can I make a PDF file only accessible for those users (who pay and validate their credit card) and not for everyone ? I want to know the main idea about securing these files. hi... I have a site that allows user to download some files. at present if i type http://www.abc.com/files/xyz.zip it allows all the users to access and download files. I want only the login users can access these files....... pls help how to do this. thanks in advance Hi, I'm pretty new to this, so apologies if there's some simple solution/misunderstanding. It seems to me that when the user uploads a file, PHP pulls in the file into the temporary directory and then you can query it using the $_FILES array. Assuming I am correct so far, I have two questions: 1. Is there anyway to prevent the upload to the temporary folder based on file size? Seems to me a good way to overload a server to upload 10GB files, even if they are picked up as "errors" and deleted from the temp folder. 2. How long do files stay in the temporary folder? Does PHP delete them automatically, and if so, when? Thanks. My server is Linux/Apache/PHP.
When a file is uploaded, I use PHP's finfo_open to confirm that the file have the correct file extension matches and delete them if it doesn't match. I also which file mimi types and size could be uploaded.
Things I do with the files include:
Upload user's files and store them in some public directory (/var/www/html/users_public_directory/), and allow other users to directly download them.
Upload user's files and store them in some private directory (/var/www/users_private_directory/), and allow other users to download them using X-Sendfile.
Upload user's ZIP files and convert them to PDF files (unzip the ZIP file, and uses Libreoffice and Imagemagick's convert to convert them to PDFs).
From the server's prospective, what are the risks of allowing users to upload files? Are there some file types which are more dangerous to the server? Could they be executed on the server, and if so, how could this be prevented?
Hello
I am trying to work out how many regular users I have to my site and how long those users tend to be users..
So, I have a table that logs every time a user visits my site and logs in, it stores the date / time as a unix timestamp and it logs their user id.
I started by getting the id's of any user who logs in more than 5 times in a specified period, but now I want to extend that...
SELECT userID as user, count(userID) as logins FROM login_history where timestamp > UNIX_TIMESTAMP('2014-06-01 00:00:00') and timestamp < UNIX_TIMESTAMP('2014-07-01 00:00:00') group by user having logins > 5; I just discovered that I have a major security flaw with my website. Anyone who logs in to the website can easily access other users information as well as delete and edit other users information just by changing the ID variable in the address bar. I have user ID Session started on these pages but still people can do anything they like with other users information just by editing the address bar. For example if your logged in in the address bar of www.mywebsite.com/delete_mystuff.php?id=5 and change the "5" say to a "9" then you will have access to user#9 information. Every important page that I have has this code: Code: [Select] session_start(); if (!isset($_SESSION['user_id'])) { // Start defining the URL. $url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); // Check for a trailing slash. if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) { $url = substr ($url, 0, -1); // Chop off the slash. } // Add the page. $url .= '/index.php'; ob_end_clean(); // Delete the buffer. header("Location: $url"); exit(); // Quit the script. } else { //Else If Logged In Run The Script if((isset($_GET['id'])) && (is_numeric($_GET['id']))) { $id = (int) $_GET['id']; } elseif ((isset($_POST['id'])) && (is_numeric($_POST['id']))) { $id = (int) $_POST['id']; } else { echo ' No valid ID found, passed in url or form element'; exit(); } What am I doing wrong? Please help if you know how to correct this. Many thanks in advance. Hello I have a simple question about file handling... Is it possible to list all files in directories / subdirectories, and then read ALL files in those dirs, and put the content of their file into an array? Like this: array: [SomePath/test.php] = "All In this php file is being read by a new smart function!"; [SomePath/Weird/hello.txt = "Hello world. This is me and im just trying to get some help!";and so on, until no further files exists in that rootdir. All my attempts went totally crazy and none of them works... therefore i need to ask you for help. Do you have any ideas how to do this? If so, how can I be able to do it? Thanks in Advance, pros So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png fileĀ which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is? i have made 2 classes. the first "point" has an array of 3 floats and some functions to help manipulate the values the second "triangle" has an array of 3 points. in this way if i want to make a tetrahedron i can make 4 points and assign them to 4 triangles. problem is for some reason each triangle point group seems to use 1k. any idea why? I have a .php code that gets data from a database and saves it in a variables as xml. However how can I then save all of the data in this variable as a .xml file somewhere? Thanks for any help. I am using WPSQT plugin in my blog site .I code some files in PHP also.how to add that files in plugin files.
Hi All... I am looking for a way of saving currently open webpage as a pdf file.........I searched for that and even gone for this site http://www.tcpdf.org. But there also I didn't find any perfect way of doing this all....If somebody else has tried tcpdf for that or done something like that, then plzzzzz plzzz plzzzz do help me....Thanx...... I'm trying to get an equation from a user that types it in the url, ex) 1+2+3. I can get the 1,2,3 fine, but the + operator is no longer in the string. Same with the * and / operators. Is there a way to keep them as a string using $_GET?
Am trying to update a table called "budget_request" and also inserting the data of that table into another table called "Budget". The Update works but it is not inserting into the other table. please help me out.. check my code below
<?php $id = $_GET['id']; ?> <?php include('mysql_connect.php'); $q = mysql_query("UPDATE budget_request SET status = 'Approved' WHERE id = '$id'") or die(mysql_error()); // send the details to the budget database $query = mysql_query("SELECT * FROM budget_request WHERE id = '$id' ") or die (mysql_error()); $dat = mysql_fetch_array($query); $department = $dat['department']; $amount = $dat['amount']; // Add the data to the Budget DB $que = (" INSERT INTO budget (id, department, amount, actual) VALUES ( ' ','$department', '$amount', '$amount')" ) or die(mysql_error()); header("Location: add_budget.php"); ?> $new_relation->save(); echo "after save".$requestor_profile->getId()." ".$requestee_profile->getId(); return true; }catch(PropelException $e) { echo "in die"; die($e); return false; } }//end - if (!$res) [/PHP] the echo after the save executes but when i look in my db table there is nothing???? please help??? Hi, I'm completely new to anything that is not html but I'm wondering if in something like php I can get a checkbox to permanently save through reloads and different machines. My idea was just to have a page with only a checkbox on it, and then load that through and iframe in html. If anybody could give me the code for that checkbox page (complete if possible as I don't really know anything about that type of programming) I would be very grateful. Thank You I have problem how to saving all my record.
when I save I just got 1 record saved in mySQL and it the last record on that table. Here is my code =
<?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO thasil (nrp, nama, pangkat, mgolongan, mtes_fisik, mkemampuan, hasil) VALUES (%s, %s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['nrp'], "int"), GetSQLValueString($_POST['nama'], "text"), GetSQLValueString($_POST['pangkat'], "text"), GetSQLValueString($_POST['mgolongan'], "int"), GetSQLValueString($_POST['mtes_fisik'], "double"), GetSQLValueString($_POST['mkemampuan'], "double"), GetSQLValueString($_POST['hasil'], "double")); mysql_select_db($database_stok, $stok); $Result1 = mysql_query($insertSQL, $stok) or die(mysql_error()); $insertGoTo = ""; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } mysql_select_db($database_stok, $stok); $query_anggotaset = "SELECT * FROM tanggota ORDER BY nrp ASC"; $anggotaset = mysql_query($query_anggotaset, $stok) or die(mysql_error()); $row_anggotaset = mysql_fetch_assoc($anggotaset); $totalRows_anggotaset = mysql_num_rows($anggotaset); mysql_select_db($database_stok, $stok); $query_bobotset = "SELECT * FROM tbobot"; $bobotset = mysql_query($query_bobotset, $stok) or die(mysql_error()); $row_bobotset = mysql_fetch_assoc($bobotset); $totalRows_bobotset = mysql_num_rows($bobotset); $crMax = mysql_query("SELECT min(Golongan) as minK1, max(tes_fisik) as maxK2, max(kemampuan) as maxK3 FROM tanggota"); $max = mysql_fetch_array($crMax); $no=1; ?> <?php include ('header.php') ?> <div id="conten-wrapper"> <div id="conten"> <h1> Normalisasi Anggota Kesamaptaan </h1> <p> <a href="cetak.php"><img src="../images/btn_list.png" height="20"/> >>> Lihat & Cetak Hasil Akhir Perangkingan</a></p> <form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1"> <table border="1" cellpadding="3" cellspacing="1"> <tr> <td>no</td> <td>nrp</td> <td>nama</td> <td>pangkat</td> <td>C1 Golongan</td> <td>C2 tes_fisik</td> <td>C3 kemampuan</td> <td>hasil</td> </tr> <?php do { $hasil= round (($max['minK1']/$row_anggotaset['Golongan']*$row_bobotset['golongan']+ $row_anggotaset['tes_fisik']/$max['maxK2']*$row_bobotset['tes_fisik']+ $row_anggotaset['kemampuan']/$max['maxK3']*$row_bobotset['kemampuan']),2) ; ?> <tr> <td><?php echo $no; $no++;?></td> <td><input type="text" name="nrp" value="<?php echo $row_anggotaset['nrp']; ?>" readonly/></td> <td><input type="text" name="nama" value="<?php echo $row_anggotaset['nama']; ?>" readonly/></td> <td><input type="text" name="pangkat" value="<?php echo $row_anggotaset['pangkat']; ?>" size="4" readonly/></td> <td><input type="text" name="mgolongan" value="<?php echo round ($max['minK1']/$row_anggotaset['Golongan'] *$row_bobotset['golongan'],2); ?>" size="2" readonly/></td> <td><input type="text" name="mtes_fisik" value="<?php echo round ($row_anggotaset['tes_fisik']/$max['maxK2'] *$row_bobotset['tes_fisik'],2); ?>" size="2" readonly/></td> <td><input type="text" name="mkemampuan" value="<?php echo round ($row_anggotaset['kemampuan']/$max['maxK3'] *$row_bobotset['kemampuan'],2); ?>" size="3" readonly/></td> <td><input type="text" name="hasil" value="<?php echo $hasil ?>" size="2" readonly/></td> </tr> <?php } while ($row_anggotaset = mysql_fetch_assoc($anggotaset));?> <tr valign="baseline"> <td colspan="8" align="right" nowrap="nowrap"><input type="submit" value="Insert record" /></td> </tr> </table> <input type="hidden" name="MM_insert" value="form1" /> </form> </div> <?php include ('footer.php') ?> </body> </html> <?php mysql_free_result($anggotaset); mysql_free_result($bobotset); ?> Hi I'm really new to php and could really do with some help. I am using the following script http://test.dpetroff.ru/jquery.iviewer.test/test/ which basically allows me to position an image within a DIV area My question is, how can I get PHP to save just the image within the DIV area, so it's almost acting like a crop tool I've tried a few things but so far not managed to get anything working |