---
layout: page
title: "JavaScript file_exists function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/file_exists:399
- /functions/view/file_exists
- /functions/view/399
- /functions/file_exists:399
- /functions/399
---
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's file_exists

{% codeblock filesystem/file_exists.js lang:js https://raw.github.com/kvz/phpjs/master/functions/filesystem/file_exists.js raw on github %}
function file_exists (url) {
  // http://kevin.vanzonneveld.net
  // +   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;
}
{% endcodeblock %}

 - [view on github](https://github.com/kvz/phpjs/blob/master/functions/filesystem/file_exists.js)
 - [edit on github](https://github.com/kvz/phpjs/edit/master/functions/filesystem/file_exists.js)

### Example 1
This code
{% codeblock lang:js example %}
file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
{% endcodeblock %}

Should return
{% codeblock lang:js returns %}
'123'
{% endcodeblock %}


### Other PHP functions in the filesystem extension
{% render_partial _includes/custom/filesystem.html %}
