Skip to content

Instantly share code, notes, and snippets.

@doxt3r
Forked from kitsaels/getFilename.php
Created March 18, 2021 21:12
Show Gist options
  • Save doxt3r/5b87f750451cb8b8a7179471f9629a62 to your computer and use it in GitHub Desktop.
Save doxt3r/5b87f750451cb8b8a7179471f9629a62 to your computer and use it in GitHub Desktop.
Get Filename from HTTP header Content-Disposition
<?php
function getFilename($header) {
if (preg_match('/Content-Disposition:.*?filename="(.+?)"/', $header, $matches)) {
return $matches[1];
}
if (preg_match('/Content-Disposition:.*?filename=([^; ]+)/', $header, $matches)) {
return rawurldecode($matches[1]);
}
throw new Exception(__FUNCTION__ .": Filename not found");
}
$s1 = 'Content-Disposition: attachment; filename="FILE NAME HERE"';
echo getFilename($s1) . PHP_EOL;
$s2 = 'Content-Disposition: attachment; filename=file.ext';
echo getFilename($s2) . PHP_EOL;
$s3 = 'Content-Disposition: attachment; name=file.ext';
echo getFilename($s3) . PHP_EOL;
<?php
function getFilename($header) {
if (preg_match('/filename="(.+?)"/', $header, $matches)) {
return $matches[1];
}
if (preg_match('/filename=([^; ]+)/', $header, $matches)) {
return rawurldecode($matches[1]);
}
throw new Exception(__FUNCTION__ .": Filename not found");
}
header("Content-Type: text/plain;charset=UTF-8");
$s1 = 'attachment; filename="FILE NAME HERE"';
echo getFilename($s1) . PHP_EOL;
$s2 = 'attachment; filename=file.ext';
echo getFilename($s2) . PHP_EOL;
$s3 = $_SERVER['HTTP_CONTENT_DISPOSITION'] ?? "";
echo getFilename($s3) . PHP_EOL;
<?php
function parseProperties($message) {
$properties = explode(';', $message);
$result = array();
foreach ($properties as $prop) {
$property = trim($prop);
$pos = strpos($property, '=');
if ($pos > 0) {
$key = trim(substr($property, 0, $pos));
$val = trim(substr($property, $pos+1));
if (strlen($val) > 0 && $val{0} == '"') {
$val = substr($val, 1, -1);
}
$result[$key] = $val;
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment