I don’t have as much experience with PHP as I have with c and c++, so I am not new to programming but pretty new to web programming.
My question is about, how to do specific Url for a content. That means, I have for exemple a view.php file, that reads from a txt file and echos it on the page. Now, I have 5 .txt files: file_1.txt, file_2.txt … file_5.txt. And I want to have 5 different urls specific to this files.
How do I do that? I want to have like: domain.com/writer.php/file_2.txt and make it so that my file reading function in writer.php gets file_2.txt specifically.
I am sure this has an easy way to do it. I mean I can try and code something complicated with SESSION and POST variables. But I think there should be an easiest, and commonly used way.
I really tried to research this on the internet. And I am sure there is the easy answer somewhere on the net. But I just couldn’t formulate it the right for when I googled for it.
Over the years “pretty URLs” and routing have become more popular.
That is “.html” or “.php” are not part of the URL and a lot of times HTTP requests don’t go directly to an actual file of that name, but result in a page getting displayed comprised of content put together on the server.
If you have only a few pages and you don’t mind the “old fashioned” URLs. the simple folder / file structure is easy work. You can use PHP to build the resulting page that is output to the browser from various pieces whether it be various assets, CSV, XML, text files, other PHP files, a database or other sources.
Thinking ahead about the goal is a good thing, but if you don’t have a good grasp of HTML yet, I strongly recommend you start there.
A common way to do something like this is with URL variables and GET.
So the URL may look like:-
http://www.example.com/thisfolder/?page=2
The index.php file in that folder will contain something like:-
if(isset($_GET['page'])) {
$pn = preg_replace('#[^0-9]#i', '', $_GET['page']) ; // Filter and get the page number (pn)
$filename = 'file_' . $pn . '.txt' ; // Put the page number into the filename string
}
page is the url variable, which in the example is equal to 2: ?page=2 $_GET gets the value of whatever variable you ask for, so $pn gets the value of 2 in this case.
In its simplest form, $pn = $_GET['page']
The 'preg_replace` is there to filter out any non numeric data, for security and prevention of error.
You guys are awesome, I just got what I wanted work on my website.
Btw yes Mittineague, I will definitely try more complicated codes with what I understood. And I will also use htaccess to hide the url names, and show users a cleaner link, just like youtube does for exemple.