Build A PHP Website Speed Test With The PageSpeed API

Website performance affects rankings, conversions and customer trust. A slow page can be especially frustrating for Australian users switching between home NBN connections, mobile data and public Wi-Fi. A lightweight speed test tool gives visitors a practical way to inspect their websites without leaving your platform.

Google’s PageSpeed Insights API provides the testing engine. Your PHP application sends a page URL to the API, receives Lighthouse performance data, and displays useful results such as the performance score, Largest Contentful Paint and cumulative layout shift.

This approach is suitable for a hosting blog, web development agency, SEO platform or VTU-related business that wants to offer a free utility. It also creates an opportunity to attract website owners who may later need hosting, optimisation, copywriting or technical support.

The example below uses plain PHP, cURL and a simple HTML form. You can run it on shared hosting, a VPS or a local development environment before adding a database, user accounts or more advanced reporting.

Prepare The API And PHP Environment

Create a Google Cloud project, enable the PageSpeed Insights API and generate an API key. The API has quotas, so check the current Google Cloud pricing and usage rules before launching a public tool. For a small website, the free quota may be enough, but unlimited public requests should never be assumed.

Keep the key on the server. Do not place it inside JavaScript, visible HTML or a downloadable file. Store it in an environment variable where possible:

$apiKey = getenv('PAGESPEED_API_KEY');

if (!$apiKey) {
    throw new RuntimeException('PageSpeed API key is not configured.');
}

Your server should support PHP 8 or a recent supported version, cURL and JSON. Test the setup with a command such as php -m and confirm that both curl and json are available. On shared hosting, these extensions are commonly enabled, although the exact controls vary between providers in Sydney, Melbourne, Brisbane and regional areas.

A production tool also needs HTTPS, sensible request limits and a clear privacy notice. If you collect submitted URLs, email addresses or IP addresses, consider your obligations under Australia’s Privacy Act 1988 and the Australian Privacy Principles. Avoid storing more information than the tool needs.

Create A Safe URL Submission Form

Start with a form that accepts one website address and lets the visitor choose mobile or desktop testing. Mobile testing should be the default because many Australians browse while commuting, shopping or comparing services on smartphones.

<form method="post" action="">
    <label for="url">Website URL</label>
    <input
        type="url"
        id="url"
        name="url"
        placeholder="https://example.com"
        required
    >

    <label for="strategy">Test device</label>
    <select id="strategy" name="strategy">
        <option value="mobile">Mobile</option>
        <option value="desktop">Desktop</option>
    </select>

    <button type="submit">Test performance</button>
</form>

Validate the submitted value before sending it to Google. filter_var() checks the basic URL format, while parse_url() lets you restrict requests to HTTP and HTTPS. This prevents malformed input and makes your application easier to maintain.

$url = trim($_POST['url'] ?? '');
$strategy = $_POST['strategy'] ?? 'mobile';

if (!filter_var($url, FILTER_VALIDATE_URL)) {
    exit('Please enter a valid website address.');
}

$parts = parse_url($url);

if (
    !$parts ||
    !in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true)
) {
    exit('Only HTTP and HTTPS addresses are supported.');
}

if (!in_array($strategy, ['mobile', 'desktop'], true)) {
    $strategy = 'mobile';
}

For a public service, add CSRF protection, a timeout and rate limiting. You can also reject private IP ranges if your application ever fetches URLs directly. In this design, Google performs the page audit, but input validation still reduces abuse and confusing errors.

Send The Request Through PHP

The PageSpeed Insights endpoint accepts the page URL, testing strategy, selected Lighthouse categories and API key. URL-encode the query parameters with http_build_query() rather than concatenating user input manually.

$params = [
    'url' => $url,
    'strategy' => $strategy,
    'category' => ['performance', 'accessibility', 'best-practices', 'seo'],
    'key' => $apiKey,
];

$endpoint = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?'
          . http_build_query($params);

$ch = curl_init($endpoint);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($response === false || $curlError) {
    exit('The speed test could not be completed.');
}

$data = json_decode($response, true);

if ($httpCode >= 400 || !is_array($data)) {
    $message = $data['error']['message'] ?? 'The PageSpeed service returned an error.';
    exit(htmlspecialchars($message, ENT_QUOTES, 'UTF-8'));
}

The request can take several seconds because Google loads and audits the submitted page. Display a loading message after form submission, or use AJAX if you want a smoother interface. Set a reasonable server timeout so a stalled test does not consume PHP workers indefinitely.

Google may return data from Lighthouse and, when available, Chrome User Experience Report field data. Lab metrics are generated during the test, while field metrics represent real-user experiences. A page can score well in a lab run but still need improvement for visitors using slower mobile connections or older devices.

Read Scores And Core Web Vitals

The main category score is stored as a decimal between zero and one. Convert it to a percentage before displaying it:

$performance = $data['lighthouseResult']['categories']['performance']['score']
    ?? null;

$performancePercent = $performance !== null
    ? round($performance * 100)
    : null;

$audits = $data['lighthouseResult']['audits'] ?? [];

$lcp = $audits['largest-contentful-paint']['displayValue'] ?? 'Unavailable';
$cls = $audits['cumulative-layout-shift']['displayValue'] ?? 'Unavailable';
$tbt = $audits['total-blocking-time']['displayValue'] ?? 'Unavailable';

Useful metrics include Largest Contentful Paint, which indicates loading speed; Cumulative Layout Shift, which indicates visual stability; and Total Blocking Time, which reflects how long scripts keep the page from responding. You can also display First Contentful Paint and Speed Index.

Render values with escaping:

echo '<h2>Performance: ' . htmlspecialchars(
    (string) $performancePercent,
    ENT_QUOTES,
    'UTF-8'
) . '/100</h2>';

echo '<p>Largest Contentful Paint: ' . htmlspecialchars($lcp) . '</p>';
echo '<p>Cumulative Layout Shift: ' . htmlspecialchars($cls) . '</p>';
echo '<p>Total Blocking Time: ' . htmlspecialchars($tbt) . '</p>';

Do not present a single score as a complete verdict. Explain that results vary according to server location, caching, page content and test conditions. An online store serving customers in Perth may experience different real-world conditions from a brochure site hosted near Sydney, particularly for visitors using mobile networks or distant data centres.

You can show the SEO, accessibility and best-practices scores as separate cards. This makes the tool more useful than a generic green, amber or red label and gives visitors clear areas to investigate.

Turn Results Into Helpful Recommendations

A speed test should explain what to do next. Use the audit data to list failed or warning audits, but avoid dumping every technical detail on beginners. Select a few high-impact items and link to documentation or an internal tutorial.

$importantAudits = [
    'render-blocking-resources',
    'unused-javascript',
    'uses-optimized-images',
    'uses-text-compression',
];

foreach ($importantAudits as $auditId) {
    $audit = $audits[$auditId] ?? null;

    if ($audit && in_array($audit['score'] ?? 1, [0, 0.5], true)) {
        echo '<p><strong>'
            . htmlspecialchars($audit['title'], ENT_QUOTES, 'UTF-8')
            . ':</strong> '
            . htmlspecialchars($audit['description'], ENT_QUOTES, 'UTF-8')
            . '</p>';
    }
}

Common recommendations include converting oversized images to WebP or AVIF, removing unused plugins, deferring non-essential JavaScript, enabling Brotli or gzip compression and improving server response time. WordPress users may need to review themes and plugins, while custom PHP sites may need application-level caching.

Performance advice should account for the visitor’s market. A local tradesperson in Adelaide may care most about fast contact pages and map embeds, while an ecommerce business selling across Australia needs fast product, cart and checkout pages. Avoid recommending aggressive optimisation that breaks forms, analytics or accessibility.

Content can help turn a one-time test into repeat traffic. A guide on weekly email newsletters can support a simple follow-up system that sends users performance tips, provided they actively opt in. Marketing emails in Australia must also follow the Spam Act 2003, including consent and unsubscribe requirements.

Add Features Before Publishing

Once the basic request and response work, improve the interface and protect your hosting resources. A simple result page is enough for a first release, but carefully chosen features can make the utility more valuable.

Practical Features To Add

Use prepared database statements if you save test history. Never trust audit titles, descriptions or submitted URLs as safe HTML. Escape output consistently, and set a content security policy where practical.

Before launch, test pages with redirects, password protection, large images, blocked robots rules and JavaScript-heavy frameworks. Check API failures, invalid keys, quota errors and slow responses. Test the layout on a phone commonly used by your audience, since many Australian customers will access the tool over mobile data rather than a desktop connection.

A good landing page should explain what the score means, identify whether the test is mobile or desktop, and clarify that Google’s result is an automated assessment. If your business promotes web development or SEO services, place relevant internal links beside the recommendations without making the free tool feel like a sales gate.

Publish the PHP files over HTTPS, keep the API key outside the web root and monitor logs for repeated abuse. Review the PageSpeed API documentation periodically because response fields, quotas and Google’s reporting behaviour can change.

Use this foundation to launch a focused performance checker, then improve it with caching, accessible reporting and practical Australian website advice. Start with one secure PHP endpoint and a clean result page, measure how visitors use it, and turn the most requested diagnostics into your next development release.