PHP - Get base64 in data - php

How can I get the base64 value properly in PHP from a submitted data?
The data being passed on is
data:image/png;base64,LongBase64ValueHereOfAnImage
Right now, I can only get it by
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list($data) = explode(',', $data);
$data = base64_decode($data);
Is there a proper way to get the base64 value?

This could be done in one line with regex
$data = $_POST['image'];
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

try this: uploading image code.
if (count($_FILES) > 0) {
if (is_uploaded_file($_FILES['image']['tmp_name'])) {
$conn = mysqli_connect('localhost', 'username', 'password', 'databasename');
$imgData = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$imageProperties = getimageSize($_FILES['image']['tmp_name']);
$sql = "INSERT INTO upload(image) VALUES('$imgData')";
$current_id = mysqli_query($conn, $sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error($conn));
if (isset($current_id)) {
echo 'done';
}
}
}
And then get data using base64
$sql = "SELECT * FROM upload WHERE id = 113";
$sth = $conn->query($sql);
$result = mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,' . base64_encode($result['image']) . '"/>';

Related

Rebuilding a jpg from blob

Edited and started over to better describe my issue.
I have this code that displays an image from a database using blob data.
function getContent($db) {
$query = "SELECT name, animalid, image, thumb FROM images ";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent($db);
foreach($data as $row) {
$id = $row['id'];
$image = $row['image'];
$thumb = $row['thumb'];
echo '<img src="data:thumb/jpg;charset=utf8;base64,'.$image.'">';
}
This code displays a image on the page, when viewing the source code i see the blob data that the image is made from, what i need is to actually make an image that i can name properly.
How do i make a ******.jpg from the blob data?
Use base64_encode. You should use image/jpeg MIME type without charset.
function getContent($db) {
$query = "SELECT name, animalid, image, thumb FROM images ";
$sql = $db->prepare($query);
$sql->execute();
return $sql->fetchAll();
}
$data = getContent($db);
foreach($data as $row) {
$id = $row['id'];
$image = $row['image'];
$thumb = $row['thumb'];
// $image is the BLOB
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}

Issue with LONGBLOBs in MySQLi

I'm trying to insert LONGBLOBs to my database. Unfortunately when I click insert nothing is being inserted in the db. When I change the column type to BLOB everything is fine but the blob size capacityis too small so I really need LONGBLOBs. Using blob I can add only a 64kb file. Using longblob I can insert a file which is much larger. What's why I need to use LONGBLOB. I'm using MySQLi and PHP. Could you help me out?
if($_POST && $_FILES['uploadFile']['size'] > 0) {
$name = $_FILES['uploadFile']['name'];
$_SESSION['fileType'] = $_FILES['uploadFile']['type'];
$data = $_FILES['uploadFile']['tmp_name'];
//$data = addslashes($data);
$ifImage = getimageSize($_FILES['uploadFile']['tmp_name']);
$getAuthorID = $_SESSION['userID'];
$_SESSION['ifImage'] = $ifImage;
echo '<pre>'.print_r($_SESSION['ifImage'], true).'</pre>';
$fp = fopen($data, 'rw');
$content = fread($fp, filesize($data));
$content = addslashes($content);
fclose($fp);
/* SELECT FILE ID BY IT'S NAME */
$selectIDname= "SELECT fileID FROM files WHERE fileName = '$name'";
$selectIDnameQuery = mysqli_query($connection, $selectIDname);
$row = mysqli_fetch_array($selectIDnameQuery);
$selectIDname = $row['fileID'];
echo '<pre>ID: '.print_r($selectIDname, true).'</pre>';
$_FILES['uploadFile']['fileID'] = $row['fileID'];
/* INCREMENT FILE ID */
$selectFileIDQuery = mysqli_query($connection, "SELECT fileID FROM filescontent ORDER BY fileID DESC LIMIT 1");
$fetchFileID = mysqli_fetch_assoc($selectFileIDQuery);
$incrementFileID = $fetchFileID['fileID'] + 1;
/* GET AND INCREMENT FILE VERSION */
$getVersionsObject = new File($_FILES['uploadFile']['fileID']);
$fetchVersions = $getVersionsObject->getVersions();
$fetchLastElement = end($fetchVersions);
$incrementVersion = $fetchLastElement + 1;
echo '<pre>Version: '.print_r($incrementVersion, true).'</pre>';
/* SELECT FILE NAME FROM DB */
$selectName = mysqli_query($connection, "SELECT fileName FROM files WHERE fileName='$name'");
$fetchName = mysqli_fetch_assoc($selectName);
$fetchName = $fetchName['fileName'];
if(!strcmp($name, $fetchName)){
echo 'The file exists <br>';
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileExist($selectIDname, $incrementVersion, $content, $getAuthorID);
}
else{
echo 'The file does not exist';
$insertIntoFilesObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFiles = $insertIntoFilesObject->uploadContentIntoFiles($incrementFileID, $name, $getAuthorID);
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileNotExist($incrementFileID, $incrementVersion, $content, $getAuthorID);
}
$mysqliErorr = mysqli_error($connection);
echo '<br>'.$mysqliErorr.'<br>';
//header("Location: listFiles.php");
}
else if($_POST && $_FILES['uploadFile']['size'] == 0) {
echo 'You have not chosen a file';
}
}

Getting empty response, If blob field is there [PHP]

I have beem retrieving the data from mysqli db by php.
$query = "SELECT id, parentId, firstName, middleName, lastName, mobileNumber, photo FROM person WHERE orgId='".$orgId."' ";
$sql = mysqli_query($con, $query);
$data=array();
if($rows_count!=0){
while ($rows_fetch = mysqli_fetch_assoc($sql))
{
var_dump($rows_fetch);
$info = $rows_fetch;
array_push($data, $info);
$isSuccessful = true;
$code = 200;
}
}else{
$isSuccessful = true;
$code = 202;
}
$response = array("resp"=>$data, "code"=>$code, "isSuccessful"=>$isSuccessful);
If blob field is empty, I am getting response. If blob is there, I am getting empty response
while ($rows_fetch = mysqli_fetch_assoc($sql))
{
//var_dump($rows_fetch);
$info = $rows_fetch;
$info['photo'] = base64_encode($rows_fetch['photo']);
array_push($data, $info);
$isSuccessful = true;
$code = 200;
}
I have changing blob to base64 code.

Problems displaying blob images

This is my actual code, i'm starting to using php and i want to know how to display a blob image on my website.
But until now i can't find how to do it. This is my php code...
$query=mysqli_query($link, "SELECT image, titulo, tecnica, medidas FROM upload ");
$numrows = mysqli_num_rows($query);
$posts = array();
if ($numrows != 0)
{
while ($row = mysqli_fetch_assoc($query))
{
$post = new stdClass();
$post->image = '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'"/>';
$post->titulo = $row['titulo'];
$post->tecnica = $row['tecnica'];
$post->medidas = $row['medidas'];
array_push($posts, $post);
}
}
$jsonData = json_encode($posts);
header("Content-Type: image/jpeg");
echo $jsonData;
Try this:
<?php
//Connect to the database
$databasehost = "YOUR DATABASE HOST";
$databasename = "YOUR DATABASE NAME";
$databaseusername ="YOUR DATABASE USERNAME";
$databasepassword = "YOUR DATABASE PASSWORD";
$con = mysqli_connect($databasehost, $databaseusername, $databasepassword, $databasename) or die(mysqli_error($con));
mysqli_set_charset ($con, "utf8");
$sql = "SELECT image, titulo, tecnica, medidas FROM upload;";
$res = mysqli_query($con, $sql);
$result = array();
while($row = mysqli_fetch_array($res)) {
array_push($result,
array(
'image'=>base64_encode($row[0]),
'titulo'=>$row[1],
'tecnica'=>$row[2],
'medidas'=>$row[3]
));
}
echo json_encode(array($result));
mysqli_close($con);
This will print your data like this:
{[{"image":"IMAGE ENCODED IN BASE 64","titulo":"SOME
DATA","tecnica":"SOME DATA", "medidas":"SOME DATA"},
{"image":"IMAGE ENCODED IN BASE 64","titulo":"SOME
DATA","tecnica":"SOME DATA", "medidas":"SOME DATA"},
{"image":"IMAGE ENCODED IN BASE 64","titulo":"SOME
DATA","tecnica":"SOME DATA", "medidas":"SOME DATA"}]}
Hope it helps! Good Luck! Happy Coding!

Problems deleting File PHP

This is my code to pull information from my sql database and then I want to delete the .txt files in each directory, but I can't seem to figure out why it won't delete the files.
<?php
session_start();
$user = $_SESSION['SESS_USERNAME'];
$id = array();
$id = $_POST['selected'];
//Include database connection details
require_once('config_order.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if (!$db) {
die("Unable to select database");
}
//Create query
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
// display query results
while ($row = mysql_fetch_array($query)) {
$c_name = $row['clientname'];
$sitestreet = $row['sitestreet'];
$inspector = $row['inspector'];
}
mysql_close($link);
$client_name = str_replace(" ", "_", $c_name);
$site_street = str_replace(" ", "_", $sitestreet);
$client_name = "{$client_name}.txt";
$site_street = "{$site_street}.txt";
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (unlink($client_path . "/" . $client_name)) {
echo 'File Deleted';
} else {
echo 'File could not be deleted';
}
?>
I think this is because your while loop is overwriting the $c_name, $sitestreet and $inspector variables. This means you will only ever delete the last file.
Is this what you were trying to do? (Edited Again...)
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` IN (".mysql_real_escape_string(implode(',',$id)).")");
while ($row = mysql_fetch_array($query)) {
$inspector = $row['inspector'];
$client_name = str_replace(" ", "_", $row['clientname']).'.txt';
$site_street = str_replace(" ", "_", $row['sitestreet']).'.txt';
$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
if (!file_exists($client_path.'/'.$client_name)) {
echo "File $client_path/$client_name does not exist!\n";
} else echo (unlink($client_path.'/'.$client_name)) ? "File $client_path/$client_name was deleted\n" : "File $client_path/$client_name could not be deleted\n";
}
mysql_close($link);
Try some extra debugging:
$realpath = $client_path . '/' . $client_name;
if (file_exists($realpath)) {
if (is_writable($realpath)) {
if (unlink($realpath)) {
echo "$realpath deleted";
} else {
echo "Unable to delete $realpath";
}
} else {
echo "$realpath is not writable";
}
} else {
echo "$realpath does not exist";
}
On first glance, this is a problem, if $_POST['selected'] is not an array:
$id = array();
$id = $_POST['selected'];
...
$query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'");
You are instantiating $id as an empty array, then overwriting it with $_POST['selected'], so $id[0] is the first character of the string $id.
For example, if $_POST['selected'] is 12345:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '$id[0]'"
is equivalent to:
"SELECT * FROM `PropertyInfo` WHERE `order_number` = '1'"
Either don't try to access it with an index or do $id[] = $_POST['selected']; to add the element onto the $id array instead.
Whether that is an array or not, you do need to either sanitize that input before you insert it into the query or use prepared statements, though!

Categories