PHP: Encode image Base64 local - php

I want to convert a image to Base64 and put in into my database.
I know how to encode a image to Base64, but I dont know how to use a file from a user.
So the user can "upload" a file with <input type="file" />
But how can I approach that file without download the file and store it at my server?
So i encode the file actually localy on the user his/her computer
Thanks

The BLOB datatype is best for storing files.
This PHP sample goes over it pretty well
Also see: How to store .pdf files into MySQL as BLOBs using PHP?
The MySQL BLOB reference manual has some interesting comments
if you do not want to save the file to the database, but just read it, use:
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
$content here has the file content

To encode an image to base64 you can use file_get_contents to read the image file:
$imageBinaryString = file_get_contents('/image/file/path.png');
http://us1.php.net/file_get_contents
Then base64 encode:
$base64_imageString = base64_encode($imageBinaryString);
You can then store in database in a column with type text or varchar.

<input type="file" name="icon" />
Now try with below code.
$base = $_REQUEST['icon'];
$binary = base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen('upload/imagename.png', 'wb');
$imagename = 'path_to_image_/images.png';
fwrite($file, $binary);
fclose($file);

Related

Submitting Image From Form Apparently Wrong Octet

A simple form with an image viewer below it in the same test.php script, the image gives errors in displaying. Disabling the headers and viewing the image data on the screen, it seems to have many of the little black ? diamonds all over it so probably somehow the wrong octet is being submitted. Where does the encoding get lost and how do I fix it?
To clarify, I am not trying to upload and save the file anywhere and I am not trying to insert it into a database. I simply want the data stream to directly display itself on the screen.
Also, the conditional around the PHP code is simply so that it does nothing until it receives a file. No validation needed as this is used only locally on my development system as a test tool.
test.php
<form method="POST" action="test.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><input name="insert" type="submit" value="Upload">
</fieldset>
</form>
<?php
if (isset($_FILES['fileToProcess'])) :
$file = $_FILES['fileToProcess'];
$image = file_get_contents($file['tmp_name']);
// TEST ConvertImage() FUNCTON HERE
// Get the image mime type
$mimetype = Array("1" => "image/gif",
"2" => "image/jpeg",
"3" => "image/png",
"6" => "image/bmp");
// Add headers and output the image
Header("Pragma: no-cache");
Header('Content-type: ' . $mimetype[exif_imagetype($image)]);
echo $image;
endif;
?>
I guess you are trying to display uploaded image. in your code I see that you are trying to validate to ensure that user submit only images. In php they are just two best method to ensure that submitted files are not virus but image
1.) using Getimagesize Function
2.) Fileinfo method.
I have implemented the validation in your code to ensure workability.
First create a directory call uploads where files will be uploaded and run this your update code
<form method="POST" action="test.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><div class="ButtonCenter">
<input name="insert" type="submit" value="Upload">
</div>
</fieldset>
</form>
test.php
<?php
if (isset($_FILES['fileToProcess'])) {
$uploadDir = "uploads/";
$filename= $_FILES['fileToProcess']['name'];
$file_types=array(
'image/gif',
'image/jpeg',
'image/png',
'image/jpg',
'image/GIF',
'image/JPEG',
'image/PNG',
'image/JPG'
);
// validate image using getimagesize function
$image_info =getimagesize($_FILES['fileToProcess']['tmp_name']);
//print_r($image_info);
$mime_image = $image_info['mime'];
// ensure the file is image via getimagesize function
if ( ! ( in_array($mime_image, $file_types) ) ) {
echo "you can only upload images";
exit();
}
//validate image using file info function
$f = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($f, $_FILES['fileToProcess']['tmp_name']);
if ( ! ( in_array($mime, $file_types) ) ) {
echo "You can only upload Images";
exit();
}
finfo_close($f);
if(move_uploaded_file($_FILES['fileToProcess']['tmp_name'],"$uploadDir/".$filename)) {
echo "File uploaded successfully";
echo "<img src='uploads/$filename' width='100px' height='100px'>";
}
}
?>
After fighting with this for two days, I just found the problem although I don't fully understand the reason it makes a difference. Apparently the form and the viewer cannot be on the same page so splitting them into two files works perfectly:
test.php
<?php
if (!isset($_FILES['fileToProcess'])) : ?>
<div class="PageCaption">Site Administration<hr></div>
<form method="POST" action="testviewer.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><div class="ButtonCenter">
<input name="insert" type="submit" value="Upload">
</div>
</fieldset>
</form><?php
endif; ?>
testviewer.php
<?php
if (isset($_FILES['fileToProcess'])) :
$file = $_FILES['fileToProcess'];
$image = file_get_contents($file['tmp_name']);
// Get the image mime type
$mimetype = Array("1" => "image/gif",
"2" => "image/jpeg",
"3" => "image/png",
"6" => "image/bmp");
// Add headers and output the image
Header("Pragma: no-cache");
Header('Content-type: ' . $mimetype[exif_imagetype($image)]);
echo $image;
endif;?>

Attach image in a php form and use html2pdf

i have a php form and use html2pdf (TCPDF). The php form works when I use text and images that already include in the form, but now I want to attach a image and also include that in the pdf file.
The code I am using now I get the filename.
To attach the image I am using
$<span><input type="file" name="foto"></span>
And to include it in the pdf-file I use this code
$foto = $_POST['foto'];
$content .= '<img src='.$foto.'with=200 height=auto>';
Sorry for my bad English!
Regards
Daniel
Do an normal HTML file upload like this:
<form method="post" enctype="multipart/form-data">
<label>Deine Datei ;) :
<input name="fileUpload" type="file" accept="image/*">
</label>
<label>Your Name:
<input name="userName" type="text" accept="image/*">
</label>
<button type="submite" name="submite">Upload</button>
</form>
And on the PHP side you must move your file:
if(isset($_POST["submit"])) {
$userName = $_POST['userName']; // the normale methode
$check = getimagesize($_FILES["fileUpload"]["tmp_name"]);
if($check !== false) {
$temp_path_to_file = $_FILES['fileUpload']['tmp_name'];
$file_content = file_get_contents($temp_path_to_file);
// and now past your image to your PDF.
// if you want to save the image on the server you must move it with this (its not necessary if you want only to past it in your PDF)
if(move_uploaded_file($temp_path_to_file, '/my/image/folder/image_'.uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION);
}
}
EDIT:
For your example you must convert the $file_content to an base64 string. Than you can past it in your image:
$base64 = 'data:image/' . pathinfo($filename, PATHINFO_EXTENSION) . ';base64,' . base64_encode($file_content);
echo '<img src="'. $base64 .'" style="with: 200; height: auto">';

Upload files without using php but no php form

I have a C program running on the localhost server which generates some files( writes its output to these file). Then I zip all these files together using php. Now I want to upload the zip file produced to mysql server using some php script but i dont want the user to upload these files using a form by clicking choose file button but i would like to upload these automatically as soon as they are generated to mysql using php script.
<?php
//get content of json file
require_once("zip.php");
$str = file_get_contents("program/heatmap_parameters.json");
//decode the JSON
$json = json_decode($str,true);
//echo '<pre>' . print_r($json, true) . '</pre>';
foreach ($json['parameters'] as $params) {
echo $params[3]."<br>";
$files_to_zip = array("program/".$params[3]);
var_dump($files_to_zip)."<br>";
//$files_to_zip = array("program/cctv2.mp4.json");
//if true, good; if false, zip creation failed
$zip_name = "program/".$params[3].".zip";
//zip the files
$result = create_zip($files_to_zip,$zip_name);
}
//connect to database
require_once("database/conn.php");
//upload zip file to database without displaying any form.
?>
I need a way to upload my generated file to saved to mysql without choosing it from the form.
<form action="" method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
include '../database/conn.php';
$sql = "INSERT INTO upload (name, content ) ".
"VALUES ('$fileName', '$content')";
$query = mysqli_query($conn,$sql);
if(!$query){
die("Cannot Insert".mysql_error());
}
}
How can i make this code such that it does not need the form
To answer your question in oneline,
You can not upload a file without form/input type file element, because that will a big security hole to web.
To upload any file to server, server need files object which has all the info of file. that info will be given by client from where you are uploading a file. It will also has the tmp location of file form where server will take that file.
You can copy file from one server to another, using curl or you can
write a bash script which will copy file from one place to another and
you can run that bash script using PHP.
Hope this helps to you!

Empty Image was saved on server

i need your help...i want to copy/upload images on server and saving directories in database...Problem is the images are empty =(
I'm using:
WampServer
Apache Version : 2.2.22
PHP Version : 5.3.13
MySQL Version : 5.5.24
Issue is that it's creating the file but is empty.... can it be WampServer fault?
CODE:
<input type="hidden" name="MAX_FILE_SIZE" value="30000">
<input name="image" id="image" multiple="true" type="file" />
<input name="name" id="name" type="text" maxlength="50" value="" placeholder="Enter Image Name" class="text-field"/>
if(isset($_POST['name']) && isset($_POST['image']))
{
$name = $_POST['name'];
$img = $_POST['image'];
$file_url = $img;
$fp = fopen($file_url, 'rb');
$content = fread($fp, filesize($file_url));
$fp = fopen('../Images/UploadedImages/'.$img, 'wb');
$image='../Images/UploadedImages/'.$img;
$result=mysql_query("insert into Images(Name,Directory,Register_Day)
values ('$name','$image',now())");
if (!$result) {
die("Failed to load");}
else{
fputs($fp, $content);
fclose($fp);
}
Uloading images doesn't work like that, you must do something like this:
$img = $_FILES['image']['tmp_name'];
Also note that you don't want to save the image into the database, you (probably) want to save the image to the server but you save only the file location into the database.
You cant upload image by using fopen. Try below code.
Your will get image details in $_FILES array not in $_POST.
$tmp_name = $_FILES['image']['tmp_name'];
$name = $_FILES['image']["name"];
$uploads_dir = '../Images/UploadedImages';
move_uploaded_file($tmp_name, "$uploads_dir/$name");
In above code $uploads_dir/$name will be your image path which you can store in db.
And also make sure that your <form> tag has enctype="multipart/form-data" attribute set.

help...! same page file upload to mysql

so i decided against using uploadify as i could not get any help on it. i've been now trying to implement a simpler solution. but unfortunately i cannot seem to process the upload code on a single page without receiving the following error:
Warning: fopen() [function.fopen]:
Filename cannot be empty in
C:\xampp\htdocs\speedycms\manageclient.php
on line 205
Warning: fread() expects parameter 1
to be resource, boolean given in
C:\xampp\htdocs\speedycms\manageclient.php
on line 206
Warning: fclose() expects parameter 1
to be resource, boolean given in
C:\xampp\htdocs\speedycms\manageclient.php
on line 208 Error, query failed
this is the code i've been trying to get to work... can you suggest any means of getting it all to work on a single page rather than splitting it up into two apart from ajax (im not too familiar with that)... its all on a single page
any help would be appreciated!
<!-- upload file --->
<?php
if (array_key_exists('uploadfile',$_POST)) {
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$uploadQry = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($uploadQry) or die('Error, query failed');
echo "<br>File $fileName uploaded<br>";
exit;
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?id=' . intval($client_id); ?>">
<p>
<b>File Upload</b></p>
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"><BR />
<input type="hidden" name="uploadfile" value="1"/>
<input name="upload" type="submit" id="upload" value=" Upload ">
</p>
<p> View files
</p>
<div id="viewFiles" style="display:none;" rel="facebox">
<div style="width:300px; height: 300px;"></div></div></form>
You need to set the correct encoding of your form to enable file uploads:
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
...
</form>
Edit: Filename cannot be empty is telling you that you have not specified the file name in your first call to fopen - you're passing in $tmpName to that method, which is assigned from $_FILES['userfile']['tmp_name'].
The only reason I can think of for $_FILES['userfile']['tmp_name'] to be empty is that you haven't actually uploaded a file?
The error message says that in
$fp = fopen($tmpName, 'r');
$tmpName is blank (or NULL).
Try looking in $_FILES to see what you've got:
print serialize($_FILES);

Categories