Published in Coding Project
avatar
3 minutes read

Create a instant index system with PHP simple page + Google api

Create a instant index system with PHP simple page + Google api

How is this instant index - it's a tool that use your website/page fastly index on Google search engine. If you're not using wordpress, that can be helped you . Simple structure - 

1. Create a index.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Instant Index API</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 2em;
        }
        textarea, button {
            padding: 10px;
            margin: 5px;
            width: 80%;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        #response {
            margin-top: 20px;
            white-space: pre-wrap;
            background: #f9f9f9;
            padding: 10px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <h1>Google Instant Index API</h1>
    <p>Submit URLs to Google's Instant Indexing API (one per line).</p>
    <textarea id="urls" placeholder="Enter URLs (one per line)" rows="6"></textarea><br>
    <button onclick="submitUrls()">Submit URLs</button>
    <div id="response"></div>

    <script>
        function submitUrls() {
            const urls = document.getElementById('urls').value.trim().split('\n');
            if (urls.length === 0 || urls.some(url => url.trim() === '')) {
                alert('Please enter at least one URL!');
                return;
            }

            fetch('submit.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ urls: urls })
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('response').textContent = JSON.stringify(data, null, 4);
            })
            .catch(error => {
                document.getElementById('response').textContent = 'Error: ' + error;
            });
        }
    </script>
</body>
</html>

2. Create submit.php

<?php
header('Content-Type: application/json');

// Path to the JSON service account file (private directory)
$serviceAccountPath = 'private/service-account.json';

// Read input data
$data = json_decode(file_get_contents('php://input'), true);
$urls = $data['urls'] ?? [];

// Check if at least one URL is provided
if (empty($urls)) {
    echo json_encode(['success' => false, 'message' => 'At least one URL is required.']);
    exit;
}

// Check if the service account file exists
if (!file_exists($serviceAccountPath)) {
    echo json_encode(['success' => false, 'message' => 'Service account file not found.']);
    exit;
}

// Load the service account file
$serviceAccount = json_decode(file_get_contents($serviceAccountPath), true);
$privateKey = $serviceAccount['private_key'];
$clientEmail = $serviceAccount['client_email'];
$tokenUrl = $serviceAccount['token_uri'];

// Create a JWT (JSON Web Token)
$jwt = createJwt($privateKey, $clientEmail, $tokenUrl);

// Request an access token
$postData = http_build_query([
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

// Handle cURL errors
if (!$response) {
    echo json_encode(['success' => false, 'message' => 'cURL error: ' . curl_error($ch)]);
    curl_close($ch);
    exit;
}

curl_close($ch);
$tokenResponse = json_decode($response, true);

// Check if the access token is retrieved
if (!isset($tokenResponse['access_token'])) {
    echo json_encode(['success' => false, 'message' => 'Failed to retrieve access token.', 'error' => $tokenResponse]);
    exit;
}

$accessToken = $tokenResponse['access_token'];

// Process each URL
$results = [];
foreach ($urls as $url) {
    $url = trim($url); // Remove leading/trailing spaces
    if ($url) {
        $apiUrl = 'https://indexing.googleapis.com/v3/urlNotifications:publish';
        $postData = json_encode([
            'url' => $url,
            'type' => 'URL_UPDATED'
        ]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $accessToken,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

        $results[] = json_decode($response, true);
    }
}

// Return the results as JSON
echo json_encode(['success' => true, 'results' => $results]);

// Helper function to create a JWT
function createJwt($privateKey, $clientEmail, $tokenUrl)
{
    $header = base64UrlEncode(json_encode(['alg' => 'RS256', 'typ' => 'JWT']));
    $payload = base64UrlEncode(json_encode([
        'iss' => $clientEmail,
        'scope' => 'https://www.googleapis.com/auth/indexing',
        'aud' => $tokenUrl,
        'exp' => time() + 3600, // Expiration time (1 hour)
        'iat' => time()        // Issued at time
    ]));
    $signature = base64UrlEncode(signData($header . '.' . $payload, $privateKey));
    return $header . '.' . $payload . '.' . $signature;
}

// Helper function to sign data with a private key
function signData($data, $privateKey)
{
    openssl_sign($data, $signature, $privateKey, 'sha256');
    return $signature;
}

// Helper function for base64 URL encoding
function base64UrlEncode($data)
{
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

3. Now need a JSON file and file upload and rename service-account-key.json  (API key generate JSON file)

JSON file upload on private folder 

4. File structure like-

├── index.html

├── submit.php

└── private/

        └── service-account-key.json 

(Down text collect from rankmath ) 👇

Go to Google Cloud Platform 

Start by heading over to the Google Cloud Platform directly from here.

2.2 Create a New Project

Ensure that you’re creating a new Indexing API project by clicking the Create Project option.

Alternatively, you can click the Select a project drop-down and choose New Project from the popup that appears on the screen.

In the next screen, enter a project name that you can recognize later. And then click Create.

2.3 Enable Access to API

Once you create the project, you’d need to enable the project to access the API. In the next step, you’d see a screen as shown below. Confirm if the selected project is the one that we’ve created for Instant Indexing API, else, select the drop-down at the top to change the project. Once you’ve selected the project, click Next

In the next step, click the Enable option to enable the project to access the Instant Indexing API.

Once you’ve enabled it, you can close this tab.

3 Steps to Create Service Account

Next, you need to create a service account by opening the service accounts page.

3.1 Select the Project

You will first be prompted to select the API project you wish to create this service account (the one created in the previous step).

3.2 Create Service Account

After selecting the project you wish to create a service account for, you’ll be taken to the following page, where you simply need to click the Create Service Account button highlighted below:

On the Create service account screen, enter a name and description for the newly created service account.

Select and copy the whole Service Account ID (the one that looks like an email address) because you will need it later. Then, click on the Done button at the bottom:

3.3 Manage Keys for Service Account

You will then be able to download the file that contains your API key. To do so, simply click the three vertical dots in the Actions column and then select the Manage keys as shown below:

3.4 Create New JSON Key for Service Account

You will then be taken to the following page where you can click Add Key and then select the Create new key option, as shown below:

Choose the default JSON format when prompted in the overlay, and click Create:

Upon clicking Create, the .json file will be automatically downloaded in your browser, meaning you’ve successfully created the API key & can proceed to the next step…

4 Add the Service Account as an Owner of Your Google Search Console Property

To do this, you’ll need to register and verify your website with the Google Search Console (if you haven’t done so already), which is super easy: just follow the recommended steps to verify ownership of your property.

4.1 Navigate to Users and Permissions in Google Search Console Settings

After verifying your property, open the Google Search Console, select your property on the left (if prompted), and then click on Settings near the bottom:

Click on Users and Permissions:

4.2 Add User to Your Search Console Property

Click on the three dots next to your account, and then click on Add User.

4.3 Delegate Service Account ID as Owner

A popup will now appear. Enter the Service account ID (the one you copied out earlier) in the Email address field. Ensure that you’ve provided Owner level Permission, and then click Add.

Now in a few moments, you should see the Service account listed as a new Owner.

You can use a single Project, Service Account, and JSON API Key across multiple sites; just make sure that the Service Account is added as Owner for all the sites in the Search Console.


Comments