Advertisement
ssaidz

post curl json

Nov 26th, 2024
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.78 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Form CURL JSON</title>
  7. </head>
  8. <body>
  9.     <h1>Submit URL untuk Mendapatkan JSON</h1>
  10.     <form method="POST" action="">
  11.         <label for="url">Masukkan URL JSON:</label><br>
  12.         <input type="url" id="url" name="url" required placeholder="https://example.com/data.json"><br><br>
  13.         <button type="submit">Submit</button>
  14.     </form>
  15.  
  16.     <?php
  17.     if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['url'])) {
  18.         $url = filter_var($_POST['url'], FILTER_SANITIZE_URL);
  19.  
  20.         // Validasi URL
  21.         if (filter_var($url, FILTER_VALIDATE_URL)) {
  22.             // Inisialisasi cURL
  23.             $ch = curl_init();
  24.  
  25.             // Konfigurasi cURL
  26.             curl_setopt($ch, CURLOPT_URL, $url);
  27.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  28.  
  29.             // Eksekusi cURL
  30.             $response = curl_exec($ch);
  31.  
  32.             // Cek error
  33.             if (curl_errno($ch)) {
  34.                 echo "<p>cURL Error: " . curl_error($ch) . "</p>";
  35.             } else {
  36.                 // Decode JSON
  37.                 $data = json_decode($response, true);
  38.  
  39.                 if (json_last_error() === JSON_ERROR_NONE) {
  40.                     echo "<h2>Hasil JSON:</h2>";
  41.                     echo "<pre>" . htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT)) . "</pre>";
  42.                 } else {
  43.                     echo "<p>JSON Error: " . json_last_error_msg() . "</p>";
  44.                 }
  45.             }
  46.  
  47.             // Tutup cURL
  48.             curl_close($ch);
  49.         } else {
  50.             echo "<p>URL tidak valid. Silakan masukkan URL yang benar.</p>";
  51.         }
  52.     }
  53.     ?>
  54. </body>
  55. </html>
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement