用php转换为base64

时间:2012-11-30 15:12:39

标签: php

我正在将图片上传转换为base64,但我也试图不必将图像存储在我的服务器上,遗憾的是这段代码将文件存储在我的服务器上有没有办法让它删除文件后呢它编码为base64?

这是我的代码..

    if(isset($_FILES['t1']['name'])){
    $file = rand(0, 10000000).$_FILES['t1']['name'];
    if (move_uploaded_file($_FILES['t1']['tmp_name'], $file)) {
        if($fp = fopen($file,"rb", 0))
        {
           $picture = fread($fp,filesize($file));
           fclose($fp);
           // base64 encode the binary data, then break it
           // into chunks according to RFC 2045 semantics
           $base64 = base64_encode($picture);
           $tag1 = '<img src="data:image/png;base64,'.$base64.'" alt="" />';
           $css = 'url(data:image/png;base64,'.str_replace("\n", "", $base64).'); ';
        }
    }
}

3 个答案:

答案 0 :(得分:4)

使用http://us3.php.net/manual/en/function.unlink.php

所以

....
$css = 'url(data:image/png;base64,'.str_replace("\n", "", $base64).'); ';
unlink($file);

答案 1 :(得分:0)

if(isset($_FILES['t1']['name'])){
    $file = rand(0, 10000000).$_FILES['t1']['name'];
    if (move_uploaded_file($_FILES['t1']['tmp_name'], $file)) {
           $fileCon = file_get_contents($file) ;
           // base64 encode the binary data, then break it
           // into chunks according to RFC 2045 semantics
           $base64 = base64_encode($fileCon);
           $tag1 = '<img src="data:image/png;base64,'.$base64.'" alt="" />';
           $css = 'url(data:image/png;base64,'.str_replace("\n", "", $base64).'); ';
           unlink($file);
    }

如果你不从临时文件移动文件将删除自动或移动它你可以取消链接

祝你好运

答案 2 :(得分:0)

您可以像普通文件一样使用$ _FILES ['t1'] ['tmp_name']。

所以你应该能够做到这一点:

if(isset($_FILES['t1']['name'])){
    $file = $_FILES['t1']['tmp_name'];
    if($fp = fopen($file,"rb", 0))
    {
        $picture = fread($fp,filesize($file));
        fclose($fp);
        // base64 encode the binary data, then break it
        // into chunks according to RFC 2045 semantics
        $base64 = base64_encode($picture);
        $tag1 = '<img src="data:image/png;base64,'.$base64.'" alt="" />';
        $css = 'url(data:image/png;base64,'.str_replace("\n", "", $base64).'); ';
    }
}

如果这不好,你可以使用@ cryptic的解决方案,只需取消链接()文件。