google/cloud-dlp
Idiomatic PHP client for Google Cloud Data Loss Prevention (DLP). Inspect, classify, and manage sensitive data using REST or gRPC. Install via Composer and authenticate with Google Cloud credentials to start calling the DLP API.
Installation:
composer require google/cloud-dlp
Ensure your composer.json includes the package under require.
Authentication: Configure Google Cloud credentials via:
GOOGLE_APPLICATION_CREDENTIALS pointing to a service account JSON key file).First Use Case: Scan a text content for sensitive data (e.g., credit card numbers):
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\InspectContentRequest;
use Google\Cloud\Dlp\V2\InfoType;
$dlp = new DlpServiceClient();
$request = (new InspectContentRequest())
->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
->setData(new \Google\Cloud\Dlp\V2\ContentItem\Data())
->setBytes('Your sensitive text here')
->setInfoTypes([new InfoType()->setName('CREDIT_CARD')]);
$response = $dlp->inspectContent($request);
print_r($response->getFindings());
DlpServiceClient is the primary class for all operations.inspectContent(): Scan text, images, or files for sensitive data.redactContent(): Redact sensitive data from text.createInspectJob(): Asynchronous scanning for large datasets (e.g., BigQuery tables).getDataProfile(): Retrieve insights about data (e.g., column statistics, sensitive data distribution).$dlp = new DlpServiceClient();
$request = (new InspectContentRequest())
->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
->setData(new \Google\Cloud\Dlp\V2\ContentItem\Data())
->setBytes('SSN: 123-45-6789')
->setInfoTypes([new InfoType()->setName('US_SOCIAL_SECURITY_NUMBER')]);
$response = $dlp->inspectContent($request);
foreach ($response->getFindings() as $finding) {
echo "Found: " . $finding->getInfoType()->getName() . "\n";
}
$request = (new RedactContentRequest())
->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
->setData(new \Google\Cloud\Dlp\V2\ContentItem\Data())
->setBytes('Email: user@example.com')
->setInfoTypes([new InfoType()->setName('EMAIL_ADDRESS')]);
$response = $dlp->redactContent($request);
echo "Redacted: " . $response->getResult()->getData()->getBytes() . "\n";
$job = (new CreateInspectJobRequest())
->setParent('projects/YOUR_PROJECT_ID/locations/us')
->setInspectJob(new \Google\Cloud\Dlp\V2\InspectJob())
->setBigQueryTable(new \Google\Cloud\Dlp\V2\BigQueryTable())
->setProjectId('YOUR_PROJECT_ID')
->setDatasetId('YOUR_DATASET')
->setTableId('YOUR_TABLE')
->setInfoTypes([new InfoType()->setName('CREDIT_CARD')]);
$operation = $dlp->createInspectJob($job);
$jobName = $operation->getName();
// Poll for completion (see `getInspectJob`).
$profileRequest = (new GetColumnDataProfileRequest())
->setName('projects/YOUR_PROJECT_ID/locations/us/dataProfiles/YOUR_PROFILE_ID');
$profile = $dlp->getColumnDataProfile($profileRequest);
print_r($profile->getColumnStatistics());
$fileItem = new \Google\Cloud\Dlp\V2\ContentItem\File();
$fileItem->setBytes(file_get_contents('data.csv'));
$fileItem->setMimeType('text/csv');
$request = (new InspectContentRequest())
->setItem(new \Google\Cloud\Dlp\V2\ContentItem())
->setFile($fileItem)
->setInfoTypes([new InfoType()->setName('PHONE_NUMBER')]);
$response = $dlp->inspectContent($request);
Register the DLP client in AppServiceProvider:
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
public function register()
{
$this->app->singleton(DlpServiceClient::class, function () {
return new DlpServiceClient();
});
}
Inject the client into controllers/services:
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
class DataScannerService {
public function __construct(private DlpServiceClient $dlp) {}
public function scanText(string $text): array {
// Use $this->dlp->inspectContent(...)
}
}
For large datasets, use asynchronous jobs (InspectJob) to avoid timeouts:
$job = $dlp->createInspectJob($request);
while (!$dlp->getInspectJob($job->getName())->getState()->getValue() === 'DONE') {
sleep(5); // Poll every 5 seconds
}
Extend detection rules by combining multiple InfoType objects:
$infoTypes = [
new InfoType()->setName('US_SOCIAL_SECURITY_NUMBER'),
new InfoType()->setName('CREDIT_CARD'),
new InfoType()->setName('EMAIL_ADDRESS'),
];
Wrap API calls in try-catch blocks:
try {
$response = $dlp->inspectContent($request);
} catch (\Google\ApiCore\ApiException $e) {
\Log::error("DLP Error: " . $e->getMessage());
throw new \RuntimeException("Failed to scan data", 0, $e);
}
Enable debug logging for troubleshooting:
$dlp = new DlpServiceClient([
'logger' => new \Monolog\Logger('dlp', [
new \Monolog\Handler\StreamHandler('php://stderr', \Monolog\Logger::DEBUG),
]),
]);
Google\Auth\Exception\GoogleAuthException with "Could not load credentials".GOOGLE_APPLICATION_CREDENTIALS points to a valid service account JSON key.export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account.json"
.env).RESOURCE_EXHAUSTED or QUOTA_EXCEEDED.InspectJob) for large datasets to avoid timeouts.use Google\ApiCore\Retry\RetrySettings;
$retrySettings = new RetrySettings()
->setMaxAttempts(3)
->setInitialBackoff(1.0)
->setMaxBackoff(60.0);
$dlp = new DlpServiceClient(['retrySettings' => $retrySettings]);
INVALID_ARGUMENT for large files (>10MB).DataCatalog actions.How can I help you explore Laravel packages today?