View Full Version : Variable's used in fopen and file paths question.

03-25-2009, 08:10 PM
Hello -

I have been learning PHP for about a month now, and I am working on a large project that requires a lot of it. My project involves the Google Maps API and I have a database that populates my map with information collected from a form.

Each of the markers on my map are populated by the following javascript code:

var html = '<b>' + name + '</b> <br/>' + address + '<br />' + '<a href=\"/locations/' + state + '/' + city + '/' + name + '\">View Profile</a>';

As you can see a link is created in the marker using the state, city and name.

Now that I have determined a URL path, I need to actually create it. I need a way to go through the database and create a file and file path for each one, this will be a "Profile" page for each location.

I know how to use fopen to create a file, I just dont know how to use a variable $name for the file and I cant find a guide that explains how to determine the file path, which in my case would be location/$state/$city/ and then the actual file.

Any help would be greatly appreciated, it somewhat hard to explain the ultimate goal I envision so if you need more details I will certainly give them.

If you know of any guides anywhere that relate to this in some way that would work perfectly.


03-25-2009, 08:29 PM
Use pathinfo() to determine a filename's path.


You can use a variable in place of a string with fopen(), as with any function.

$filename = "mamma.txt";
$handle = fopen($filename, "r");

03-25-2009, 08:43 PM
Thankyou for the link to pathinfo documentation.

As for the fopen part, could I do something like the following?

$filename = "$name";
$handle = fopen($filename.'.php', "r");



$filename = "$name";
$handle = fopen('/locations/'.$state.'/'.$city.'/'.$filename.'.php', "r");

03-25-2009, 09:45 PM
Sure can, although there's no point in your reassignment $filename = $name; statement; you can juse use your $filename variable.

03-25-2009, 10:08 PM
Alright thanks Fumigator.

Also, if I added $_SERVER["HTTP_HOST"]. before the location directory, would that ensure that it always uses my root directory? Or is there a better method?

By the way, I have been reading through the archives, and this is by far the most resourceful coding website I have ever come accross. Really glad I found you guys today.

03-25-2009, 10:48 PM
I believe you'll be best served using $_SERVER['DOCUMENT_ROOT'], which I think can't be manipulated by your browser (HTTP_HOST can be set to anything by the browser and/or hooligans messing with a browser).


Be sure to avoid using a protocol prefix (such as http://) as part of the filename, as doing so convert fopen() to using a HTTP (or other) wrapper which changes permissions to the file (you typically can't modify a file through a HTTP wrapper).