PHP file listing multiple file extensions
$files = glob("*.{jpg,png,gif}", GLOB_BRACE);
How to check if multiple files' extensions are in_array
As mentioned by the commenters, your $allowed
array contains a list of valid mime-types
, not extensions. You must decide what you want to use to check the validity of the file.
If you decide to go with the pure file extension, then in the loop you must also extract the extension, and compare that to a new list, one that contains expected valid extensions. Something like this:
$files = ['orange.jpg', 'apple.jpeg'];
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
foreach($files as $names) {
$pathinfo = pathinfo($names); /* split path in its components */
$extension = strtolower($pathinfo['extension']); /* extract the extension and normalize to lowercase */
if (in_array($extension, $allowed)) {
echo "Valid image extension";
} else {
echo "Invalid image extension";
}
}
How can I pass multiple file extensions parameter in header?
If you want in downloading any type of file you can just use application/octet-stream.
header('Content-Type: application/octet-stream');
// for example this will download any type of file
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
glob() Multiple files have the same file name with different file extensions
You need to use Glob function
$name= "hello";
$files = glob("/path/to/files/$name.*"); // Will find all file with hello.extension
if (count($files) > 0){
foreach ($files as $file)
{
$info = pathinfo($file);
echo "File found: extension ".$info["extension"]."<br>";
}
}else{
echo "No file name exists called $name."
}
PHP - Glob multiple file extensions only displays first extension listed
You seem to be limiting your search to the first 10 matches. If there are more than ten of each, then you will get them in the order you specified (since they are sorted by how they are found, not alphabetically).
You could use a foreach
loop to iterate through all files, or you could add sort($pictures)
before the loop.
PHP list of specific files in a directory
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml')
{
$thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
}
}
closedir($handle);
}
A simple way to look at the extension using substr and strrpos
PHP Upload multiple images and check their file extensions prior
The error is in both string echo 'Uploaded successfully!';{
position and content.
1) No any statements is allowed between }
and else
.
2) 'Uploaded successfully!';{
contains {
which is superfluous.
Update: One of a quite good ways to process uploaded files. Depends on $pic_names array from OP.
$pic_names = array (
'01' => 'picture01',
'02' => 'picture02',
'03' => 'picture03',
'04' => 'picture04',
'05' => 'picture05',
);
$allowed_mime = array(
'image/jpeg' => 'jpg',
'image/pjpeg' => 'jpg',
'image/gif' => 'gif',
'image/png' => 'png',
);
$upload_messages = array(
UPLOAD_ERR_OK => ' Uploaded successfully!',
UPLOAD_ERR_INI_SIZE => ' The uploaded file exceeds the maxumum size of ' . ini_get('upload_max_filesize') . '.',
UPLOAD_ERR_PARTIAL => ' The uploaded file was only partially uploaded.',
UPLOAD_ERR_NO_FILE => ' No file was uploaded',
UPLOAD_ERR_NO_TMP_DIR => ' Missing a temporary folder.',
UPLOAD_ERR_CANT_WRITE => ' Failed to write file to disk.',
UPLOAD_ERR_EXTENSION => ' A PHP extension stopped the file upload.',
100 => ' Wrong file type.',
);
$folder = "temp_images/";
$error_message = $success_message = '';
$upload_counter = 0;
foreach ($pic_names as $key => $value) {
if (isset($_FILES['image'.$key]) && !$_FILES['image'.$key]['error']) {
$file_mime = getFileMime($_FILES['image'.$key]['tmp_name']);
if ( in_array($file_mime, array_keys($allowed_mime)) ) {
$new_path = $folder . $value . '.' . $allowed_mime[$file_mime];
if ( !move_uploaded_file($_FILES['image'.$key]['tmp_name'], $new_path) ) {
$error_message .= ' Image' . $key . ':' . $upload_messages[UPLOAD_ERR_CANT_WRITE];
} else {
$upload_counter++;
}
} else {
$error_message .= ' Image' . $key . ':' . $upload_messages[100];
}
} else {
$error_message .= ' Image' . $key . ':' . ($_FILES['image'.$key]['error'] ? $upload_messages[$_FILES['image'.$key]['error']] : $upload_messages[UPLOAD_ERR_NO_FILE]);
}
}
if ( $upload_counter == count($pic_names) ) {
echo $upload_messages[UPLOAD_ERR_OK];
} else {
echo 'Loaded ' . $upload_counter . ' file' . ($upload_counter != 1 ? 's' : '') . '.' . $error_message;
}
function getFileMime ($file) {
if (PHP_VERSION >= '5.3.0') {
$finfo = new finfo(FILEINFO_MIME_TYPE);
return $finfo->file($file);
} else {
return mime_content_type($file);
}
}
Check extension of multiple file
Make a loop in files property of input object to get some information of each file:
<input type="file" multiple id="myInput" />
var myInput = document.getElementById('myInput');
myInput.onchange = _ => {
for (var i = 0; i < myInput.files.length; i++) {
var file = myInput.files[i];
console.log(file.name); // file_XYZ.xlsx
console.log(file); // Other info: size, type, etc.
}
};
PHP - directory listing script - display file names WITHOUT file extensions
You can use pathinfo
function to get filename without extension as below:
function display_block($file) {
global $ignore_file_list, $ignore_ext_list, $force_download;
$file_ext = getFileExt($file);
if (!$file_ext AND is_dir($file))
$file_ext = "dir";
if (in_array($file, $ignore_file_list))
return;
if (in_array($file_ext, $ignore_ext_list))
return;
$filePathInfo = pathinfo($file);
$download_att = ($force_download AND $file_ext != "dir" ) ? " download='" . basename($file) . "'" : "";
$rtn = "<div class=\"block\">";
$rtn .= "<a href=\"$file\" class=\"$file_ext\"{$download_att}>";
//$rtn .= " <div class=\"img $file_ext\"> </div>";
$rtn .= " <div class=\"name\">\n";
$rtn .= " <div class=\"file\">" . $filePathInfo['filename'] . "</div>\n";
//$rtn .= " <div class=\"date\">Size: " . format_size($file) . "<br />Last modified: " . date("D. F jS, Y - h:ia", filemtime($file)) . "</div>\n";
$rtn .= " </div>\n";
$rtn .= " </a>\n";
$rtn .= "</div>";
return $rtn;
}
basename
function is used when we are sure about the file extension. if you are sure that file extension will be same then you can also use it as below:
$fileName = basename($file, ".php");
Hope it helps you!!
Related Topics
Laravel Model with Two Primary Keys Update
How to Get the Client's Ip Address in a PHP Webservice
PHP Sentence Boundaries Detection
Advantages of MySQLi Over MySQL
Get Element by Classname with Domdocument() Method
Remove .PHP Extension with PHP
How to Join Three Table by Laravel Eloquent Model
Not Equal to != and !== in PHP
How to Convert an Array into an Object Using Stdclass()
How to Create a Laravel Hashed Password
How to Extract Links and Titles from a .HTML Page
Laravel: Connect to Databases Dynamically
Ajax Passing Data to PHP Script
How to Schedule the Execution of a PHP Script on the Server Side
Transpose 2D Array, Join Second Level with Commas, and Join First Level with Pipes