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 25 | function file_exists (url) { // Returns true if filename exists // // version: 909.322 // 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; } |
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.

Do you have updated the link? I downloaded the lib some time before and the function was not included.. now it is o.O 
Kevin van Zonneveld
18 Nov '08