Reputation: 268
I have a site I am working on with over 11000 product pages. They are written is .php
I am trying to add the file name (without the file extension .php) to the file for identifying the current page.
Example: If the file name is
product1.php
A line of code
$thisPage = "product1"
Will be added to each page withing the top PHP tag. I have tried to find a solution to this for longer than I care to admit, and while I am a PHP newb, it seems like their must be a simple solution.
Any help would be greatly appreciated
$currentPage = $_SERVER["PHP_SELF"];
Is what I know to use to get the name of the file. I can the truncate $currentPage to remove the ".php" from the string. I will then be left with the text I want to write to the file.
The difficulty I am having, is writing it to the file, not echoing the name but actually writing the file name as a new string for later use.
So what I will be left with
$currentPage = "the-truncated-file-name-text"
Unique to each page for use indexing
So something like "write($currentPage)" to the file
Upvotes: 0
Views: 3879
Reputation: 11221
php.net is a wonderful resource.
The pathinfo function is what you want. It splits a path or filename into its constituent parts.
Alternatively you could explode on '.'
list($file, $ext) = explode('.',$myfile);
to write it to your file then call
file_put_contents($filename, $stringtoadd, FILE_APPEND);
however note that doing this will make your file no longer a valid CSV file as the format of the last line will not be correct.
Upvotes: 2
Reputation: 48887
$thisPage = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME );
You'll want to stay away from magic constants like __FILE__
as they will return the current running file, i.e., if the code is in an include file, the path of the included file will be returned, not the script requested by the visitor.
Upvotes: 4