Skip to content
← Back to Snippets
Code

Read a CSV File

Reads a CSV file with fopen() and fgetcsv(), returning rows only when the file resolves under an approved base directory.

Purpose

Reads a CSV file with fopen() and fgetcsv(), returning rows only when the file resolves under an approved base directory.

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.
 */

/**
 * Read a CSV File.
 *
 * Purpose:
 * Reads CSV rows from an approved file path.
 *
 * @param string $csv_path CSV file path.
 * @param string $base_dir Approved base directory.
 * @return array CSV rows.
 */
function ogSnippetReadACsvFile(string $csv_path, string $base_dir): array {
	$rows = array();
	$resolved_base = realpath($base_dir);
	$resolved_path = realpath($csv_path);

	if ($resolved_base === false || $resolved_path === false) {
		return $rows;
	}

	if (strpos($resolved_path, $resolved_base) !== 0 || is_file($resolved_path) === false || is_readable($resolved_path) === false) {
		return $rows;
	}

	$handle = fopen($resolved_path, 'r');

	if ($handle === false) {
		return $rows;
	}

	while (($row = fgetcsv($handle)) !== false) {
		$rows[] = $row;
	}

	fclose($handle);

	return $rows;
}

$csv_rows = ogSnippetReadACsvFile(__FILE__, __DIR__);

echo 'CSV rows read: '.count($csv_rows);