When attempting to save a base64 code to a directory, I encounter an issue where the image fails to load and cannot be accessed

I've been facing an issue where I try to save an image into a folder in my project, but the saved file appears corrupted and cannot be viewed or opened.

Here's how I'm handling it: First, I receive the image through a form where I capture the base64 code after selection. When I submit the post, I use the following code:

var selectFotoAdjunta = document.getElementById("fotoAdjunta__url_val"); var selectedFotoAdjunta = selectFotoAdjunta.src; var selectedEncodedFotoAdjunta = encodeURIComponent(selectedFotoAdjunta);

Then, I pass this variable via the post system:

var $form = $( this ), $submit = $form.find( 'button[type="submit"]' ), fotoadjunta_value = selectedEncodedFotoAdjunta, url = $form.attr('action');

var posting = $.post( url, { 
    foto: fotoadjunta_value,
});

Next, I navigate to the PHP code designated for processing the form submission which seems to be functioning correctly initially.

The base64 code looks something like this: "data%3Aimage%2Fjpeg%3Bbase64%2CiVBORw0KGgoAAAANS..." The complete base64 encoded image can be found here:

$extension = "jpeg";
if (!empty($foto)){
    $base64img = rawurldecode($foto);
    
    if (str_contains($base64img, 'data:image/jpeg')) { 
        $extension = "jpeg";
        $base64img = str_replace('data:image/jpeg;base64,', "", $base64img);
        
    } else if (str_contains($base64img, 'data:image/jpg')) {
        $extension = "jpg";
        $base64img = str_replace('data:image/jpg;base64,', "", $base64img);
        
    } else if (str_contains($base64img, 'data:image/png')) {
        $extension = "png";
        $base64img = str_replace('data:image/png;base64,', "", $base64img);
    } 
    
    $filename = '../Imagenes/temp_viajes.'.$extension;
    $fpc = file_put_contents($filename, $base64img);
        if ($fpc) { echo 'Image uploaded correctly'; }

}

However, when I check the folder where the image should be saved, I'm greeted with this result:

enter image description here

I also attempted using the base64_decode function instead of rawurldecode, but unfortunately encountered the same problem. Could someone offer assistance on this matter? I am stumped as to why this is happening.

My efforts to download the image into a local folder have not been successful so far.

Answer №1

The data contained in the image you are attempting to save is base64-encoded. Although you successfully decoded the URL and removed the "data" prefix, you overlooked the crucial step of using base64_decode.

To fix this issue, consider revising your second last line to:

$fpc = file_put_contents($filename, base64_decode($base64img));

Remember to always implement additional validation measures for any user input or form data as it can be easily exploited.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Laravel 5 querying relationship not functioning correctly

I am working with two tables, myurls and links: 1). myurls id domain ---------------------- 1 google.com 2 test.com 3 example.com etc 2). links id myurls_id end_date created_at ---------------- ...

What are some creative ways to incorporate images into websites outside of a ReactJS environment?

I'm currently working on a ReactJS application that is client-side only and intended for local use. One of the requirements is to save and load images using filepaths, including URLs and local file system paths. While I am able to store paths in loca ...

PHP: Upload error has been detected as 0, indicating that the file does not exist

Recently updated to php 5.6.17 on Centos 6.5 and encountering issues with file uploads. Below is a dump of the $_FILES variable: Array( [files] => Array ( [name] => file.pdf [type] => application/pdf [tmp_name] => ...

Verify the existence of a record based on the user ID and update it if it already exists. If the record does not exist, insert a new

I am currently working on updating a record for a specific user_id if it already exists, and inserting a new record if it does not exist in Laravel. However, I encountered an issue where the user id is being inserted as NULL even though the data is gettin ...

Convert the MySQL DATE column from numerical month to full month name

I'm having trouble figuring out a simple solution. I'm using the code below to generate a tree grid from a MySQL database. $sql2 = mysql_query("SELECT DISTINCT YEAR(date) FROM blogs ORDER by YEAR(date) desc")or die(mysql_error()); $archive .= "& ...

Retrieving emails from database without using the "@" symbol or

My current task involves retrieving data from a database to be posted later on. When a user logs in using the following code: function login($email, $password, $mysqli) { // By utilizing prepared statements, SQL injection is effectively prevented ...

Display information from a specific identifier in a modal popup window after clicking a button using PHP and MySQL

When a button is clicked on my website, a popup window appears using modal functionality. The issue I am facing is not being able to retrieve the correct data based on the id of the button. Below is the HTML table code snippet: <tbody> <?php $cou ...

Acquire information from an XML .NET DataSet within a PHP environment

I am working with XML data retrieved from a .NET web service: <?xml version="1.0" encoding="utf-8"?> <DataSet> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msd ...

Tips for reducing text in a card design

As a newcomer to codeigniter 4, I recently created an event card with a lengthy description. However, when I attempted to display the event data from the database on the card, it ended up becoming elongated due to the length of the description: https://i. ...

Calculate the number of weekdays that are not designated as holidays

In my symfony project, there is a Holiday class with various static functions related to non-holiday weekdays counting. The core of this code was borrowed from different responses in this discussion. I have integrated these static methods throughout my co ...

Implement a dialog on top of a current web page, achieve php-ajax query result, and enhance with

My website features 'dynamic' content, where 'static' nav-buttons replace specific div contents upon clicking. While I am able to retrieve my php/ajax results in a dialog box, I am struggling with placing this dialog above my current p ...

PHP displaying incorrect value after modifying value in JavaScript

One issue I am facing is with an html page that submits a form through javascript. Prior to the submission of the form, I modify the value of a hidden tag, which should then be retrievable in php. However, when attempting to retrieve the value in php, it a ...

Featuring my Cookie page prominently on my website's homepage

I am facing a simple issue: I have a cookie verification page (cookies_check.php) that I want to include on my home page (accueil.php). So, currently, the only code on accueil.php is: <?php include ('Controleur/cookies_check.php'); ?> He ...

PHP Lightweight HTML Content Scraper

I have been experimenting with a basic web crawler and here is the simple HTML code I used for learning purposes: input.php <ul id="nav"> <li> <a href="www.google.com">Google</a> <ul> <li&g ...

Guide on converting a string into an array using PHP

My log file has a structure similar to the following: [{"ip":"XXX","prop1":"d","prop2":"xxx","prop3":{"index":0,"type":"xxx"},"id":"xxxxx","reason": "xxx [xxx]"}] [{"ip":"XXX","prop1":"d","prop2":"xxx","prop3":{"index":0,"type":"xxx"},"id":"xxxxx","reaso ...

What is the best strategy for efficiently extracting information from multiple tables with only a handful of queries?

Attention: this query pertains to the integration of PostGIS, PostgreSQL, and PHP. We currently have Table A: gid | kstart | kend | ctrl_sec_no | the_geom | 626 | 238 | 239 | 120802 | 123456 | 638 | 249 | 250 | 120802 | 2 ...

Having trouble getting Vue.js to cooperate with a brand new Laravel 5.8 setup?

I set up a fresh Laravel project using laravel new sample. Then I executed npm install followed by npm run dev. Next, I modified the welcome.blade.php file as shown below: <!DOCTYPE html> <html> <head> <script type="text/j ...

Can you please identify the issue with my code?

Please help me identify the issue. Here are the errors: Notice: Undefined variable: name in C:\wamp\www\3arabschool\admin\section_insert.php on line 10 Check out the source code below: <?php include("../config/config.php") ...

Locate items within PHP query output

I have been successfully loading values from a custom category table in my Joomla 2.5 website. Everything works fine when displaying the category names. However, I am facing an issue when trying to add categories with a specific ID to a new array. In C#, ...

Updating the output without the need for a page refresh following the insertion of data into the database

I'm interested in enhancing the interactivity of this section in my code. Currently, I utilize a form to send announcements via ajax to a php file which successfully updates my database. The table displays the data effectively. However, I want these c ...