Home » Php » How to use a PHP include to print HTML code based on URL filename

How to use a PHP include to print HTML code based on URL filename

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying to write a simple PHP script that uses PHP include to inject HTML based on the filename of the URL.

For example using a PHP include
– if the filename in the URL is dog.html print dog into the html document.
– if the filename in the URL is cat.html print cat into the html document.

This is to inject JSON-LD code for structured data.

I’m able to use PHP includes to print html code without issue, but its getting it to read the filename and print a specific portion of HTML that I can’t seem to make work.

How to&Answers:

You can get the filename using __FILE__ constant. It is a pre-built constant in PHP. PHP has some other constant like __DIR__, __CLASS__ etc.

Answer:

You can use $_SERVER[‘REQUEST_URI’] to grab the Path, File, and Query of a url such as ( ..dog.php?dep=n/a&title=boss )
from a full url eg. http://www.weeex.com/dog.php?dep=n/a&title=boss

To solve your case:

 //Grab the filename from the uri using the basename function. 

 $request_uri = $_SERVER['REQUEST_URI'] ;
//I am exploding at the  "?" delimiter so that I can get rid of the query I don't need

 $path=explode("?",$request_uri);
 $filename=basename($path[0]);

     //YOUR PHP INCLUDE CODE HERE 
     include $filename ;

this will work to grab the filename even with a complicated url like……”http://www.ex.com/dog.php?dep=n/a&title=boss

I hope this will shed some light

Answer:

Well it depends how you are sending a html file to PHP script.?
If sent in $_GET, Than get file name simply replace .html using str_replace and print it..