PHP Requires Chilkat v11.0.0+
Chilkat2 PHP
Backup Windows Current User / Personal Certificates to a .zip
See more Certificates Examples
Demonstrates how to backup the certificates in the Windows registry-based Current User certificate store (in the "Personal" Logical Store as seen in certmgr.msc), to a zip archive. Certificates having an exportable private key are exported to .pfx files. Certificates with no private key, or with a non-exportable private key, are exported to .cer files.Obviously, this example only runs on Windows computers.
Chilkat PHP Downloads
<?php
use Chilkat2\BinData;
use Chilkat2\Cert;
use Chilkat2\CertStore;
use Chilkat2\StringBuilder;
use Chilkat2\Zip;
$success = false;
$certStore = new CertStore();
$readOnly = true;
try {
$certStore->OpenCurrentUserStore($readOnly);
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
$pfxPassword = 'secret';
$allSuccess = true;
$numSuccess = 0;
$zip = new Zip();
$zip->NewZip('qa_output/personalCerts.zip');
$certData = new BinData();
$sbFilename = new StringBuilder();
// Iterate over the certificates in the Current User store.
$cert = new Cert();
$numCerts = $certStore->NumCertificates;
$i = 0;
while ($i < $numCerts) {
$certStore->GetCert($i, $cert);
echo 'DN = ', $cert->SubjectDN, "\n";
$sbFilename->SetString('cert');
$sbFilename->AppendInt($i + 1);
$bHasPrivateKey = $cert->HasPrivateKey();
if (($bHasPrivateKey) && ($cert->PrivateKeyExportable)) {
// Export to a .pfx
try {
$cert->ExportToPfxBd($pfxPassword, true, $certData);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
$sbFilename->Append('.pfx');
$zip->AddBd($sbFilename->GetAsString(), $certData);
}
} else {
// Export to a .cer
try {
$cert->ExportCertDerBd($certData);
$success = true;
} catch (\Chilkat2\Exception $e) {
$success = false;
}
if ($success) {
$sbFilename->Append('.cer');
$zip->AddBd($sbFilename->GetAsString(), $certData);
}
}
if (!$success) {
$allSuccess = false;
} else {
$numSuccess = $numSuccess + 1;
}
$i = $i + 1;
}
if ($numSuccess > 0) {
try {
$zip->WriteZipAndClose();
} catch (\Chilkat2\Exception $e) {
echo $e->getMessage(), "\n";
$allSuccess = false;
}
}
echo 'All success = ', ($allSuccess ? 'true' : 'false'), "\n";