954,561 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help on PHP fopen

I am trying to make a website that uses fopen to open up text file. Something like this http://somesite.com/readarticle.php?name=sample.txt

<?php
$file = 'sample.txt';
$f = fopen($file, r);
while ( $line = fgets($f, 1000) ) {
print $line;
}
?>


The sample.txt is located on the web server, I was able to make this work but my problem now is how do I use the same php file on opening other text file without specifying filename on the php file itself?

Something like this.. http://somesite.com/readarticle.php?name=sample.txt
http://somesite.com/readarticle.php?name=sample2.txt
http://somesite.com/readarticle.php?name=sample3.txt

Sorry for my bad english..:)

ivatanako
Junior Poster
150 posts since Jul 2007
Reputation Points: 18
Solved Threads: 16
 

You can get URL value's with $_GET[] array, in your sample URL ( http://somesite.com/readarticle.php?name=sample.txt ) it would be $_GET['name']; . Be warned to use this cause this brings potential security leeks with it. you should read up on the problems with it.

<?php
$file = $_GET['name'];
$f = fopen($file, r);
while ( $line = fgets($f, 1000) ) {
print $line;
}
?>


now if I go to readarticle.php?name=readarticle.php I can see the PHP source.
Good luck with your site.

Anonymusius
Posting Whiz in Training
238 posts since Aug 2006
Reputation Points: 129
Solved Threads: 11
 

Oh? Thank you! Is there any way I could use this function without this information leak? Any suggestions?

ivatanako
Junior Poster
150 posts since Jul 2007
Reputation Points: 18
Solved Threads: 16
 

yeah.. but, use if conditional to safely your site. like this
if ($_GET['name'] == $_PHPSELF) die(

ndunks
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You