<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/functions.php';

$page_title   = 'Ping Test – Measure Response Time of a Website or IP';
$page_desc    = 'Free Ping Test: measure the response time of any website or IP address from Düsseldorf, Germany – fast and free on ipcheck.tools.';
$page_current = 'ping';

$query   = trim(strip_tags($_GET['host'] ?? ''));
$results = [];
$error   = '';
$avg_ms  = 0;
$min_ms  = 0;
$max_ms  = 0;
$loss    = 0;

if ($query) {
    $host = preg_replace('/^https?:\/\//i', '', $query);
    $host = explode('/', $host)[0];
    $host = rtrim($host, '/');

    $ip = '';
    if (filter_var($host, FILTER_VALIDATE_IP)) {
        $ip = $host;
    } else {
        $ip = @gethostbyname($host);
        if ($ip === $host) {
            $error = 'Host could not be resolved. Please check your input.';
            $ip    = '';
        }
    }

    if ($ip && !$error) {
        $attempts = 4;
        $times    = [];

        for ($i = 0; $i < $attempts; $i++) {
            $start_t = microtime(true);
            $fp = @fsockopen('udp://' . $ip, 53, $errno, $errstr, 2);
            if ($fp) {
                stream_set_timeout($fp, 1, 0);
                @fwrite($fp, "\x00\x01\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x01");
                $resp = @fread($fp, 512);
                $ms   = round((microtime(true) - $start_t) * 1000, 1);
                fclose($fp);
                if ($resp !== false && strlen($resp) > 0 && $ms < 900) {
                    $times[]   = $ms;
                    $results[] = ['seq' => $i + 1, 'ms' => $ms, 'status' => 'ok'];
                } else {
                    $results[] = ['seq' => $i + 1, 'ms' => null, 'status' => 'timeout'];
                    $loss++;
                }
            } else {
                $results[] = ['seq' => $i + 1, 'ms' => null, 'status' => 'timeout'];
                $loss++;
            }
            usleep(200000);
        }

        if (count($times) > 0) {
            $avg_ms = round(array_sum($times) / count($times), 1);
            $min_ms = min($times);
            $max_ms = max($times);
        }
        $loss_pct = round(($loss / $attempts) * 100);
    }
}

require_once __DIR__ . '/header.php';
?>

<div class="hero">
  <div class="hero-label">Tool</div>
  <div class="hero-title">Ping Test</div>
  <div class="hero-sub">
    Measure response time · Location:
    <img src="https://flagcdn.com/20x15/de.png" width="20" height="15" alt="DE"
         style="vertical-align:middle; border-radius:2px; margin:0 3px;">
    Düsseldorf, Germany
  </div>
  <form method="GET" action="/en/ping.php" onsubmit="startPingLoading()">
    <div class="input-group">
      <input class="input-text" type="text" name="host"
             value="<?= h($query) ?>"
             placeholder="e.g. google.com or 8.8.8.8"
             required />
      <button type="submit" class="btn btn-primary" id="ping-btn">
        <span id="ping-btn-content"><i class="ti ti-activity"></i> Start Ping</span>
        <span id="ping-btn-spinner" style="display:none; align-items:center; gap:8px;">
          <svg style="animation:apple-spin 1s linear infinite;" viewBox="0 0 24 24" width="18" height="18">
            <circle cx="12" cy="12" r="9" fill="none" stroke="rgba(147,197,253,0.2)" stroke-width="2.5"/>
            <path d="M12 3 A9 9 0 0 1 21 12" fill="none" stroke="#93c5fd" stroke-width="2.5" stroke-linecap="round"/>
          </svg>
          Pinging...
        </span>
      </button>
    </div>
  </form>
</div>

<div class="wrap">

  <div class="ad-slot"><ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-8287576653347400" data-ad-slot="2715725452" data-ad-format="auto" data-full-width-responsive="true"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>

  <?php if ($error): ?>
    <div class="alert alert-danger"><i class="ti ti-alert-circle"></i><span><?= h($error) ?></span></div>

  <?php elseif ($query && $results): ?>

    <div class="alert alert-info">
      <i class="ti ti-map-pin"></i>
      <span>This ping test is performed from our server in
        <img src="https://flagcdn.com/20x15/de.png" width="20" height="15" alt="DE"
             style="vertical-align:middle; border-radius:2px; margin:0 3px;">
        <strong>Düsseldorf, Germany</strong>.
      </span>
    </div>

    <div class="stat-grid">
      <div class="stat">
        <div class="stat-val" style="color:<?= $avg_ms > 0 ? ($avg_ms < 50 ? 'var(--green)' : ($avg_ms < 150 ? 'var(--orange)' : 'var(--red)')) : 'var(--text4)' ?>;">
          <?= $avg_ms > 0 ? $avg_ms . ' ms' : '–' ?>
        </div>
        <div class="stat-key">Avg. Response</div>
      </div>
      <div class="stat">
        <div class="stat-val" style="color:var(--green);"><?= $min_ms > 0 ? $min_ms . ' ms' : '–' ?></div>
        <div class="stat-key">Minimum</div>
      </div>
      <div class="stat">
        <div class="stat-val" style="color:var(--orange);"><?= $max_ms > 0 ? $max_ms . ' ms' : '–' ?></div>
        <div class="stat-key">Maximum</div>
      </div>
      <div class="stat">
        <div class="stat-val" style="color:<?= $loss_pct > 0 ? 'var(--red)' : 'var(--green)' ?>;"><?= $loss_pct ?>%</div>
        <div class="stat-key">Packet Loss</div>
      </div>
    </div>

    <div class="grid2">
      <div class="card card-blue">
        <div class="card-title"><i class="ti ti-activity"></i> Ping Results</div>
        <table class="result-table">
          <thead><tr><th>#</th><th>Target</th><th style="text-align:right;">Time</th><th style="text-align:right;">Status</th></tr></thead>
          <tbody>
            <?php foreach ($results as $r): ?>
            <tr>
              <td class="mono" style="color:var(--text4);"><?= $r['seq'] ?></td>
              <td class="mono" style="font-size:11px;"><?= h($ip) ?></td>
              <td class="mono" style="text-align:right; color:<?= $r['status'] === 'ok' ? ($r['ms'] < 50 ? 'var(--green)' : ($r['ms'] < 150 ? 'var(--orange)' : 'var(--red)')) : 'var(--red)' ?>;">
                <?= $r['status'] === 'ok' ? $r['ms'] . ' ms' : 'Timeout' ?>
              </td>
              <td style="text-align:right;">
                <?= $r['status'] === 'ok' ? '<span class="badge badge-green">OK</span>' : '<span class="badge badge-red">Timeout</span>' ?>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <div class="card">
        <div class="card-title"><i class="ti ti-server"></i> Host Information</div>
        <?php
        $host_geo = get_geoip($ip);
        $hostname = get_hostname($ip);
        ?>
        <div class="data-row"><span class="dk">Input</span><span class="dv mono"><?= h($query) ?></span></div>
        <div class="data-row"><span class="dk">Resolved IP</span><span class="dv mono blue"><?= h($ip) ?></span></div>
        <div class="data-row"><span class="dk">Hostname</span><span class="dv mono" style="font-size:11px;"><?= h($hostname ?: '–') ?></span></div>
        <div class="data-row"><span class="dk">Provider</span><span class="dv"><?= h($host_geo['isp'] ?: $host_geo['asn_org'] ?: '–') ?></span></div>
        <div class="data-row"><span class="dk">Location</span><span class="dv">
          <?= $host_geo['country_iso'] ? country_flag($host_geo['country_iso']) : '' ?>
          <?= h(($host_geo['city'] ? $host_geo['city'] . ', ' : '') . ($host_geo['country'] ?: '–')) ?>
        </span></div>
        <div class="data-row"><span class="dk">ASN</span><span class="dv mono"><?= h($host_geo['asn'] ?: '–') ?></span></div>
      </div>
    </div>

    <div class="card">
      <div class="card-title"><i class="ti ti-chart-bar"></i> Rating</div>
      <div class="data-row">
        <span class="dk">Reachability</span>
        <span class="dv" style="color:<?= count($results) > $loss ? 'var(--green)' : 'var(--red)' ?>;">
          <?= count($results) > $loss ? 'Reachable' : 'Not reachable' ?>
        </span>
      </div>
      <div class="data-row">
        <span class="dk">Latency rating</span>
        <span class="dv" style="color:<?= $loss_pct === 100 ? 'var(--red)' : ($avg_ms < 50 ? 'var(--green)' : ($avg_ms < 100 ? 'var(--orange)' : 'var(--red)')) ?>;">
          <?php
          if ($loss_pct === 100)   echo 'Not reachable';
          elseif ($avg_ms === 0.0) echo '–';
          elseif ($avg_ms < 20)    echo 'Excellent (under 20 ms)';
          elseif ($avg_ms < 50)    echo 'Very good (under 50 ms)';
          elseif ($avg_ms < 100)   echo 'Good (under 100 ms)';
          elseif ($avg_ms < 200)   echo 'Acceptable (under 200 ms)';
          else                     echo 'High (over 200 ms)';
          ?>
        </span>
      </div>
      <div class="data-row">
        <span class="dk">Jitter</span>
        <span class="dv mono"><?= $min_ms > 0 ? round($max_ms - $min_ms, 1) . ' ms' : '–' ?></span>
      </div>
    </div>

    <div class="card">
      <div class="card-title"><i class="ti ti-arrow-right"></i> Continue with</div>
      <div style="display:flex; gap:8px; flex-wrap:wrap;">
        <a href="/en/ip-lookup.php?ip=<?= urlencode($ip) ?>" class="btn btn-primary" style="font-size:12px; padding:6px 14px;">
          <i class="ti ti-world-search"></i> IP Lookup
        </a>
        <a href="/en/blacklist.php?ip=<?= urlencode($ip) ?>" class="btn btn-primary" style="font-size:12px; padding:6px 14px; background:#1e1a3a; border-color:#3d3080; color:var(--purple-dim);">
          <i class="ti ti-shield-search"></i> Blacklist Check
        </a>
        <a href="/en/port-check.php?host=<?= urlencode($query) ?>" class="btn btn-ghost" style="font-size:12px; padding:6px 14px;">
          <i class="ti ti-plug"></i> Port Check
        </a>
      </div>
    </div>

  <?php elseif (!$query): ?>
    <div class="alert alert-info">
      <i class="ti ti-info-circle"></i>
      <span>Enter a domain or IP address to start the ping test. The test is performed from our server in <strong>Düsseldorf, Germany</strong>.</span>
    </div>
  <?php endif; ?>

  <div class="ad-slot"><ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-8287576653347400" data-ad-slot="2715725452" data-ad-format="auto" data-full-width-responsive="true"></ins><script>(adsbygoogle = window.adsbygoogle || []).push({});</script></div>

  <div class="tools-row">
    <a href="/en/"                class="tool-btn"><i class="ti ti-home"></i><span>My IP</span></a>
    <a href="/en/ping.php"        class="tool-btn current"><i class="ti ti-activity"></i><span>Ping Test</span></a>
    <a href="/en/port-check.php"  class="tool-btn"><i class="ti ti-plug"></i><span>Port Check</span></a>
    <a href="/en/ip-lookup.php"   class="tool-btn"><i class="ti ti-world-search"></i><span>IP Lookup</span></a>
    <a href="/en/dns-lookup.php"  class="tool-btn"><i class="ti ti-search"></i><span>DNS Lookup</span></a>
  </div>

  <div class="seo-box">
    <h2>What does the ping test measure?</h2>
    <p>The ping test measures the <strong>response time</strong> (latency) between our server in Düsseldorf and the specified target. 4 connection attempts are made and minimum, maximum and average are calculated. A low ping means a fast, responsive connection – ideal values for web servers are under 50 ms within Europe. Note: since this test is started from our server, it measures the reachability of the target from the German internet – not your personal ping.</p>
  </div>

<style>@keyframes apple-spin { from { transform:rotate(0deg); } to { transform:rotate(360deg); } }</style>
<script>
function startPingLoading() {
  document.getElementById('ping-btn-content').style.display = 'none';
  document.getElementById('ping-btn-spinner').style.display = 'inline-flex';
}
</script>

<?php require_once __DIR__ . '/footer.php'; ?>
