Skip to content
Advertisement

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

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.

Advertisement

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement