2017-01-09 12 views
1

提供されたbase64_decode引数のファイルタイプを返す関数を作成しました。画像でない場合、関数はfalseを返します。しかし、(jquery ajax(FormDataオブジェクト)を介して)エンコードされたイメージを渡すとき、この関数は毎回falseを返します。私は多くのことを試みましたが、それを働かせることはできません。Php | base64_decodeをimageとして検証する| Not working

編集:私は今、Javascriptのエラーを取得しています、ここにある:
"キャッチされないでSyntaxError:位置0でJSONで予期しないトークン"

function base64_extension($base64){ 
    $base64 = str_replace("data:image/png;base64,", "", $base64); 
    $base64 = base64_decode($base64); 

    $base64 = imagecreatefromstring($base64); 

    if(!$base64){ 
     return 0; /* Not image */ 
    } 


    if(imagepng($base64)){ 
     imagedestroy($base64); 
     return 1; 
    }else if(imagejpeg($base64)){ 
     imagedestroy($base64); 
     return 2; 
    } 
    else if(imagegif($base64)){ 
     imagedestroy($base64); 
     return 3; 
    } 
    else{ 
     return 4; /* Not image */ 
    } 
} 

CLIENT

var cropCanvas = $('#user-img').cropper('getCroppedCanvas'); 
var cropImg = cropCanvas.toDataURL("image/jpeg"); 
var formData = new FormData(); 
formData.append('pic', cropImg); 

次にI formDataをここでajaxに渡します。

+1

あなたは 'imagecreateのいずれか*'関数で作成したイメージを持っていたら、出力することができ関わらず 'png'、' jpg'、 'gif'のような画像の任意のタイプ入力形式は何でしたか。イメージを作成することは、拡張子が操作して理解できるイメージ形式で出力できる 'GD'形式であることを意味します。 –

+0

また、デコードしている画像データの例がありますか?私が正しく覚えていれば、そのようなajaxから送られたデータにはコンテンツタイプが含まれています。それを取り除くのでなければ、悪質な 'base64_decode'のデータが得られます。あなたはそれからイメージを作成することはできません。 –

+0

@JonathanKuhn関連するクライアントコードで質問を更新しました。 –

答えて

0

ジョナサン・クーンは、だからあなたの道は、あなたがfinfo_ *関数でデコードbase64でのMIMEタイプを取得することができます間違っている

Once you have an image created with any of the imagecreate* functions, you can output any type of image like png, jpg, gif regardless of what the input format was. Creating the image means it is in GD's format that the extension can manipulate and then output in any image format it understands.

を言ったように。例については

$base64 = base64_decode($base64); 
$finfo_handler = finfo_open(); 
$allowed_types = ["image/jpeg","image/png","image/gif"]; 
$mime_type = finfo_buffer($finfo_handler, $base64, FILEINFO_MIME_TYPE); 
finfo_close($finfo_handler); 
if(!in_array($mime_type, $allowed_types)){ 
    // Mime Type is not JPEG or PNG or GIF 
    return false; 
}else{ 
    // Mime Type is in Array and returns first index of exploded string by "/" char. 
    // That means for image/jpeg exploded_array = [ 0 => "image", 1 => "jpeg"] 
    // and it returns first index "jpeg" for "image/png" it returns "png" 
    return explode("/", $mime_type)[1]; 
} 
+0

画像ファイル以外のファイルに.png拡張子を入れた場合のこのアカウントはありますか? –

+0

更新しました。それをチェックしてください –

+0

これは「ファイル名の拡張子」と「ファイル形式」が異なるためにカウントされません。Base64エンコーディングはエンコードされたファイル名を与えません。フォーマットされたファイルのデータのBase64 Encoded文字列を返します。 –