2017-04-04 10:43
浏览 1.1k


I'm uploading files to my PHP webservice by encoding them to Base64 and sending them via Json.

I'm decoding the data on the server using this code: $file_content = base64_decode($file,true);

Now I want to extract file name and extension from the $file_content variable.

How can I do that?

UPDATE: here is the code I used to decode the file:

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);


//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);

Only the file content is given to my PHP webservice through JSON (file name or extension is not sent to my service). If it helps, the client side of my application is both a C# Windows Forms app and an Android app.

I want to save the file on the server with the same file name as the client side. Also I have to check the file type to make sure it is allowed on the server. (the file can be .pdf , .jpg , .jpeg or .zip)

Now is there a way to extract file info from $file_content variable?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsiy62758 2017-04-04 10:52

    I used thw Intervention/image library to deal with base64 encoded images. THis library got many other features as well.

    $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);

    Alternatively, if you have mime type of the file, you can use function image_type_to_extension to get file extension

    解决 无用
    打赏 举报

相关推荐 更多相似问题