Passing Data Between PHP Sites in a Scheduled Task
As a software developer, you may often find yourself needing to transfer data between different PHP applications. This could be for a variety of reasons, such as syncing data between a backend system and a public-facing website, or integrating two separate applications that need to share information.
One common way to do this is by setting up a scheduled task, or cron job, to periodically fetch data from one system and send it to the other. In this blog post, we'll explore how you can do this using a WordPress REST API and a cron job.
Why Use a WordPress REST API?
WordPress is a popular content management system (CMS) that is widely used for building websites and web applications. One of the key features of WordPress is its REST API, which allows you to interact with your WordPress site programmatically.
Using the WordPress REST API has several advantages:
-
Ubiquity: WordPress is an incredibly popular platform, with millions of active websites. This means that chances are good that at least one of the PHP applications you need to integrate with is running on WordPress.
-
Ease of Implementation: WordPress provides excellent documentation and developer tools for working with its REST API, making it relatively straightforward to set up and use.
-
Security: WordPress' REST API includes built-in security features, such as authentication and authorization mechanisms, which can help protect your data as it's being transferred between systems.
-
Flexibility: The WordPress REST API is highly extensible, allowing you to create custom endpoints to suit your specific needs.
Setting Up a WordPress REST API Endpoint
To get started, you'll need to set up a WordPress REST API endpoint that can receive data from your other PHP application. Here's how you can do that:
- Create a Custom Endpoint: WordPress comes with a set of default REST API endpoints, but you can also create your own custom endpoints. To do this, you can use the
register_rest_route()
function in your WordPress plugin or theme's functions.php
file.
function my_custom_endpoint( $request ) {
// Get the data from the request
$data = $request->get_params();
// Process the data as needed
$result = process_data( $data );
// Return the result
return rest_ensure_response( $result );
}
add_action( 'rest_api_init', function () {
register_rest_route( 'my-plugin/v1', '/my-endpoint', array(
'methods' => 'POST',
'callback' => 'my_custom_endpoint',
) );
} );
- Secure the Endpoint: To ensure that only authorized applications can access your custom endpoint, you should implement some form of authentication. WordPress provides several options for this, such as using API keys or OAuth.
function my_custom_endpoint( $request ) {
// Check if the request is authorized
if ( ! is_user_authorized( $request ) ) {
return new WP_Error( 'not_authorized', 'You are not authorized to access this endpoint.', array( 'status' => 401 ) );
}
// Get the data from the request
$data = $request->get_params();
// Process the data as needed
$result = process_data( $data );
// Return the result
return rest_ensure_response( $result );
}
function is_user_authorized( $request ) {
// Check the request for a valid API key or other authentication credentials
$api_key = $request->get_header( 'X-API-Key' );
return ( $api_key === 'valid_api_key' );
}
- Test the Endpoint: Once you've set up the custom endpoint, you can test it by making a POST request to the
my-plugin/v1/my-endpoint
endpoint. You can use a tool like Postman or cURL to do this.
curl -X POST \
-H "Content-Type: application/json" \
-H "X-API-Key: valid_api_key" \
-d '{"key1": "value1", "key2": "value2"}' \
https://example.com/wp-json/my-plugin/v1/my-endpoint
Now that you have a WordPress REST API endpoint set up and ready to receive data, let's look at how you can create a cron job to fetch data from a database and send it to the API.
Creating a Cron Job to Send Data to the WordPress API
To set up a cron job that will fetch data from a database and send it to the WordPress REST API, you'll need to follow these steps:
- Fetch the Data from the Database: Assuming you're using a database to store the data you need to transfer, you can use PHP's built-in database connectivity functions (such as
mysqli_
or PDO
) to retrieve the data.
$db = new mysqli('localhost', 'username', 'password', 'database_name');
$result = $db->query("SELECT * FROM data_table");
$data = $result->fetch_all(MYSQLI_ASSOC);
- Send the Data to the WordPress API: Once you have the data, you can use PHP's built-in
file_get_contents()
or curl_*()
functions to make a POST request to your WordPress API endpoint.
$url = 'https://example.com/wp-json/my-plugin/v1/my-endpoint';
$headers = array(
'Content-Type: application/json',
'X-API-Key: valid_api_key',
);
$payload = json_encode($data);
$options = array(
'http' => array(
'header' => implode("\r\n", $headers),
'method' => 'POST',
'content' => $payload,
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
- Set Up a Cron Job: Finally, you'll need to set up a cron job to run the script that fetches the data from the database and sends it to the WordPress API. You can use a tool like crontab to schedule the job to run at the desired interval.
# Example cron job that runs every 15 minutes
*/15 * * * * /path/to/php /path/to/your/script.php
Here's a complete example of the PHP script that you can use as a cron job:
<?php
// Connect to the database
$db = new mysqli('localhost', 'username', 'password', 'database_name');
// Fetch the data from the database
$result = $db->query("SELECT * FROM data_table");
$data = $result->fetch_all(MYSQLI_ASSOC);
// Send the data to the WordPress API
$url = 'https://example.com/wp-json/my-plugin/v1/my-endpoint';
$headers = array(
'Content-Type: application/json',
'X-API-Key: valid_api_key',
);
$payload = json_encode($data);
$options = array(
'http' => array(
'header' => implode("\r\n", $headers),
'method' => 'POST',
'content' => $payload,
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
error_log('Error sending data to WordPress API');
} else {
error_log('Data sent to WordPress API successfully');
}
?>
This script will fetch the data from the database, encode it as JSON, and then send it to the WordPress REST API endpoint you set up earlier. The cron job will run this script at the scheduled interval, ensuring that the data is regularly synced between the two PHP applications.
Conclusion
In this blog post, we've explored how you can use a WordPress REST API and a cron job to pass data between two PHP applications. By setting up a custom API endpoint in WordPress and creating a scheduled task to fetch data and send it to the API, you can easily integrate your systems and keep them in sync.
Remember, this is just one way to approach this problem. There are many other techniques and tools you can use, such as using a message queue, a third-party integration platform, or direct database connections. The best approach will depend on the specific requirements of your application and the constraints you're working within.
If you're looking for a comprehensive solution to monitor and optimize your website's technical performance, check out Flowpoint.ai. Flowpoint uses advanced AI to analyze your website's data and provide actionable recommendations to improve your conversion rates
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.