Last active
May 15, 2022 10:51
-
-
Save Waseem-Almoliky/c6d5f9624bdef4da406c683eb043a54d to your computer and use it in GitHub Desktop.
Save and work with Base46 files in (PHP -> Laravel) . It was made as Laravel trait to allow usage when needed by using it
This file contains hidden or 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 App\Traits; | |
use Illuminate\Support\Str; | |
trait Base64 | |
{ | |
public function getBase64Files($file): array | |
{ | |
$extension = $this->getExtension($file); | |
return ['file' => $this->decodeBase64($file), 'extension' => $extension]; | |
} | |
public function saveBase64Files($file, $path, $name): string | |
{ | |
if(!$name) $name = Str::random(10); | |
$extension = $this->getExtension($file); | |
$location = $this->joinPaths($path , $name . '.' . $extension); | |
file_put_contents($location, $this->decodeBase64($file)); | |
return $location; | |
} | |
public function getExtension($file){ | |
return explode('/', explode(':', substr($file, 0, strpos($file, ';')))[1])[1]; // .jpg .png .pdf | |
} | |
public function decodeBase64($file){ | |
$replace = substr($file, 0, strpos($file, ',') + 1); | |
$image = str_replace($replace, '', $file,); | |
$image = str_replace(' ', '+', $image); | |
return base64_decode($image); | |
} | |
public function joinPaths(): string | |
{ | |
$paths = array(); | |
foreach (func_get_args() as $arg) { | |
if ($arg !== '') { $paths[] = $arg; } | |
} | |
return preg_replace('#/+#','/',join('/', $paths)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment