I have the below base64 string generated from an app I'm testing out. It's supposed to generate an image but I can seem to get it to validate or display in HTML. I am trying to use PHP to decode and change to a JPG file but it seems the source of the base64 string may be the issue. Any thoughts?
I actually linked the file with the base64 in here since it's so many characters.
Thanks in advance!
PHP Code:
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
$source_type = "app";
if($pass == "Fan412") {
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../FOLDER_TO_IMAGES/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO TABLE_HERE (account, date, source_type, title, market, image) VALUES ('$account', '$date', '$source_type', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
}
Related
I am trying to create thumbnails from pdf uploads using Imagick. I wrote a script that's supposed to do it, but, it only uploads the file without creating a thumbnail.
This will certainly make some of you roll your eyes, but, PHP is completely uncharted territory to me. Could anyone help me out? Thanks!
<?php
include 'includes/session.php';
include 'includes/slugify.php';
if(isset($_POST['add'])){
$name = $_POST['name'];
$slug = slugify($name);
$category = $_POST['category'];
$price = $_POST['price'];
$description = $_POST['description'];
$filename = $_FILES['photo']['name'];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$allowed = array('pdf', 'doc', 'docx', 'odc', 'jpg');
$conn = $pdo->open();
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE slug=:slug");
$stmt->execute(['slug'=>$slug]);
$row = $stmt->fetch();
if($row['numrows'] > 0){
$_SESSION['error'] = 'document already exists';
}
else{
if(!in_array($ext, $allowed)) {
$_SESSION['error'] = 'Filetype not allowed';
}
else{
if(!empty($filename)){
$new_filename = $slug.'.'.$ext;
copy($_FILES['photo']['tmp_name'], '../documents/'.$new_filename);
}
else{
$new_filename = '';
creating a thumbnail
$img = new Imagick($filename[0]);
$img-> setImageFormat('jpg');
$convert = $slug. '.' .$jpg;
$img-> writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert);
}
try{
$stmt = $conn->prepare("INSERT INTO products (category_id, name, description,
slug, price, photo) VALUES (:category, :name, :description, :slug, :price, :
photo)");
$stmt->execute(['category'=>$category, 'name'=>$name,
'description'=>$description,
'slug'=>$slug, 'price'=>$price, 'photo'=>$new_filename]);
$_SESSION['success'] = 'document added successfully';
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
}
}
$pdo->close();
}
else{
$_SESSION['error'] = 'Fill up product form first';
}
header('location: documents.php');
?>
It looks like your call to $img->writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert) is incorrect: you're passing two strings (the filename of an uploaded image and what looks like a destination filename) but the Imagick documentation indicates you should be passing only a destination filename (along with an optional Boolean).
So this:
$img-> writeImages($_FILES['photo']['tmp_name'], '../images/'.$convert);
Should probably be:
$img-> writeImages('../images/'.$convert);
Also, it's hard to tell whether the two chunks of PHP that you posted come one after the other, but if they do, then your logic for when to create the images looks faulty:
if(!empty($filename)){
// Do some stuff
} else {
// Write the images
}
The problem here is that the block of code that writes the images only executes when $filename is empty. Shouldn't it write the images if $filename is not empty?
Last but not least, the Imagick writeImages() function returns a Boolean indicating whether it was successful. You should store this result and log it to see what the result is. You should also confirm that your destination filename ('../images/'.$convert) is correct, and that the path exists and is writable.
I have a base64 image that is a very long character count and when I try to send it via Fetch POST API it gets cut off and makes the image unacceptable by my PHP file server-side. The base64 is the b64data variable in my below code. Any solutions or ideas would be appreciated!
function submitPhoto(){
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
The PHP:
<?php
$title = $_POST['name'];
$market = $_POST['market'];
$account = "414890";
$date = date("Y-m-d");
$pass = $_GET['pass'];
$image = $_POST['picture'];
$title = $_POST['name'];
//$source_type = "app";
if($pass == "Fan412") {
//Clean base64 String
//$image = str_replace(' ', '', $image);
//Convert base64 into image
$filename_path = md5(time().uniqid()).".jpg";
$decoded=base64_decode($image);
file_put_contents("../MY_FOLDER/".$filename_path,$decoded);
// Insert Info into Database
$mysqli->query("INSERT INTO MY_TABLE (account, date, title, market, image) VALUES ('$account', '$date', '$title', '$market', '$filename_path')");
// close connection
$mysqli->close();
} else {
die();
} ?>
how about cut the base64_code into pieces then
post them before submit the whole form...
postData
{
'code': one piece_code,
'current_position': 1,
'full_pieces_count': a count you cut pieces
}
in php you can use redis to cache the base64_pieces with sorted_set piece1 piece2 ...( the score use the current_position you post)
after final pieces upload success...
combine them into pic to save then give js an img_url
then submit the whole form
btw: set the max length to post all the string...if it's too long...cut it and post them async/sync
How Can I Store a Base 64 Image to my Database and To my Server Folder. the Following Code is Using to Save that Image into My server Folder. but the image can't open.
$data = $src;
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data = base64_decode($data);
$file = '../emailtest'.rand() . '.png';
$success = file_put_contents($file, $data);
$data = base64_decode($data);
$source_img = imagecreatefromstring($data);
$rotated_img = imagerotate($source_img, 90, 0);
$file = '../emailtest'. rand(). '.png';
$imageSave = imagejpeg($rotated_img, $file, 10);
imagedestroy($source_img);
My advice:
1. Avoid to save binary to database, save it into file if possible.
2. Prefer to save binary into blob column better than save base64 into text column. Because base64 encode make this more bigger
Here is, i try to
1. download image from url
2. save binary into file
3. save binary to db
4. convert image binary to base64
5. display image base64 using html <*img> tag
try this code
DEMO
<?php
$img_url = 'http://cdn-o7.outfit7.com/wp-content/uploads/2016/01/Icon-r-512-3.png';
$img_binary = file_get_contents($img_url);
$ext = pathinfo($img_url, PATHINFO_EXTENSION);
$img_base64 = "data:image/".$ext.";base64," . base64_encode($img_binary);
//save into file
$name = "emailtest_".rand().$ext;
file_put_contents($name, $img_binary);
echo "<img src=\"$name\" title=\"show from file\"/>";
//store to db
/* create your new table for testing
CREATE TABLE IF NOT EXISTS `table_img` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`img_binary` blob NOT NULL,
`location` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
$insert="INSERT INTO table_img ('img_binary','location') VALUES('$img_binary','$name')"; //==>save to db using this query
$select="SELECT img_binary FROM table_img WHERE id=1"; //call your image binary using this query
// then convert binary into base64 with this : $img_base64= base64_encode(YOUR BINARY DATA FROM DATABASE);
//because i cant do it live in my server, i will shortcut call previous variable $img_base64 from above instead call binary from db and base64 encode
echo "<img src=\"$img_base64\" title=\"show from base64\"/>";
?>
I was introduced to Cropit recently and find it really easy to use but I am stuck at one area. I am trying to use Cropit and form submit. I am following the demo provided by Cropit.
Javascript:
$('form').submit(function() {
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$('#result-data').text(formValue);
// Prevent the form from actually submitting
return false;
});
PHP:
$encoded = $base64_string;
$decoded = urldecode($encoded);
$image_name = explode(';', $decoded);
$image_name = explode(':', $image_name[0]);
$image = array_pop($image_name);
$ext = explode('/', $image);
//decode the url, because we want to use decoded characters to use explode
$decoded = urldecode($encoded);
//explode at ',' - the last part should be the encoded image now
$exp = explode(',', $decoded);
//we just get the last element with array_pop
$base64 = array_pop($exp);
//decode the image and finally save it
$data = base64_decode($base64);
$str = random_string('alnum', 8);
$file = $str.'.'.$ext[1];
$data = $upload;
file_put_contents('assets/image_test/cropped/'.$file, $data);
It is able to output the file into my folder but the picture is just a blank screen with the dimension I set.
I have try to search the web but I couldn't find any solution to my problem.
Hope to get help from anyone who have encounter or know a solution.
I am working on a database where we need to have user form data and an image captured from a web cam then send the user data to the DB with a link to the photo on a file server. I am using the code found here http://davidwalsh.name/demo/camera.php (with added dataurl and base64 coding) for the image capture to canvas. I have searched for the past 2 weeks (unknown separate pieces of code changes and reversions) prior to posting here and have read a few people stating that a similar question has been asked about the Canvas.toDataURL() but it is just not working for me.
I am getting a file uploaded as a png but the file has a size of 0. I have no experience with other forms of coding (ruby/api/ajax/python) so I am not able to code with those. If those are mandatory then I will have to find another method (action script through Flash possibly) to make this work or abandon this until those scripts are learned.
Any info if this is even possible using PHP and mySQL would be helpful so I am not trying to create something that is not possible. The platofrm/delivery system will be an in house server on our intranet. currently testing on the web host server on windows computers running google chrome (also tested on firefox, opera and IE) Thanks in advance for taking the time to read through.
In my form.php
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var C = canvas.getContext('2d');
}
$('#canvas').submit()(function(event) {
// feel free to choose your event ;)
// just for example
// var OFFSET = $(this).offset();
// var x = event.pageX - OFFSET.left;
// var y = event.pageY - OFFSET.top;
// standard data to url
var imgdata = canvas.toDataURL('image/png');
// modify the dataUrl so the browser starts downloading it instead of just showing it
var newdata = imgdata.replace(/^data:image\/png/,'data:application/octet- stream');
// give the link the values it needs
$('a.linkwithnewattr').attr('download','your_pic_name.png').attr('href',newdata);
});
In my addcontent.php
<?php
include("connectionInfo.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$name = $_POST['name'];
$phone = $_POST['phone'];
$duedate = $_POST['duedate'];
$employee = $_POST['employee'];
$address = $_POST['address'];
$email = $_POST['email'];
$estimate = $_POST['estimate'];
$dataURL = $_POST["canvas"];
//input file into images folder
$image = str_replace('data:image/png;base64,', '', $dataURL);
$image = str_replace(' ', '+', $dataURL);
$image = base64_decode($dataURL);
$filename = "$duedate$name.png";
file_put_contents('images/' . $filename, $dataURL);
// create path for image upload
$path = "images/" . $filename;
move_uploaded_file($_FILES["file"]["tmp_name"],$path);
//show file location
echo "Stored in: ". $path;
//store file path in database
if(mysql_query("INSERT INTO JobBags (image) VALUES ('$path')")){
echo "Successfull!!";} else {
echo '---fail-sadface---';}
// put customer info into job bag database
$sql = "INSERT INTO JobBags (name, phone, duedate, employee, address, email, estimate, image)
VALUES ('$name', '$phone', '$duedate', '$employee', '$address', '$email', '$estimate', '$dataURL')";
//check if jobbag created correctly
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $mysqli . "<br>" . $conn->error;
}
// close connection to database
$conn->close();
?>