Home | Me | Portfolio | Search
Creating a file and downloading it in php
03-27-09

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.

Step 1: Getting the I.P Address

To get the ip address, we use this code: $_SERVER['REMOTE_ADDR'];

So when we put it as a varible:

$ip = $_SERVER['REMOTE_ADDR'];

Step 2: Creating the file

Now that we have the user’s ip address stored in a varible, we want to put it in a file.

So first, we need to create the file:  fopen($ip, 'w') or die("die");

If you notice, we are using hte person’s ip address for the file name.

Now here is the final piece of that code: $file = fopen($ip, 'w') or die("die");

Step 3: Writing to the file

So we have the file created and now we need to write to it. Use this code to do so: fwrite($file, $ip);

Note that it writing the ip address to our file

Step 4: Close it

Not much for this: fclose($file);

Step 5: Forcing it

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

$filepath = "/home/manywor/public_html/phptest/";

$file = $filepath . $ip; header("Content-type: application/force-download");

header("Content-Transfer-Encoding: Binary"); header("Content-length: ".filesize($file));

header("Content-disposition: attachment;filename=\"".basename($file)."\""); readfile($file);

I’ll explain all that in a later tutiral.

Step 6: Deleting the file

To delete the file, all we need to do is this: unlink($ip);

Note that it deletes the file named after that ip adress

Final Code

//Get the IP Address of the user

$ip = $_SERVER['REMOTE_ADDR'];

//Create and close the text file

$file = fopen($ip, 'w') or die("die");

//Write to the text file

fwrite($file, $string);

//Close it fclose($file);

//Force it

$filepath = "/home/manywor/public_html/phptest/";

$file = $filepath . $ip; header("Content-type: application/force-download");

header("Content-Transfer-Encoding: Binary");

header("Content-length: ".filesize($file)); header("Content-disposition: attachment; filename=\"".basename($file)."\""); readfile($file);

//Delete it

unlink($ip);

Final Thoughts

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:

//Replace the dots in it

$ip =str_replace(".","",$ip);

//Turn the IP into a text extention

$extiontion = ".txt";

$ip = $ip .''. $extiontion;