Use PHP functions in JavaScript

JavaScript file_exists

Returns true if filename exists

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
function file_exists (url) {
    // Returns true if filename exists  
    // 
    // version: 1109.2015
    // discuss at: http://phpjs.org/functions/file_exists    // +   original by: Enrique Gonzalez
    // +      input by: Jani Hartikainen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // %        note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
    // %        note 1: Synchronous so may lock up browser, mainly here for study purposes.     // *     example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
    // *     returns 1: '123'
    var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
    if (!req) {
        throw new Error('XMLHttpRequest not supported');    }
 
    // HEAD Results are usually shorter (faster) than GET
    req.open('HEAD', url, false);
    req.send(null);    if (req.status == 200) {
        return true;
    }
 
    return false;}
external links: original PHP docs | raw js source

Examples

Running

1
file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');

Should return

1
'123'

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have file_exists goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
Jan 6th Permalink

q  To add clarification to my last post regarding your point, using PHP as a proxy will add EXTRA time if you have an Ajax-based application. And even regarding PHP's extra features, HTML5 apps nowadays are doing more of the things you can do on the server (there may even be a standard way to run a proxy on the client-side in the future, with user permission, letting you build your own browser in HTML5).

Gravatar
Brett Zamir
Jan 6th Permalink

q  Hello Ali.MD,

There are indeed client-side uses for checking the existence of a file (though probably adapting this function to accept an asynchronous callback). For example, particularly if your application is interacting with other sites---such as allowing the user to access an API with JSONP or HTML5 cross-domain access (as I was developing in making a site-independent Mediawiki browser client), one might wish to know whether a certain file exists (e.g., to decide the coloring of a link to a wiki page).

The synchronous part of the function is the real problem here, and there is already a disclaimer in the function's notes about the function being for study purposes.

Gravatar
Ali.MD
Jan 6th Permalink

q  its wrong .
you load content of file to check its exist ?!?!
it can very slow in big files, even in 'HEAD' method. (except in nginx servers)
why you don't write an optional php server site script too boost performance and full php feature ?

Gravatar
Felipe
21 Dec '11 Permalink

q  Funny

Gravatar
James 'Skateside' Long
22 May '10 Permalink

q  Blast! Sorry for the double-post but I've just realise that regular expression should only check the beginning of the string so it should be:
/^https?:\/\//i

Gravatar
James 'Skateside' Long
22 May '10 Permalink

q  Hi guys

This is my first contribution to php.js, but I feel that it's an important one.

Firstly, Wikipedia (http://en.wikipedia.org/wiki/Xmlhttprequest) assures us that there are a few more ActiveXObject parameters that can be tried to allow older versions of MSIE to use this function. This can be easily fixed by replacing the ternary opperator on line 14 with a self-executing function to try as many things as possible.

Secondly, checking an absolute URL offline in Firefox throws an NS_ERROR_FAILURE error. I think the best solution to this is to check whether the file location is an absolute reference and whether or not the script is being run online. If the reference is absolute but the script is being run offline, just assume the file exists.

Finally, any status returned that's between 200 and 300 is technically a sucessfull response.

So, with all these in mind, I'd like to propose the following function as the new file_exists(). Please note that I've tweaked this so that it only returns true or false so I can use it in my own scripts - feel free to add your own error handling to the function.

function file_exists(url) {

	// Fire up the AJAX function
	var req = (function() {
		if (typeof XMLHttpRequest == "function") {
			return new XMLHttpRequest();
		} else {
			XMLHttpRequest = function () {
				try {return new ActiveXObject("Msxml2.XMLHTTP.6.0");}catch(e){};
				try {return new ActiveXObject("Msxml2.XMLHTTP.3.0");}catch(e){};
				try {return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){};
				return false;
			};
		}
	}());

	// If we can't use AJAX, or we're offline, we'll have to assume that the image is fine until proved otherwise
	if (!req || (url.match(/https?:\/\//i) && !window.location.href.match(/https?:\/\//i))) {return true;}

	// Send a 'HEAD' request since it's faster than 'GET' and 'POST'
	req.open('HEAD', url, false);
	req.send(null);

	// Any status in the 200 range is a successful request
	return (req.status >= 200 && req.status < 300);
}

Gravatar
Kevin van Zonneveld
18 Nov '08 Permalink

q  @ frame: This could happen if you are writing multiple comments at the same time, cause only one allowed security key is remembered per user. Could this be your case as well?

Gravatar
frame
18 Nov '08 Permalink

q  Do you have updated the link? I downloaded the lib some time before and the function was not included.. now it is o.O

Another Bug?: The security code i typed in was not valid.. for 3 times.. and also did not reload to another code.. always the same..

Gravatar
Kevin van Zonneveld
14 Nov '08 Permalink

q  @ frame: But it is, what link are you using?

Gravatar
frame
14 Nov '08 Permalink

q  The function file_exists isn't avaiable in php.js.


Contribute a New function

More functions

In this category

basename
dirname
fclose
feof
fgetc
fgetcsv
fgets
fgetss
file
» file_exists
file_get_contents
filemtime
filesize
fopen
fpassthru
fread
fscanf
fseek
ftell
pathinfo
pclose
popen
readfile
realpath
rewind

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !