5

I am trying to get the current filename from the url using:

$currentFile = window.location.pathname.split("/").pop();

This works fine if the full path is something like:

http://www.yoursite.com/folder/index.php

It will return index.php, index.cfm, index.html etc.

But when the url is http://www.yoursite.com/folder/

I cannot retrieve the current filename, is this possible via js or jquery?

4
  • 1
    No because the default index file is a setting within the webserver. You can make an assumption and just say it's index.html if you're loading a folder... Commented Jul 10, 2013 at 16:08
  • That URL has no filename to get. Could you explain why you are trying to this? Commented Jul 10, 2013 at 16:08
  • Yes, I am using jquery to show/hide elements within a particular folder structure /contact but not for the index.php file, or only for the index.php file for example. Commented Jul 10, 2013 at 16:10
  • if you NEED to know, you can just try fetching HEADs on all the default document names, in order of probability: index.html, index.htm, index.php, default.aspx, default.asp, etc. the first one that doesn't 404 is the right url. Commented Jul 10, 2013 at 16:39

1 Answer 1

5

If you only have the path in the URL, then you cannot get the filename from it - not using jQuery, not using any other client-side method. This is because only the server that sends this file knows what this file is. Specifically, in the web server configuration, there's a directive, which indicates what filename to search for if only the directory name is specified. For example, in apache this can be

DirectoryIndex index.html index.php home.htm

This tells the server that for requests with only a directory name the server will attempt to serve file index.html from that directory; if it doesn't exist, then index.php; if that also doesn't exist then home.htm. If that one also doesn't exist, then the behaviour depends on other configuration options. Other web server software has similar configuration options.

Hence, when you send a request like http://www.yoursite.com/folder/ to a server, only that server will know what file is actually used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.