Write to a CSV File
Writes scalar rows to a CSV file under an approved base directory with fputcsv().
Purpose
Writes scalar rows to a CSV file under an approved base directory with fputcsv().
Snippet details
ContextCsvLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Write to a CSV File.
*
* Purpose:
* Writes rows to a CSV file under an approved directory.
*
* @param string $csv_path Destination CSV path.
* @param string $base_dir Approved base directory.
* @param array $rows CSV rows.
* @return array Write result.
*/
function ogSnippetWriteToACsvFile(string $csv_path, string $base_dir, array $rows): array {
$result = array(
'ok' => false,
'rows_written' => 0,
'message' => 'CSV was not written.'
);
$resolved_base = realpath($base_dir);
$target_dir = realpath(dirname($csv_path));
if ($resolved_base === false || $target_dir === false) {
return $result;
}
if (strpos($target_dir, $resolved_base) !== 0) {
$result['message'] = 'CSV target is outside the approved directory.';
return $result;
}
$handle = fopen($csv_path, 'w');
if ($handle === false) {
return $result;
}
foreach ($rows as $row) {
if (is_array($row) === false) {
continue;
}
if (fputcsv($handle, $row) !== false) {
$result['rows_written']++;
}
}
fclose($handle);
$result['ok'] = true;
$result['message'] = 'CSV was written.';
return $result;
}
$csv_path = sys_get_temp_dir().'/phpog_stargate_manifest.csv';
$write_report = ogSnippetWriteToACsvFile($csv_path, sys_get_temp_dir(), array(
array('team', 'destination'),
array('SG-1', 'Abydos')
));
echo 'CSV rows written: '.$write_report['rows_written'];