base64 decode mixed results - php

I have the following code in PHP, and it works for the most, fine. I am sending a image from a mobile device to this script, which decodes it into a img file and creates a file out of it on the server. I am 99.9% sure every time its a base64 encoded.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: image/jpeg');
$data = ($_POST['imageData']);
define('UPLOAD_DIR', 'images/');
$img = str_replace('data:image/jpeg;base64,', '', $data);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
file_put_contents($file, $data);
echo ('{"imgUrl" : "' . $file . '"}');
?>
This then returns the image URL back to be added to a database.
The problem is, most of the time it does decode into a .jpg file, and other times into a txt file. I cannot see why it does it, as its a little random. But I have noticed that sometimes it will come as a $_POST, and other times, $_POST is Null. So I looked at using:
$data = json_decode(file_get_contents('php://input'));
But again, it seems inconsistant. But I put a logic statement such as:
$data = ($_POST['imageData']);
if($data == NULL) {
$data = json_decode(file_get_contents('php://input'));
}
Is there any reason I should be aware of why the code works, and sometimes does not work ?

I know this question is old, but is one of the first appearance by looking at this topic. So everyone looking at this question can find a link to a proper answer right away.
You should check this PHP - get base64 img string decode and save as jpg (resulting empty image )
Also check the conditions you're using, because
if ($data === NULL)
it may be different for
if ($data == NULL)
Also, you're saving the base64 string incorrectly to an image file.
Check that link and let me know how if it helped.

Related

How to convert byte array to image and save it in folder using php ?

I'm using below code
Here $data is a byte array.
$decoded_data = base64_decode($data);
$im = imagecreatefromstring($decoded_data);
if ($im !== false) {
header('Content-Type: image/png');
$image_nam = "png_".time().".png";
imagepng($im, $image_nam);
imagedestroy($im);
}
But I don't get the exact output
try this simple code for save image into directory
file_put_contents('/myfolder/imageName.jpg', base64_decode($img));
you can also try this
$base_to_php = explode(',', $base64Img);
$data = base64_decode($base_to_php[1]);
$filepath = "/path/imageName.png"; // or image.jpg
file_put_contents($filepath,$data);
I would suggest you to refer link -
This could be possible an issue with metadata present in base64 string.
As per source the problem could be due to data:image/png;base64, is included in binary string.
The metadata present in the binary string results in invalid image data when the decoded back. Can you try it by removing metadata in the function before decoding the string.
You may use function and write output to a new file.
$position_s= strpos($base64_string , "data:image/png;base64,");
substr($base64_string, 0, $position_s) . substr($base64_string, $position_s+ strlen("data:image/png;base64,");
Note: If you are preferring explode function, it would be best to set limits:
explode(',',$base64_string,2)

Replace Array value with other preg_replaced value

i've got an array, which i know that its values would be JPGs from somewhere
i need to go to each value returned to that array and preg_replace some characters
then set the values of the returned values to some other value
here's the code and here's what i've tried
//first piece of code
$data['images'] = array();
foreach ($single['PictureURL'] as $ispec) {
$data['images'][] = $ispec;
$ispec = preg_replace('/\$_[0-9]+.JPG\b/i', '$_10.JPG', $ispec);
$file = 'C:\wamp64\www\mz\images1.txt';
file_put_contents ($file, $ispec, FILE_APPEND);
//images1.txt shows all images returned fine with modified strings
}
//second piece of code
$product->imageUrl = $data['images'][0];
unset($data['images'][0]);
$product->subImageUrl = $data['images'];
$file = 'C:\wamp64\www\mz\images3.txt';
file_put_contents ($file, $data['images'], FILE_APPEND);
//images3.txt shows all the images returned but without being modified?? WHY??!
the first piece of the code is working on all values and replacing is working just fine.
the second piece of the code is my issue, it is returning the values of the old none modified images, which i don't
i need to modify the images before its being written to
'$product->imageUrl & $product->subImageUrl'
The problem is very simple. You're modifying your data after you already
stored it in $data['images']. To solve this, just move this line to
after the preg_replace:
foreach ($single['PictureURL'] as $ispec) {
$ispec = preg_replace('/\$_[0-9]+.JPG\b/i', '$_10.JPG', $ispec);
$data['images'][] = $ispec;
$file = 'C:\wamp64\www\mz\images1.txt';
file_put_contents ($file, $ispec, FILE_APPEND);
}

Uploading image after image and displaying them all

I've already asked a couple of questions regarding this and each step gets me closer however it still doesnt work as intended.
I want to upload an image and write it to the textfile, then when i upload another image that will be written to the end and so on so forth. So ultimately you'll have a long file with lots of images.
As far as i can tell my code should work but it doesn't. Here is a link to the site website for testing. Testing it maybe useful and below is the code.
It also always creates an empty element at the end of the array as you'll see from testing the site.
The PHP:
$sFileName = "imgDB.txt";
for ($i=0 ; $i < count($_FILES) ; $i++) {
move_uploaded_file(
$_FILES['file-'.$i]['tmp_name'],
"img/". $_FILES['file-'.$i]['name']
);
}
$sImgs = file_get_contents($sFileName); //gets a string from the file.
if (json_decode($sImgs, true) != false) {
$ajImgs = json_decode($sImgs, true);
} else {
$ajImgs = array();
}
$aOutPut = array_merge ($ajImgs, $_FILES);
$aSendToFile = json_encode(
$aOutPut,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);
file_put_contents($sFileName, $aSendToFile);
Some remarks
if the move_uploaded_file call is not protected further, this allows to upload any files, including script files - this opens a security vulnerability in your application - check for MIME-type and file-extension to avoid this
json_decode returns null if the input value is empty or cannot be decoded - not false like in your code
appending to an array is not done with array_merge, this just overrides the properties of $_FILES of the previous execution - use $aOutPut[] = $_FILES; instead

Validation of Base64 encoded image

In my cakephp program, I am converting a base64 encoded image to an image and then storing it in a folder.
How can I validate this image, before conversion?
The string is like data:image/png;base64,iVBORw0KG......
(The image can be of any extension not only png.)
This answer might be useful for processing the image.
This answer might be useful for validating the image.
Code:
$data = 'data:image/png;base64,iVBORw0KG.....';
list($type, $data) = explode(';base64,', $data, 2);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
if (imagecreatefromstring($data) == false) { echo "invalid_image"; die(); }
file_put_contents('/storage/folder/image.png', $data);
You might also want to restrict file types.
You must keep in mind that you can't simply trust any of the data sent from the client (like 'data:image/png'), so you must rely on other means (some php functions).

php Update filename from directory

so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.

Categories