如何检查字符串在PHP中是否为base64有效 [英] How to check if a string is base64 valid in PHP

查看:379
本文介绍了如何检查字符串在PHP中是否为base64有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,想使用PHP测试是否为有效的base64编码.

I have a string and want to test using PHP if it's a valid base64 encoded or not.

推荐答案

我意识到这是一个老话题,但是使用strict参数不一定会有所帮助.

I realise that this is an old topic, but using the strict parameter isn't necessarily going to help.

在诸如我不是base 64编码的"之类的字符串上运行base64_decode不会返回false.

Running base64_decode on a string such as "I am not base 64 encoded" will not return false.

但是,如果您尝试使用strict解码字符串,然后使用base64_encode重新编码,则可以将结果与原始数据进行比较,以确定它是否是有效的bas64编码值:

If however you try decoding the string with strict and re-encode it with base64_encode, you can compare the result with the original data to determine if it's a valid bas64 encoded value:

if ( base64_encode(base64_decode($data, true)) === $data){
    echo '$data is valid';
} else {
    echo '$data is NOT valid';
}

这篇关于如何检查字符串在PHP中是否为base64有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆