|

How to create an email extraction API using PHP

In an increasingly data-driven world, email extraction has become an essential tool for marketers, developers, and businesses alike. Creating a RESTful service for email extraction using PHP allows developers to provide a seamless way for users to retrieve emails from various sources via HTTP requests. In this guide, we’ll walk through the process of creating a simple RESTful API for email extraction.

Prerequisites

Before we begin, ensure you have the following:

  • A working PHP environment (e.g., XAMPP, WAMP, or a live server)
  • Basic knowledge of PHP and RESTful API concepts
  • Familiarity with Postman or any API testing tool

Step 1: Setting Up Your Project

  1. Create a Project Directory
    Start by creating a new directory for your project. For example, email-extractor-api.
  2. Create the Main PHP File
    Inside your project directory, create a file named index.php. This file will serve as the entry point for your API.
  3. Set Up Basic Routing
    Open index.php and add the following code to handle incoming requests:
<?php
header('Content-Type: application/json');

// Get the request method
$method = $_SERVER['REQUEST_METHOD'];

// Simple routing
switch ($method) {
    case 'GET':
        if (isset($_GET['url'])) {
            $url = $_GET['url'];
            extract_emails($url);
        } else {
            echo json_encode(['error' => 'URL parameter is required']);
        }
        break;

    default:
        echo json_encode(['error' => 'Unsupported request method']);
        break;
}

Step 2: Implementing Email Extraction Logic

Now we will implement the extract_emails function, which fetches the specified URL and extracts email addresses.

  1. Add the Email Extraction Function
    Below the routing code, add the following function:
function extract_emails($url) {
    // Fetch the page content
    $response = file_get_contents($url);
    
    if ($response === FALSE) {
        echo json_encode(['error' => 'Failed to retrieve the URL']);
        return;
    }

    // Use regex to extract emails
    preg_match_all('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', $response, $matches);
    $emails = array_unique($matches[0]);

    // Return the extracted emails
    if (!empty($emails)) {
        echo json_encode(['emails' => array_values($emails)]);
    } else {
        echo json_encode(['message' => 'No emails found']);
    }
}

Step 3: Testing Your RESTful API

Start Your PHP Server
If you are using a local server like XAMPP or WAMP, make sure it’s running. If you’re using the built-in PHP server, navigate to your project directory in the terminal and run:

php -S localhost:8000

Make a GET Request
Open Postman (or your preferred API testing tool) and make a GET request to your API. For example:

GET http://localhost:8000/index.php?url=https://example.com

Replace https://example.com with the URL you want to extract emails from.

Step 4: Handling Errors and Validations

To make your API robust, consider implementing the following features:

  • Input Validation: Check if the URL is valid before making a request.
  • Error Handling: Implement error handling for various scenarios, such as network failures or invalid URLs.
  • Rate Limiting: To prevent abuse, implement rate limiting on the API.

Step 5: Securing Your API

Security is crucial when exposing any API to the public. Consider the following practices:

  • HTTPS: Always use HTTPS to encrypt data in transit.
  • Authentication: Implement token-based authentication (e.g., JWT) to restrict access.
  • CORS: Set proper CORS headers to control who can access your API.

Conclusion

You’ve successfully created a simple RESTful service for email extraction using PHP! This API allows users to extract email addresses from any publicly accessible URL through a GET request. You can extend this basic framework by adding more features, such as storing the extracted emails in a database or integrating third-party services for email validation.

Similar Posts