Como faço uma solicitação HTTP em Javascript e PHP?

Dec 15 2022
Para fazer uma solicitação HTTP em JavaScript, você pode usar o objeto XMLHttpRequest ou a API de busca mais recente. Aqui está um exemplo usando XMLHttpRequest: Observe que a API de busca é suportada apenas em navegadores modernos, então você pode precisar usar um polyfill ou voltar a usar XMLHttpRequest para navegadores mais antigos.

Para fazer uma solicitação HTTP em JavaScript, você pode usar o XMLHttpRequestobjeto ou a fetchAPI mais recente.

Aqui está um exemplo usando XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.example.com/', true);

xhr.onload = function() {
  if (this.status == 200) {
    var data = JSON.parse(this.response);
    console.log(data);
  }
};

xhr.send();

fetch('https://www.example.com/')
  .then(response => response.json())
  .then(data => console.log(data));

Observe que a fetchAPI é suportada apenas em navegadores modernos, então você pode precisar usar um polyfill ou voltar a usar XMLHttpRequestpara navegadores mais antigos.

E para fazer uma solicitação HTTP em PHP, você pode usar a função interna file_get_contents() ou a biblioteca cURL mais robusta.

Usando file_get_contents():

<?php
  // Set the URL of the request
  $url = 'http://www.example.com';
  
  // Send the request and store the response
  $response = file_get_contents($url);
  
  // Check for errors
  if($response === false) {
    // Handle error
  } else {
    // Use the response
  }
?>

<?php 
    // Initialize cURL
    $ch = curl_init();
    
    // Set the URL of the request
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com');
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects
    
    // Send the request and store the response
    $response = curl_exec($ch);
    
    // Check for errors
    if(curl_errno($ch)) {
      // Handle error
    } else {
      // Use the response
    }
    
    // Close the cURL handle
    curl_close($ch);
?>