Search code examples
phpbase64unlink

unlink base64 encoded image not working


hi guys ive created a base64 encoded image captured with web cam now i convert the .png to .jpg all works fine but now i get two images on server both .png and .jpg how do i go about deleting the .png or is their a way to convert to jpg without saving .png image to disk thanx here my code

$rawData = $_POST['imgBase64'];
$filteredData = explode(',', $rawData);

$unencoded = base64_decode($filteredData[1]);
$randomName = rand(1000, 99999999999);
//Create the image 
$fp = fopen('user/'.$randomName.'.png', 'w');
fwrite($fp, $unencoded);
//convert image from png to jpg
$image = imagecreatefrompng('user/'.$randomName.'.png');
imagejpeg($image, 'user/'.$randomName.'.jpg', 80);
unlink($fp);

ive tried it with

unlink($image);

unlink($_SERVER['DOCUMENT_ROOT'] . "/user/.$randomName.'.png'");

imagedestroy($fp);

imagedestroy($image);

Solution

  • Use the function unlink() but passing the file name to it instead of the file handler.

    So from your example it would be:

    EDIT: You might need to close the file first:

    fclose( $fp ); 
    unlink( 'user/'.$randomName.'.png' );