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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
lharby
  • 3,057
  • 5
  • 24
  • 56
  • 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... – Populus Jul 10 '13 at 16:08
  • That URL has no filename to get. Could you explain why you are trying to this? – loganfsmyth Jul 10 '13 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. – lharby Jul 10 '13 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. – dandavis Jul 10 '13 at 16:39

1 Answers1

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.

Aleks G
  • 56,435
  • 29
  • 168
  • 265