Check for file with same filename, but different extension - php

I have a directory contain jpeg and raw image files. Some jpeg files have a raw file version of them, some don't. Luckily, if a jpeg has a raw file they are named the same (excluding the extension). So, I need a way to check this directory for a matching raw file of the same filename, exclusing file extesion. the raw file, file extension could be pretty much anything.
Any ideas how I can do this? I have the filename (excluding extesion) stored of $filename at the moment.
To explain further. I have a directory with the following files in it:
cat.jpg
dog.jpg
bird.jpg
cat.raf
dog.foo
I need to match cat.jpg to cat.rag and dog.jpg to dog.foo. These have just been extracted from a uploaded zip file.

Try searching for files starting with the same name:
$fileWithoutExtension = basename($filename, '.jpg');
$allFilesWithThisName = glob($fileWithoutExtension . '.*');
if (count($allFilesWithThisName)) {
echo 'There is another file with this name';
}

As you already have the filename w/o the extension, you can just check if the raw file exists (file_exists()):
if (file_exists($filename.'.raw')) {
echo 'RAW file exists:', $filename , "\n";
}
But this seems so trivial to me, that I might did not understood your question completely.

Related

how to use original uploaded file without using its .tmp file in Laravel

I want to extract text from docx and doc file. I am using this class The one in the answer.
Everything works fine when i use them in native php and docx file in the same directory of the php files. It extracts pretty well. This is not the case when i upload them through <input type="file">. You can see in the link that this class accepts only docx,doc,pptx and xlsx. I know when you upload file in php it renames and move to temp to avoid name clashing and overwriting. So i came with something like getting the tmp file and removing its extension and adding docx or doc to it.
Here is my code
$file = $request->file('resume');
echo $file."<br>";
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
$echo $withoutExt."<br>";
$original_file = $withoutExt.".docx"."<br>";
$echo $original_file."<br>";
$doc_file = new DocxConversion($original_file);
$echo $docText= $doc_file->convertToText();
The above code gives me the output as i expected till converting the .tmp to .docx but finally says File Not exists Here is the output
C:\xampp\tmp\phpCB7E.tmp
C:\xampp\tmp\phpCB7E
C:\xampp\tmp\phpCB7E.docx
File Not exists
I have also tried to put a docx file in the controllers directory and tried to execute like this
public function index1(){
echo "hello";
$docObj = new DocxConversion("hello.docx");
var_dump($docText= $docObj->convertToText());
}
The above approach also says File not exists. Am i doing anything wrong here? It works perfectly with the same file in native code where my php files and docx files are in same directory but not when i use it in my controller.
Assuming your $file is a UploadedFile you can use the getRealPath method to get the path to the filename,
$file = $request->file('resume');
$doc_file = new DocxConversion($file->getRealPath());
echo $doc_file->convertToText();

PHP fileupload type check

Ok here is my code for uploading files
$ext_whitelist = array('pdf','doc','doc','mkv','mp4','mpg','mpeg','avi','flv','wma','ogg');
if(in_array($ext, $ext_whitelist))
{
$uniqid_file = uniqid('', true)."_".$file['name'];
$lokacija = $folder . "/" . $uniqid_file;
$encoded_uniqid_file = base64_encode($uniqid_file);
move_uploaded_file($file['tmp_name'], $lokacija);
$base_url= base_url("forms/fdownload/$encoded_uniqid_file/$path");
$form_data[$key] = "$uniqid_file ";
}
This checks file extension, so easy some could rename file, can someone help me to check file type proper?
Insted of a comment, I'll write a bit more as an answer.
Mimetype checking is a good thing if you want to know the type of the file, but it's not secure if you want to allow/deny the files at upload, because it's very easy to fake the mimetype.
Just try it, you can change it with a proxy or you can create a simple image, then add some php code at the end and rename it to .php. If you only check the mimetype, you can upload this .php file and run it on the server.
If you upload .jpg with php code in it, it's okay, the server won't push it through the php parser. (Except when you change the default configuration. (Apache: AddType, nginx: AddHandler )
There are some "secure" ways to check the uploaded files:
1. Check the extension and compare it to a whitelist.
This is the example in the question, but I'd like to write a complete solution. (A common mistake to check only the first think after the ., because there could be file names like: something.txt.php so always check the last postfix.)
$ext = array_pop(explode(".", $fileName));
$whitelist = array('pdf','doc','doc','mkv','mp4','mpg','mpeg','avi','flv','wma','ogg');
if (in_array($ext, $whitelist) {
//OK the extension is good, handle the upload.
} else {
//Wrong type, add error message.
}
If you use something like this, be careful and never allow extensions like .php and anything wich is in the server config.
2. Rename the file and drop the extension.
This is an another good way, but maybe you want to keep the original file name, the extension and the mimetype. You can store them in a database!
For this solution just take the original filename, add some random data (because if you upload into a single folder and you trie to upload something.jpg 2 time that would be a bad idea), then store this.
For example:
$newName = sha1($fileName.time());
move_uploaded_file($file['tmp_name'], $uploadPath . $newName);
Because the file doesn't have an extension, the server wont try to run it. (But if it's for example an image it'll work in the browsers, because they use the mimetype to determine the type and we didn't changed that.)
You can use
perl-file-mimeinfo
Ex:-
$file_path = '/tmp/temp.jpg';
$mimetype = trim(shell_exec("/usr/bin/mimetype -bi ".escapeshellarg($file_path)));
$info = null;
if(strpos($mimetype, "video/")===0 || strpos($mimetype, 'x-flash-video') > 0){
$info = 'video';
}elseif(strpos($mimetype, "audio/")===0){
$info = 'audio';
}elseif(strpos($mimetype, "image/")===0){
$info = 'image';
}

How to upload file to amazon s3 using MAMP?

I'm trying to push a file to a Amazon s3 filebucket.
I'm posting the file through an html form.
I try to generate a path to the file like this($file is a part of a foreach, because i need to support multiple files in a form-submit.)
$file['tmp_name'].'/'.$file['name'];
this outputs a filepath like this
/Applications/MAMP/tmp/php/phpZDcVQv/pdf.pdf
/Applications/MAMP/tmp/php/ exists, but nothing is inside it. I have set access read and write for everyone to that folder.
I use a library to post the images to Amazon: https://github.com/tpyo/amazon-s3-php-class It also complains that the filepath i have provided doesn't exist. It's running a check like:
if (!file_exists($file) || !is_file($file) || !is_readable($file))
How come the files aren't added?
Am I referencing the wrong folder? The file with the code is in /web/projectname/
Someone on the internet said something unclear about php removing the temp-file directly. Is this after the response has been run? Do I need to address this in some way?
The most simple code that generates the problem:
foreach ($_FILES as $file) {
$filepath = $file['tmp_name'].'/'.$file['name'];
if(file_exists($filepath)){
echo 'true <br />';
}else{
echo 'false <br />';
}
}
This echo:es false even if files have been uploaded.
$filepath contains the path i described above.
as the manual states:
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
and
$_FILES['userfile']['name']
The original name of the file on the client machine.
this means that file_exists($file['tmp_name']) should be true.
The path $file['tmp_name'].'/'.$file['name'] is bogus, since $file['name'] is there only for informing you of the original name, but this name is not used while saving the uploaded file on the server.
So in your example /Applications/MAMP/tmp/php/phpZDcVQv is actually the uploaded file.

Is it possible to get a file extension without knowing it?

I have a file called 94bf663a100e848fb599209af8cdc2b5.wmv. I know pathinfo will not give me the extension if I just use the name 94bf663a100e848fb599209af8cdc2b5. I believe glob is only for checking if a file exists. So is it possible to get a file extension just knowing the file name (94bf663a100e848fb599209af8cdc2b5)?
As the example on the php glob manual page suggests, glob does not simply check if the file exists, it returns every file that matches the expression.
Here's a modification of the example on that page for your needs:
$name = "94bf663a100e848fb599209af8cdc2b5";
$matching = glob($name . ".*");
$info = pathinfo($matching[0]);
$ext = $info['extension'];
This assumes there is one (and only one) file with that name (with any extension), but you should be able to modify it if the file might not exist, or there might be multiple files with the same name, and different extensions.
The finfo_file() function will inspect the byte signature of a file to return its mimetype. From there, you can mostly deduce the correct file extension.
// Adapted from the PHP docs
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
echo finfo_file($finfo, $filename);
finfo_close($finfo);
The first few characters of the file (binary) will usually give you some kind of hint about what the file type is.
Try it out by opening some binary files (rar, zip, mp3 etc.) in Notepad.
Try filetype() or mime_content_type() function in php...
pass the file path it returns the file type.

How we can read zip file and get information of files or folders contains without unzipping in PHP?

What I actually wanted to do is read zip file and then if it does contain folder then refuse it with some message.
I want user should upload zip file with files only without any directory structure.
So I want to read zip file contains and check file structure.
I am trying with following code snippet.
$zip = zip_open('/path/to/zipfile');
while($zip_entry = zip_read($zip)){
$filename = zip_entry_name($zip_entry);
//#todo check whether file or folder.
}
I have sorted out.
I am now checking filename as strings wherever I am getting string ending with "/" that am treating as directory else as file.
can't you parse path of $filename? something like $dirName = pathinfo($filename, PATHINFO_DIRNAME)

Categories