Set Up Your Environment
- Ensure that you have installed Composer for managing dependencies in your PHP project.
- Install the Twilio SDK for PHP using Composer.
composer require twilio/sdk
Authentication and Initialization
- Use your Twilio Account SID and Auth Token to authenticate API requests.
- Initialize the Twilio client in your PHP script.
require 'vendor/autoload.php';
use Twilio\Rest\Client;
$sid = 'your_account_sid';
$token = 'your_auth_token';
$twilio = new Client($sid, $token);
Sending a Fax
- Prepare your fax document in a format supported by Twilio (e.g., PDF, JPEG).
- Use the Twilio client to send the fax by providing the required parameters.
try {
$fax = $twilio->fax->v1->faxes
->create("recipient_fax_number", // to
"https://example.com/your-document.pdf", // mediaUrl
["from" => "your_twilio_fax_number"]
);
echo "Fax SID: " . $fax->sid;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Checking Fax Status
- Fetch the status of a specific fax using its SID. This helps in tracking if the fax was successful or failed.
try {
$fax = $twilio->fax->v1->faxes("fax_sid")->fetch();
echo "Fax Status: " . $fax->status;
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
Handling Fax Events with Webhooks
- Set up a webhook URL that Twilio will call to update you about the fax status.
- Use the webhook data to perform actions like logging or notifying users when a fax is sent or fails.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$faxSid = $_POST['FaxSid'];
$faxStatus = $_POST['FaxStatus'];
// Process the webhook data
if ($faxStatus == 'delivered') {
echo "Fax $faxSid was successfully sent!";
} elseif ($faxStatus == 'failed') {
echo "Fax $faxSid failed to send.";
}
}
Secure Your Application
- Validate incoming requests to your webhook URL by verifying Twilio signatures. This ensures security and authenticity of the request.
- Consider sanitizing all inputs and outputs to prevent security vulnerabilities.
use Twilio\Security\RequestValidator;
$validator = new RequestValidator($token);
$signature = $_SERVER["HTTP_X_TWILIO_SIGNATURE"];
$url = 'https://example.com/your-webhook';
$valid = $validator->validate($signature, $url, $_POST);
if ($valid) {
// Process the verified request
} else {
// Reject the request
}