Hello, I am still working on my Demo uploader site and would like to add a functionality which only allows users to upload 5 files within any given 24hour period. If they have uploaded 5 files, I want to make the form 'hidden' on the page.

I have seen a simple example of retrieving a users IP on php.net and know it is something to do with the $_SERVER global.

What I need to know is how would I integrate this into my current code:

My examples.php(main page):

<?php session_start();  ?>
<!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"  xml:lang="en" lang="en">
<head>
     <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
     <title>php form</title>
     <link rel="stylesheet" type="text/css" href="styles/style.css" />
</head>
<body>


<div id="container">
     <img src="images/mainbanner_v3.png" alt="DXDU Banner" title="Deus Ex Demo Uploader Logo" id="logo" border="0" />

 <?php define("MAX_FILE_SIZE", 10485760); ?>

<form action="upload.php" method="POST" enctype="multipart/form-data">
	 <fieldset>
	     <legend>Upload Your Deus Ex Demos</legend>
		 <p><label for="title">Title:</label><input type="text" name="title" maxlength="40" size="45" /> 
	     <p><label for="description">Description:</label><textarea cols="34" maxlength="170" rows="5" name="description"></textarea></p>
	     <p><label for="browse">Browse:</label><input type="file" name="file_upload" /></p>
	     <p><label for="submit">Upload:</label><input type="submit" name="submit" value="Submit" /></p>

 </fieldset>
</form>

<div id="guidelineDiv">
<pre>
 <u>Guidelines:</u>

  1. You can only post demo files with the extension (.dem).
  2. You can only post demo files which are 10mb or less.

  <span class="bold">WARNING:</span><span class="white"> Measures are in place to prevent users uploading
  anything but demo files. Persistance in trying to upload 
  malicious files will result in the user being banned from 
  uploading files, allowing them only to download files. 
  Should you repeatedly experience problems with uploading,
  please email me at <span class="email">flipmodeskwaud@hotmail.co.uk</span> also
  proving the specific error message, so that the issue
  can be debugged quicker. Thank you. Please enjoy</span>

</pre>
</div>

<?php 
     if(isset($_SESSION['answer'])){
         echo "<p class='messages'>{$_SESSION['answer']}</p>";
		 session_destroy();
     }
     else{
	     $_SESSION['answer'] = "undefine";
		 session_destroy();
	 }


?>
<?php if(!empty($message)){ echo "<p>{$message}</p>"; } ?>

<hr  id="ruleHeader" noshade="noshade" size="4" />

<table id="results">
     <tr>
	     <th>Demo Name</th>
		 <th>Title</th>
		 <th>Description</th>
	     <th>Size</th>
	     <th>Date</th>
     </tr>
	 <?php
	     require("connect.php");
	     $query = mysql_query("SELECT * FROM fileinfo");

	 while($row = mysql_fetch_array($query)){
         echo '<tr><td><a href="download.php?id='.urlencode($row['id']).'&name='.urlencode($row['name']).'">'.$row['name'].'</a></td><td> '.$row['title'].'</td><td> '.$row['description'].'</td><td> '.$row['size'].'</td><td> '.$row['date'].'</td></tr>';  
     }
 ?>

</table>

</div>
</body>
</html>

My upload.php (action script):

<?php
session_start();

define("MAX_FILE_SIZE", 10485760);

$upload_errors = array(
     UPLOAD_ERR_OK         => "No Errors.",
     UPLOAD_ERR_INI_SIZE   => "Larger than upload_max_filesize.",
     UPLOAD_ERR_FORM_SIZE  => "Larger than form MAX_FILE_SIZE.",
     UPLOAD_ERR_PARTIAL    => "Partial upload.",
     UPLOAD_ERR_NO_FILE    => "No file.",
     UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
     UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
     UPLOAD_ERR_EXTENSION  => "File upload stopped by extension."
);

/*FUNCTION TO SANITIZE USER INPUT. RETURNS USER INPUT + FILENAME VARIABLES STRIPPED OF ANY SPECIAL CHARACTERS*/
	         function check_input($data) {
			     $illegalChars = array('!','@','#','$','%','^','&','*','(',')','+','=','-','[',']','.',';',',','/','{','}','|','"',':','<','>','?'); 
				 $data = str_replace($illegalChars,'',$data);
                 $data = trim($data);
                 $data = stripslashes($data);
                 $data = htmlspecialchars($data, ENT_QUOTES);
	             $data = mysql_real_escape_string($data);
                 return $data;
             }

/*FUNCTION THAT AMENDS A 1-2 DIGIT NUMBER ONTO THE END OF A FILENAME, IF THAT FILENAME ALREADY EXISTED.*/
function editName($data){
     $info = pathinfo($data);//retrieves info on the file path.
	 $data = basename($data,'.'.$info['extension']);//returns just the filename - without extension.
	 $data = $data.rand(0, 99);//concatenates a random 2 digit number onto the end of the file name.
	 $data = $data.'.'.$info['extension'];//concatenates the extension of the file back onto the new filename.
     return $data;//returns the new filename.
}

if($_SERVER['REQUEST_METHOD'] == "POST"){

 if(is_uploaded_file($_FILES['file_upload']['tmp_name'])){

     if($_FILES['file_upload']['error'] === 0){//if the uploaded file uploaded with no error....

		 $title = check_input($_POST['title']);
		 $description = check_input($_POST['description']);
	     $name = basename($_FILES['file_upload']['name']);//full file name and extension.
	     $type = $_FILES['file_upload']['type'];//file type eg. application/octet-stream..
	     $size = $_FILES['file_upload']['size'];//file size in bytes.
	     $tmpname = $_FILES['file_upload']['tmp_name'];//temporary name on server before being moved.
	     $date = date('d/m/Y');//date - format dd/mm/yyyy.
         $c = substr_count($name, '.');//counts how many occurences of '.'
	     $dir = "files";//directory name for target file.
	     $ext = pathinfo($name);//Array..information about the file..
	     $ext = $ext['extension'];//stores the file extension in $ext...

	     if($c === 1){
		     while(file_exists($dir.'/'.$name)){//while a file exists in that directory with the same name as the given file...
			     $name = editName($name);//then amend the file name.
			 }

			 if($type == 'application/octet-stream' && $ext == 'dem' && $size <= MAX_FILE_SIZE){
			     if(move_uploaded_file($tmpname, $dir."/".$name)){//if the file moved successfully, then insert information to database.

					 require("connect.php");
					 $query = mysql_query("INSERT INTO fileinfo VALUES('', '{$name}', '{$title}', '{$description}', '{$size}', '{$date}')");

					 if(!$query){
					     $_SESSION['answer'] = "There was a MYSQL error.";
						 header("Location: examples.php");
					 }
					 else{
						 $_SESSION['answer'] = "Your file uploaded successfully.";//create session variable to use in examples.php--only on success
						 header("Location: examples.php");//redirects user to the examples.php page.
					 }

				 }
			     else{
				     $_SESSION['answer'] = "Error: Couldnt move file. Please try again later.";
					 header("Location: examples.php");
				 }
			 }
			 else{
			     $_SESSION['answer'] = "Error: Please make sure to upload only demo files which are 10 MB or less.";
				 header("Location: examples.php");
			 }

         }
	     else{
	         $_SESSION['answer'] = "Error: Corrupted file.";
			 header("Location: examples.php");
	     }
     }	 
     else{
         $error = $_FILES['file_upload']['error'];
	     $message = $upload_errors[$error];
     }
 }
 else{
     $_SESSION['answer'] = "Error: Please try uploading again.";
	 header("Location: examples.php");
 }
}
else{
     $_SESSION['answer'] = "Error with the HTTP service.";
	 header("Location: examples.php");
}
?>

Any advice, links or guidance will be greatly appreciated as I am completely lost..

Regards,

Labtec

    Labtec;11007327 wrote:

    I have seen a simple example of retrieving a users IP on php.net and know it is something to do with the $SERVER global.

    Perhaps you're thinking of $SERVER['REMOTE_ADDR']?

    However, you've left out one important piece of information - how are you going to keep track of these IP addresses? Perhaps in a SQL database of some sorts?

    Also note that it's beyond "easy" to get a new IP address within a couple of mouse clicks, so I hope you're not depending on this feature to completely stop users who decide they really want to upload more than 5 files.

      What would you suggest on how to limit them uploading?

      Regards,

      Labtec.

        Labtec;11007345 wrote:

        What would you suggest on how to limit them uploading?

        Well, that depends. Most likely, the short answer is: you can't - you can just give it your best shot and hope that users don't attempt to circumvent the limit.

        The long answer would depend on a couple of factors, e.g. the user management system (if any) you use, the amount of effort you're willing to put into this, the criticality of this limit, etc. For example, if you aren't using some sort of user management system (e.g. you have to register and login before uploading files), then your chances are pretty much slim to none that you can ensure that a given person can't exceed the limit. You're restricted to only using information about the request as well as any data that the user's browser volunteers (e.g. cookies and whatnot); unfortunately, the former is quite easy to modify (the number of free proxies/VPNs out there is staggering) and the latter is even easier (since the user has direct control over that data).

          Also note that some users will be sharing the same ip address. I remember that we once blocked an IP address for very good reasons, but in the end it turned out to be used for WAP fpr one of Sweden's largest cell phone companies, which meant that we suddenly blocked pretty much anyone else using WAP. I do not know but I'd guess that the same goes for current cell phones connecting via the cell phone network: Once the request gets to the cell phone service providers, there are a limited number of possible IP addresses used by the service providers for such a request. Thus, if you wish to cater to phone users, IP limitations may not even be remotely possible to implement.

          The best way to do this is to require users to create accounts and have the limit tied to the account. If you also limit one account per email address and require the use of a valid email address to create an account, few users will circumvent your system. However, some will still do it and there's nothing you can do about it. Perhaps your county or countries in question have some kind of individually assigned code (social security code, personal identification code or whatever they may be called), you are allowed to use such a code and can access some government system to check such a code against name, address etc which would once again up the amount of work needed to circumvent the system. Just remember that a user might still make use of someone elses information (just like you are able to verify the information sent - it's public!), albeit it is likely to be a criminal offense to use the ID code of someone else.

          Another thing you may do is require an account to be "ok'ed - usually within the hour) before they can upload images with it, while claiming it's for any other number of reasons (and automate such an "ok-ing process" on a random timer. And on top of that after such an OK you may require an additional 1 week period before allowing the 5 / day upload.

          Just keep in mind that you balance your limits between the effort to implement them, the amount of annoyance created for users who do not circumvent them, the actual need to prevent circumvention etc.

            Write a Reply...