Skip to content

Google Search API in PHP: Get Google Results with cURL

Page 2 of Google restarts its position count at 1, so rank 3 there is really 13. Fetch Google results in PHP with plain cURL and the JustSERP API: correct rank maths, a 90 second timeout, retries and parallel searches with curl_multi.

Google Search API in PHP: Get Google Results with cURL

Send "country": "UK" to our API and you will get a perfectly normal response full of American results. We match countries by their full English name, so "UK" is not recognised and the search quietly falls back to the United States. Nothing errors, the call is used, and the data is wrong. I'll show you how to pull Google results into PHP with plain cURL and the JustSERP API, and how to get the rank maths, the timeouts and the parallel requests right. Only the cURL and JSON extensions are needed, so there is no Composer package to add.

PHP code calling the JustSERP API with cURL

What you need

  • PHP 7.4 or newer with the curl and json extensions enabled.
  • A JustSERP API key. Sign up, then copy the key from your dashboard.

Keep the key out of your source code. Set it as an environment variable (in your web server or PHP-FPM pool config, or a .env loader you already use):

export JUSTSERP_API_KEY="your-key-here"

Call the API from your server only. Never put the key in JavaScript or HTML that reaches a visitor's browser. Run the search in PHP and send your own front end the results.

How a request works

You send a keyword and any options as JSON to https://api.justserp.com/v1/search. We fetch the Google results page, parse it, and return clean JSON. One request returns one results page, typically in 2 to 4 seconds. Typically is not always: when Google pushes back, we retry the fetch before giving up, so a hard query can take well over a minute. That matters for the client timeout, which I'll come back to below.

Two things we do on every request, so you don't have to: we ask Google for unfiltered results (no "similar results omitted" notice) and we switch off personalisation, so you see the plain list rather than one shaped by someone's search history. There is no response cache either. Every call is a fresh fetch from Google.

Diagram: your PHP code sends a POST request to JustSERP, which returns parsed JSON

Your first request

Send the key in the X-API-Key header and the search in the JSON body. Only keyword is required.

<?php
$ch = curl_init("https://api.justserp.com/v1/search");
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 90,
    CURLOPT_HTTPHEADER     => [
        "X-API-Key: " . getenv("JUSTSERP_API_KEY"),
        "Content-Type: application/json",
    ],
    CURLOPT_POSTFIELDS     => json_encode(["keyword" => "best coffee grinder"]),
]);

$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);

if ($body === false || $status !== 200) {
    exit("Request failed with status $status: $body\n");
}

$data = json_decode($body, true);
foreach ($data["organic_results"] ?? [] as $result) {
    echo $result["position"], ". ", $result["title"], "\n";
    echo "    ", $result["link"], "\n";
}

Set CURLOPT_TIMEOUT to 90 seconds, not 30. Our side can keep working on a difficult query for over a minute. If your client hangs up first, the call is still counted and you lose the answer, which is the worst of both outcomes. A timeout also stops a stuck connection from holding a PHP worker until the server's execution limit.

What comes back

The answer is a JSON object. A block only appears when Google showed it on that page, so always read optional blocks with ?? [].

{
  "meta": {
    "status": 200,
    "query": "best coffee grinder",
    "device": "desktop",
    "googleURL": "https://www.google.com/search?...",
    "params": { "keyword": "best coffee grinder" },
    "time_taken": "3.41"
  },
  "totalResults": 48200000,
  "organic_results": [
    { "position": 1, "title": "...", "link": "https://...", "description": "..." }
  ],
  "paid_ads": [ { "position": 1, "title": "...", "link": "...", "description": "..." } ],
  "related_questions": [ "What is the best grinder for espresso?" ],
  "related_search": [ "best burr coffee grinder" ],
  "knowledge_graph": { "title": "...", "description": "..." },
  "inline_videos": [ { "position": 1, "source": "..." } ]
}
$organic  = $data["organic_results"] ?? [];
$ads      = $data["paid_ads"] ?? [];
$questions = $data["related_questions"] ?? [];
$knowledge = $data["knowledge_graph"] ?? null;

echo count($organic), " organic results, ", count($ads), " ads\n";
foreach ($questions as $question) {
    echo "People also ask: $question\n";
}

A few details that catch people out. paid_ads is one list in page order, with no flag for top or bottom. related_questions holds the question text only, because Google loads the answers when a question is opened. On device: "mobile" the answer has no inline_videos and no totalResults. And totalResults is Google's own estimate, which can be surprisingly small.

A reusable function and the advanced parameters

Every option goes in the same JSON body. This function wraps the request, merges any options you pass, and throws on failure. The rest of the guide builds on it.

<?php
const JUSTSERP_URL = "https://api.justserp.com/v1/search";

class JustSerpException extends RuntimeException
{
    public function __construct(string $message, public int $status = 0)
    {
        parent::__construct($message, $status);
    }
}

function justserp_handle(string $keyword, array $options = [])
{
    $ch = curl_init(JUSTSERP_URL);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT        => 90,
        CURLOPT_HTTPHEADER     => [
            "X-API-Key: " . getenv("JUSTSERP_API_KEY"),
            "Content-Type: application/json",
        ],
        CURLOPT_POSTFIELDS     => json_encode(["keyword" => $keyword] + $options),
    ]);
    return $ch;
}

function justserp_search(string $keyword, array $options = []): array
{
    $ch = justserp_handle($keyword, $options);
    $body = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($body === false) {
        throw new JustSerpException("Network error: $error");
    }
    if ($status !== 200) {
        throw new JustSerpException("HTTP $status: $body", $status);
    }
    return json_decode($body, true);
}

The promoted constructor property needs PHP 8.0. On PHP 7.4, declare public int $status; in the class and assign it in the constructor instead.

Table of JustSERP request parameters with defaults and descriptions

Country, language and location

country (default "United States") and language (default "English") take full English names such as "United Kingdom" or "Germany", never codes like "UK" or "de". The trap here is that a name we don't recognise is not an error. It quietly falls back to United States and English, and the call is still used. If results look oddly American, check meta.googleURL and meta.params in the answer.

For "near me" searches use location, a city in Google's canonical City,Region,Country form. We turn it into Google's uule parameter as-is and do not validate it. A misspelled location is not rejected: Google just ignores it, you get non-local results, and the call is used. Copy canonical names exactly. location also does not change the Google domain or language, so send a matching country as well when you track a local market. You can send a ready-made uule string too, though location wins when both are present.

$french = justserp_search("assurance auto", [
    "country"  => "France",
    "language" => "French",
]);

$local = justserp_search("plumber near me", [
    "country"  => "United States",
    "location" => "Austin,Texas,United States",
]);

Pagination, devices, time filters and exact queries

page: 2 returns the second page. It overrides start: page N becomes start=(N-1)*10. Each page uses one API call. Position restarts at 1 on every page, so the absolute rank is (page - 1) * 10 + position. That holds when Google returned a full ten organic results on the page, and it sometimes returns fewer.

device is "desktop" or "mobile". tbs is passed straight to Google, so qdr:d is the past day and qdr:w the past week. nfpr set to "1" turns off Google's auto-correction. Both tbs and nfpr must be strings: sending the number 1 fails validation.

$ranks = [];
foreach ([1, 2, 3] as $page) {
    $data = justserp_search("project management software", ["page" => $page, "device" => "mobile"]);
    foreach ($data["organic_results"] ?? [] as $item) {
        $rank = ($page - 1) * 10 + $item["position"];
        $ranks[$item["link"]] ??= $rank;
    }
}
asort($ranks);
foreach (array_slice($ranks, 0, 5, true) as $link => $rank) {
    echo "$rank  $link\n";
}

$news  = justserp_search("openai announcement", ["tbs" => "qdr:d"]);
$exact = justserp_search("justserp", ["nfpr" => "1"]);

Pass "html" => true to get the raw Google page in an html field as well. Responses get much larger, so only use it when you need it. The q alias also works in place of keyword. Unknown fields are ignored without a warning, so a typo like contry silently does nothing.

Handling errors, and what is billed

Check the HTTP status before you read the body:

StatusMeaningWhat to do
200Success. One API call is used.Read the results.
400Invalid parameters. No call is used.Fix the request. Do not retry it unchanged.
401The API key is missing or invalid.Check the X-API-Key header.
429You have no API calls left.Top up or upgrade your plan.
500The page could not be fetched. No call is used.Retry after a short pause.

A 200 uses a call. A 400, a 500 and other server errors do not, and neither does a 401 or 429. So retrying a failure never costs you. The one exception is a request your client abandons: that still counts, which is another reason for the 90 second timeout. This wrapper retries a 500 and network failures with a growing delay, and gives up at once on 400, 401 and 429. Remember that a 500 only arrives after we have already retried on our side.

function justserp_search_retry(string $keyword, array $options = [], int $retries = 3): array
{
    for ($attempt = 0; ; $attempt++) {
        try {
            return justserp_search($keyword, $options);
        } catch (JustSerpException $e) {
            $retryable = $e->status === 0 || $e->status === 500;
            if (!$retryable || $attempt >= $retries) {
                throw $e;
            }
            sleep(2 ** $attempt); // 1s, 2s, 4s...
        }
    }
}

Running searches in parallel with curl_multi

PHP runs one thing at a time, but curl_multi lets cURL drive many transfers at once. Your plan sets how many requests may be in flight together: 10 on Free and Personal, 25 on Business, 50 on Enterprise. Concurrency counts requests in progress, not requests per second, and a request holds its slot until it is answered. This function sends keywords in batches no larger than your limit:

function justserp_search_many(array $keywords, array $options = [], int $limit = 10): array
{
    $results = [];

    foreach (array_chunk(array_values($keywords), $limit) as $batch) {
        $mh = curl_multi_init();
        $handles = [];
        foreach ($batch as $keyword) {
            $ch = justserp_handle($keyword, $options);
            curl_multi_add_handle($mh, $ch);
            $handles[$keyword] = $ch;
        }

        do {
            $status = curl_multi_exec($mh, $running);
            if ($running) {
                curl_multi_select($mh, 1.0);
            }
        } while ($running && $status === CURLM_OK);

        foreach ($handles as $keyword => $ch) {
            $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            $body = curl_multi_getcontent($ch);
            $results[$keyword] = $code === 200
                ? json_decode($body, true)
                : ["error" => "HTTP $code"];
            curl_multi_remove_handle($mh, $ch);
            curl_close($ch);
        }
        curl_multi_close($mh);
    }
    return $results;
}

$keywords = ["crm software", "email marketing tool", "invoice app", "seo checker"];
foreach (justserp_search_many($keywords, [], 5) as $keyword => $data) {
    $count = isset($data["error"]) ? $data["error"] : count($data["organic_results"] ?? []) . " results";
    echo str_pad($keyword, 24), $count, "\n";
}

Each batch finishes when its slowest request does, which keeps the code simple and the load predictable. A failed entry holds an error key, and you can pass just those keywords through justserp_search_retry().

Habits that save calls and headaches

  • Keep the key on the server in an environment variable, never in a repository or a template.
  • Set CURLOPT_CONNECTTIMEOUT to 10 and CURLOPT_TIMEOUT to 90 so a slow request can neither tie up a PHP worker forever nor be abandoned too early.
  • Cache results you will reuse, in APCu, Redis or a database. We do not cache searches, so a repeated search is a repeated call.
  • Default optional blocks with ?? []. Google does not show ads, knowledge panels or videos on every page.
  • Stay within your concurrency limit when using curl_multi, so requests are not rejected for sending too many at once.

Next steps

That covers what you need to put Google data into your PHP projects. Create a free account for 2,000 free requests, no credit card needed, and try the examples above, or see the pricing when you are ready to scale. Prefer another language? Read the Python version of this guide or the JavaScript version.