如何从解码的Base64字符串中提取文件名和扩展名php
我将文件上传到我的PHP webservice,将它们编码为Base64并通过Json发送。如何从解码的Base64字符串中提取文件名和扩展名php
我使用这个代码在服务器上进行解码的数据:$file_content = base64_decode($file,true);
现在我想从$file_content
变量中提取文件名和扩展名。
我该怎么做?
UPDATE:这里是我用来解码文件的代码:
include '../conn.php';
include '../functions.php';
$entityBody = file_get_contents('php://input');
$decodedJson = json_decode($entityBody);
$user_email = $decodedJson->{'email'};
$user_token = $decodedJson->{'token'};
$file = $decodedJson->{'file'}; //This is the encoded content of the file from JSON
$file_content = base64_decode($file,true);
if(!checkStudentAuthorizationOrHigher($user_email,$user_token,$conn))
{
die();
}
//now I want to get $file_content type (extension or MIME type) and
//file name from the $file_content
//I tried the below code but it only gets file path as input parameter and doesn't work this way
echo mime_content_type($file_content);
只有文件的内容是通过JSON给我的PHP Web服务(文件名或扩展不发送给我的服务) 。如果有帮助,我的应用程序的客户端就是C#Windows Forms应用程序和Android应用程序。
我想用与客户端相同的文件名将文件保存在服务器上。另外我必须检查文件类型以确保它在服务器上被允许。 (该文件可以是.pdf,.jpg,.jpeg或.zip)
现在有没有办法从$file_content
变量中提取文件信息?
我用thw干预/图像库https://github.com/Intervention/image 来处理base64编码的图像。该图书馆还有许多其他功能。
$imageManager = new Intervention\Image\ImageManager();
$imageObject = $imageManager->make($base64EncodedImageSource);
$imageInfo = getimagesize($base64EncodedImageSource);
$this->mimeType = $imageInfo[2];
$extension = image_type_to_extension($this->mimeType);
$width = $imageInfo[0];
$height = $imageInfo[1];
$tempFilePath = '/path/to/file';
$imageObject->save($tempFilePath, 100);
或者,如果您有该文件的MIME类型,你可以使用函数image_type_to_extension获取文件扩展名
我不想成为一个痛苦在这里,但是:从OP实际上说,他有什么是一个缓冲区包含一个不确定类型的文件,他们从JavaScript传递到PHP作为base64编码的字符串。他们已经将其解码为_something_,但他们并没有说它是一个图像,即使它不包含文件名和扩展名,除非该数据以某种方式添加到JavaScript中的字符串中。 _或我错过了什么_ – RiggsFolly
@RiggsFolly我没有尝试使用javascript编码文件,但尝试使用PHP编码文件,它始终具有MIME类型以及内容。 – Ima
解码后的文件可以是image/pdf或zip文件。你的答案只适用于图像。 –
你把文件名和扩展到编码在JavaScript字符串中的Base64? – RiggsFolly
您不会提供有关脚本中实际发生的事情的很多信息。如何与我们分享一些代码,以便我们可以看到你在做什么 – RiggsFolly
从你的问题来看,'$ file'是文件名还是它的内容是不明确的。你可能想澄清。 –