Find Nth Level of URL from Current Page

I ran into an interesting need when updating some code for MyQuizWiz, an online quiz and survey system that I developed.

There’s a need to display content generated by the system in users’ Facebook fan pages.. Specifically, there is a page where one of the pages pops up a box with the HTML code for an iframe. The end users would copy the code, and paste it into the configuration for their facebook fan page.

The problem I had was that the page whose URL I needed to display in the pop up was several folders up in the url from the page that displays the link. I don’t necessarily know where the system will be deployed, so the path could include any number of sub-domains or sub-folders that are needed in the URL before you get to my root directory.

I was surprised to see that I didn’t already have a function written to take care of this, but I remedied that this morning.

Let’s break down what happens here.

First, the input parameter. I wanted this to work so that by default, it gives the current URL path, but without any file name or request info (the ?variable=x&varible2=y stuff that sometimes appears at the end). If I pass a one, I want it to go up one level from there; two should go up two levels from there. This can continue indefinitely.

This line gets the full and complete URL of the current page. It’s complicated because it uses either SERVER_NAME or REQUEST_URI in the $_SERVER PHP variable, so that it gets the answer no matter what the version of PHP. It’s also complicated by the fact that it can use either HTTP or HTTPS as the protocol.

The for loop iterates through each of the levels, as passed in the parameter. Each time it runs, this function shortens the path:

substr takes the segment of the string ($path) that starts at position zero, and goes to the position where the last instance of ‘/’ is encountered. The strrpos function is just like the strpos function (finding a particular character or string inside of another string), except that it starts at the back of the string and works forward. This would have been a much more difficult function to write without PHP’s strrpos.

Just for grins, I confirmed that the whole function could also be written in one single line. I opted for the way I wrote it for the sake of readability, but this works as well.

Posted in php, Web Apps | Tagged , , | Leave a comment

Comments are closed.