Creating a file and downloading it in php


SUBMITTED BY: Guest

DATE: April 30, 2013, 9:04 a.m.

FORMAT: Text only

SIZE: 2.9 kB

HITS: 996

  1. Today I’ll show you how to get a user’s ip, stick it in a text file, and have the download it all without the text file being stored on your server for more than a few seconds.
  2. Step 1: Getting the I.P Address
  3. To get the ip address, we use this code: $_SERVER['REMOTE_ADDR'];
  4. So when we put it as a varible:
  5. $ip = $_SERVER['REMOTE_ADDR'];
  6. Step 2: Creating the file
  7. Now that we have the user’s ip address stored in a varible, we want to put it in a file.
  8. So first, we need to create the file: fopen($ip, 'w') or die("die");
  9. If you notice, we are using hte person’s ip address for the file name.
  10. Now here is the final piece of that code: $file = fopen($ip, 'w') or die("die");
  11. Step 3: Writing to the file
  12. So we have the file created and now we need to write to it. Use this code to do so: fwrite($file, $ip);
  13. Note that it writing the ip address to our file
  14. Step 4: Close it
  15. Not much for this: fclose($file);
  16. Step 5: Forcing it
  17. Now that we have the file created and with the ip adress in it, we have to make the browser be “forced” into downloading it
  18. $filepath = "/home/manywor/public_html/phptest/";
  19. $file = $filepath . $ip; header("Content-type: application/force-download");
  20. header("Content-Transfer-Encoding: Binary"); header("Content-length: ".filesize($file));
  21. header("Content-disposition: attachment;filename=\"".basename($file)."\""); readfile($file);
  22. I’ll explain all that in a later tutiral.
  23. Step 6: Deleting the file
  24. To delete the file, all we need to do is this: unlink($ip);
  25. Note that it deletes the file named after that ip adress
  26. Final Code
  27. //Get the IP Address of the user
  28. $ip = $_SERVER['REMOTE_ADDR'];
  29. //Create and close the text file
  30. $file = fopen($ip, 'w') or die("die");
  31. //Write to the text file
  32. fwrite($file, $string);
  33. //Close it fclose($file);
  34. //Force it
  35. $filepath = "/home/manywor/public_html/phptest/";
  36. $file = $filepath . $ip; header("Content-type: application/force-download");
  37. header("Content-Transfer-Encoding: Binary");
  38. header("Content-length: ".filesize($file)); header("Content-disposition: attachment; filename=\"".basename($file)."\""); readfile($file);
  39. //Delete it
  40. unlink($ip);
  41. Final Thoughts
  42. To make the file download as a text file, you’ll need to stick an txt extension on the ip adress. I used this code to do so:
  43. //Replace the dots in it
  44. $ip =str_replace(".","",$ip);
  45. //Turn the IP into a text extention
  46. $extiontion = ".txt";
  47. $ip = $ip .''. $extiontion;
  48. Also, its not secure, so I would clean it up before using it ;)

comments powered by Disqus