File "export_customers_zip.php"

Full Path: /home/chawlag2/public_html/cars/admin/css/export_customers_zip.php
File size: 5.44 KB
MIME-type: text/x-php
Charset: utf-8

<?php
// export_customers_zip.php
session_start();
include('admin/dbconn.php');

// ✅ Set your secret token here (use the one you generated)
$EXPORT_TOKEN = 'e9c4c7d2f1a84b0bb6a2d0c3d8f7a1c9_7b2f9a1d6c3e4f8b9a0d1c2e3f4a5b6c';

// ---------------- Security: token check ----------------
$token = $_GET['token'] ?? '';
if (!hash_equals($EXPORT_TOKEN, (string)$token)) {
  http_response_code(403);
  exit("Forbidden");
}

// ---------------- Zip extension check ----------------
if (!class_exists('ZipArchive')) {
  http_response_code(500);
  exit("ZipArchive is not available on this server. Enable PHP zip extension.");
}

// ---------------- Helpers ----------------
function safeFolderName($name) {
  $name = trim((string)$name);
  if ($name === '') return 'Customer';

  // replace slashes/backslashes and other unsafe characters
  $name = str_replace(['/', '\\'], '-', $name);
  $name = preg_replace('/[<>:"|?*\x00-\x1F]/u', '-', $name); // windows + control chars
  $name = preg_replace('/\s+/u', ' ', $name);
  $name = trim($name, " .-_\t\n\r\0\x0B");

  return $name !== '' ? $name : 'Customer';
}

function makeCustomerCsvString(array $row, array $columnsToExport) {
  $fp = fopen('php://temp', 'r+');
  // header
  fputcsv($fp, $columnsToExport);
  // data
  $data = [];
  foreach ($columnsToExport as $c) {
    $data[] = isset($row[$c]) ? $row[$c] : '';
  }
  fputcsv($fp, $data);

  rewind($fp);
  $csv = stream_get_contents($fp);
  fclose($fp);
  return $csv;
}

function safeJoinPath($baseDir, $relativePath) {
  $relativePath = ltrim((string)$relativePath, '/\\');
  if ($relativePath === '') return null;

  $candidate = $baseDir . DIRECTORY_SEPARATOR . $relativePath;
  $realBase = realpath($baseDir);
  $realCand = realpath($candidate);

  // If file doesn't exist, realpath will be false
  if ($realBase === false || $realCand === false) return null;

  // Prevent path traversal: ensure candidate is inside base
  if (strpos($realCand, $realBase) !== 0) return null;

  return $realCand;
}

// ---------------- Build ZIP ----------------
date_default_timezone_set("Asia/Karachi");
$stamp = date('Ymd_His');

// temp file for zip
$tmpZip = tempnam(sys_get_temp_dir(), 'cgm_zip_');
if ($tmpZip === false) {
  http_response_code(500);
  exit("Unable to create temp file.");
}

// ZipArchive needs a .zip extension on some hosts
$zipPath = $tmpZip . '.zip';
rename($tmpZip, $zipPath);

$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
  http_response_code(500);
  exit("Unable to create zip.");
}

// Base directory for file paths (nicFront/nicBack are stored like 'images/customers/xxx.jpg')
$baseDir = __DIR__;

// Choose what columns to export per customer CSV
// ✅ Recommend excluding password for safety (you can add it back if you want)
$columnsToExport = [
  'id',
  'customerName',
  'fatherHusbandName',
  'address',
  'nicNo',
  'contactNo',
  'email',
  // 'password', // <-- uncomment if you REALLY want to export hashed password
  'dob',
  'country',
  'city',
  'variant',
  'exteriorColor',
  'interiorColor',
  'nicFront',
  'nicBack',
  'status',
  'dateAdded',
  'timeStamp'
];

// Fetch all customers
// If your primary key is not `id`, change it accordingly
$sql = "SELECT * FROM customers ORDER BY timeStamp DESC";
$res = $conn->query($sql);

if (!$res) {
  $zip->close();
  @unlink($zipPath);
  http_response_code(500);
  exit("Database query failed.");
}

// Keep folder names unique if duplicate names exist
$usedFolderNames = [];

while ($row = $res->fetch_assoc()) {
  $customerId = $row['id'] ?? uniqid();
  $custName = $row['customerName'] ?? 'Customer';

  $folder = safeFolderName($custName);

  // Ensure uniqueness
  $finalFolder = $folder;
  if (isset($usedFolderNames[$finalFolder])) {
    $finalFolder = $folder . '_' . $customerId;
  }
  $usedFolderNames[$finalFolder] = true;

  $folderPathInZip = $finalFolder . '/';

  // Add customer CSV
  $csv = makeCustomerCsvString($row, $columnsToExport);
  $zip->addFromString($folderPathInZip . "customer.csv", $csv);

  // Add NIC files (front/back)
  $nicFrontRel = $row['nicFront'] ?? '';
  $nicBackRel  = $row['nicBack'] ?? '';

  // Add front
  $frontAbs = safeJoinPath($baseDir, $nicFrontRel);
  if ($frontAbs && is_file($frontAbs)) {
    $frontName = basename($frontAbs); // keep original stored filename
    $zip->addFile($frontAbs, $folderPathInZip . $frontName);
  } else {
    // optional: note missing file
    $zip->addFromString($folderPathInZip . "missing_nicFront.txt", "Missing or invalid path: " . $nicFrontRel);
  }

  // Add back
  $backAbs = safeJoinPath($baseDir, $nicBackRel);
  if ($backAbs && is_file($backAbs)) {
    $backName = basename($backAbs);
    $zip->addFile($backAbs, $folderPathInZip . $backName);
  } else {
    $zip->addFromString($folderPathInZip . "missing_nicBack.txt", "Missing or invalid path: " . $nicBackRel);
  }
}

$res->free();
$zip->close();

// ---------------- Force download ----------------
$downloadName = "customers_export_{$stamp}.zip";

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$downloadName.'"');
header('Content-Length: ' . filesize($zipPath));
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

readfile($zipPath);

// cleanup
@unlink($zipPath);
exit;
?>