Last active
March 15, 2024 15:00
-
-
Save maryisdead/4c4f46ff280be029d71e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Optc\HttpFoundation\File; | |
use Symfony\Component\HttpFoundation\File\File; | |
/** | |
* File created from a base64 encoded string. | |
* | |
* @author maryisdead | |
*/ | |
class Base64File | |
{ | |
/** | |
* Constructs a new file from the given base64 encoded string. | |
* | |
* @param string $path Path where file should be placed. Do NOT add a file extension! This will be determined automatically. | |
* @param string $base64Data Base64 encoded string, a data URI is also possible | |
*/ | |
public static function create($path, $base64Data) | |
{ | |
// Remove meta data string, if it's a data URI. | |
$dataUrl = preg_replace('/^.*;base64,/', '', $base64Data); | |
$file = fopen($path, 'w'); | |
stream_filter_append($file, 'convert.base64-decode'); | |
fwrite($file, $base64Data); | |
$meta_data = stream_get_meta_data($file); | |
$path = $meta_data['uri']; | |
fclose($file); | |
$file = new File($path); | |
// Append file extension, if possible. | |
$extension = $file->guessExtension(); | |
if ($extension) { | |
$file = $file->move(dirname($path), basename($path).'.'.$extension); | |
} | |
return $file; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment