PHPs base 64_decode is not converting base64 string to a real workable image file

后端 未结 4 1589
有刺的猬
有刺的猬 2021-01-28 04:26

Hello guys I successfully found a method that claims to make a file input file into a base 64 string in JavaScript so I successfully sent that base 64

string by JSON v

4条回答
  •  日久生厌
    2021-01-28 04:52

    I see a couple of major issues:

    1. On line 13 of x.php, you call base64_decode, but don't assign the result. If should read as $photo = base64_decode($photo);

    2. The prefix used to display the image in a browser (data:image/jpeg;base64,) should not be included in the file written. Thus your final decode should look something like:

    $photo = base64_decode(explode(",",$photo,2)[1]);
    

    Where explode is splitting on the first comma, returning an array, and we're accessing just the second item which contains the rest of the string since we're limiting it to 2 items, meaning it's safe if there's a comma later on. (Using substr and strpos may be a little more efficient, so that's a fine option as well)

    If the file type isn't always JPEG, you'll want to parse that first part as well so you know what to use in the filename (at least if you care about portability).


    If that doesn't resolve your issue, start troubleshooting incrementally: take the value from JavaScript and compare it to the value from PHP before decoding. Are they identical? Often you can get some additional encoding (e.g. URL-encoded) depending on configuration, so it's important to rule that out.

    If the strings look identical, I'd move on to the base64_decode function and set the optional $strict parameter to true. This will cause it to return false if there are any non-base64 characters (instead of silently dropping them).

    You could also try testing with a small known string (bypassing the encoding to ensure that isn't the issue), such as a 1x1 pixel black GIF:

    R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=
    

    You could test the same directly in PHP to eliminate any of the encoding or decoding of the JSON object or its processing in transit from being the issue.

提交回复
热议问题