Can you suggest an alternative to the PHP function file_get_contents in javascript?

  • What files do you want to receive using javascript? - Visman
  • Text Files - Armen
  • more precisely, from the php file - Armen
  • one
    You get cross-domain ajax. Read about CORS ru.wikipedia.org/wiki/Cross-origin_resource_sharing and learn.javascript.ru/xhr-crossdomain If the remote server is denied access from other domains, then you have a problem. But maybe on that server there is an open API for accessing it. Then you need to use it. - Visman
  • one
    for this there is a cors proxy - ivan0biwan

2 answers 2

You can use this feature.

 function httpGet(theUrl){ var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); xmlHttp.send( null ); return xmlHttp.responseText; } httpGet("some url"); 

If the site does not allow to read, you can use cors proxy (for example https://cors-anywhere.herokuapp.com/ )

     window.xhr = (url,callBack) => { let xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { if (xhr.status === 200) { callBack(xhr.responseText); } } }; xhr.send(); } xhr("http://site.domen/",(data) => { }); 

    If the request is sent to another domain to which there is no access ( Access-Control-Allow-Origin ), create a php file with the contents

     $ch = curl_init($_GET['url']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); echo curl_exec($ch); curl_close($ch); 

    And request data using it.

     xhr("get.php?url="+url,(data) => { }); 

    Also, for convenience, you can simply add a line in the xhr function and access it without the get.php?url= prefix in the first argument (as in the first example)

     xhr.open("GET", "get.php?url="+url);