php image file upload and convert to base64 without saving image - php

I know how to upload image file and save to other location by using the following code. However, I need to do in such a way that user upload image and automatically convert to base64 without saving that image in my location. How should I do?
<?php
//print_r($_FILES);
if(isset($_FILES['image']))
{
$errors=array();
$allowed_ext= array('jpg','jpeg','png','gif');
$file_name =$_FILES['image']['name'];
// $file_name =$_FILES['image']['tmp_name'];
$file_ext = strtolower( end(explode('.',$file_name)));
$file_size=$_FILES['image']['size'];
$file_tmp= $_FILES['image']['tmp_name'];
echo $file_tmp;echo "<br>";
$type = pathinfo($file_tmp, PATHINFO_EXTENSION);
$data = file_get_contents($file_ext);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "Base64 is ".$base64;
if(in_array($file_ext,$allowed_ext) === false)
{
$errors[]='Extension not allowed';
}
if($file_size > 2097152)
{
$errors[]= 'File size must be under 2mb';
}
if(empty($errors))
{
if( move_uploaded_file($file_tmp, 'images/'.$file_name));
{
echo 'File uploaded';
}
}
else
{
foreach($errors as $error)
{
echo $error , '<br/>';
}
}
// print_r($errors);
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<p>
<input type="file" name="image" />
<input type="submit" value="Upload">
</p>
</form>

There is a mistake in your code:
$data = file_get_contents( $file_ext );
This should be:
$data = file_get_contents( $file_tmp );
This should solve your problem.

Related

Upload image and display it to user

I'm trying to upload a file to a server then display it to the user. I'm having difficulties to display the image to the user.
If you could provide code that helps me out to display the image to the user. The code should fit in the php file right under //Display image here <---------
html file
<html>
<body>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="fileToUpload" id="fileToUpload" size="35">
<br>
<br>
<input type="submit" value="Upload" name="upload">
</body>
</html>
php file
<?php
if(isset($_FILES["fileToUpload"])){
$file = $_FILES['fileToUpload'];
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];
$fileError = $_FILES["fileToUpload"]["error"];
$fileType = $_FILES["fileToUpload"]["type"];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
//Image code
if($fileError === 0){
if($fileSize < 500000){
$fileDestination = 'uploads/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
header("Location: server.php?uploadsuccess");
//Display image here <----------
}else{
echo "Your file is too big!";
}
}else{
echo "There was an error while uploading your file!";
}
}else{
if(isset($_FILES["fileToUpload"])){
$file = $_FILES["fileToUpload"]["name"];
echo "File: ".$file;
}
}
}
?>
first you have to change .html file to .php and note that i have renamed file as index.php
<html>
<body>
<?php if(isset($_GET['filename'])){ ?>
<img src="<?php echo $_GET['filename']; ?>" />
<?php } ?>
<form method="post" enctype="multipart/form-data" action="server.php">
<input type="file" name="fileToUpload" id="fileToUpload" size="35">
<br>
<br>
<input type="submit" value="Upload" name="upload">
</body>
</html>
server.php
<?php
if(isset($_FILES["fileToUpload"])){
$file = $_FILES['fileToUpload'];
$fileName = $_FILES["fileToUpload"]["name"];
$fileTmpName = $_FILES["fileToUpload"]["tmp_name"];
$fileSize = $_FILES["fileToUpload"]["size"];
$fileError = $_FILES["fileToUpload"]["error"];
$fileType = $_FILES["fileToUpload"]["type"];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
//Image code
if($fileError === 0){
if($fileSize < 500000){
$fileDestination = 'uploads/'.$fileName;
move_uploaded_file($fileTmpName, $fileDestination);
// header("Location: server.php?uploadsuccess");
//Display image here <----------
header("Location:index.php?filename=$fileDestination");
}else{
echo "Your file is too big!";
}
}else{
echo "There was an error while uploading your file!";
}
}else{
if(isset($_FILES["fileToUpload"])){
$file = $_FILES["fileToUpload"]["name"];
echo "File: ".$file;
}
}
}
?>
I have done using php but better option is using ajax call .just google it you will get man examples
To be able to display the image, do this :
//Display image here <----------
echo "<img src='" . $fileLocation . "'>";
Replace $file_location with the variable containing the file location
<!-- index.php -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file2upload">
<input type="submit" value="upload">
</form>
<!-- sorry i didn't got php code section here , so i m posting php file code here -->
<!-- upload.php file -->
<?php
// target directory where files goes after uploading
$target_dir = "uploads/pictures/";
// target files name and extension save to this target_file variable
// $target_file specifies the path of the file to be uploaded
$target_file = $target_dir . basename($_FILES["file2upload"]["name"]);
$uploadOk = 1;
// checking that target_file is been uploading is a true image file extenion or not
// $audioFileType holds the file extension of the file (in lower case)
$picFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
echo $picFileType."<br />";
if(isset($_POST["submit"])) {
// The filesize() function in PHP is an inbuilt function which is used to return the size of a specified file.
// The filesize() function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure.
$check = getimagesize($_FILES["file2upload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// step:2
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// step: 3
// Check file size
if ($_FILES["file2upload"]["size"] > 5000000) { // 5MB manual set
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// step: 4
// Allow certain file formats
if($picFileType != "jpeg" && $picFileType != "jpg" && $picFileType != "bmp" && $picFileType != "gif" && $picFileType != "png" ) {
$uploadOk = 0;
echo "<b style='color:red;'> File to be uploading is not have image formates like : .jpeg,.jpg,.bmp, .gif, .png etc </b><br />";
}
// step: 5
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file2upload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["file2upload"]["name"]). " has been uploaded. <br />";
<!-- this is the ANSWER -->
<!-- ----------------------------- -->
echo $file_name = basename( $_FILES["file2upload"]["name"]);
echo $file_size = $_FILES["file2upload"]["size"];
echo $fileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
<!-- ----------------------------- -->
}
else {
echo "Sorry, there was an error uploading your file.";
}
}
// }else{ echo "<b style='color:red;'> form have diffrent method ( post/get ) </b><br />"; $uploadOk = 0; }
?>

how to upload and convert image in base64 without storing the image in php

I can upload the image and save it in any location, then I convert that image in base64. but how can we do that we convert image in base64 without saving it. any solution please?
$photoTmpPath = $_FILES['filename']['tmp_name'];
$data = file_get_contents($photoTmpPath);
$base64 = base64_encode($data);
and if you want to test:
header('Content-type: image/png');
echo $data;
exit;
If you have a Web Form which manages your Image upoad through $_POST. You could use this ..
<?php
if(isset($_POST)){
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
$type = $_FILES['file']['type'];
$tmp_name = $_FILES['file']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$target_path = basename( $_FILES['file']['name']);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['file']['name'])." has been uploaded";
$im = file_get_contents($_FILES['file']['name']);
$imdata = base64_encode($im);
var_dump($im);
unlink($_FILES['file']['name']);
}
}else{
echo 'Please choose a File';
}
}
}
?>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>

PHP multiple images upload

I know this question is repeated over and over.. But can't seem to find solution for my problem...
How can I create a form which will allow user to upload xy images at once?
Here's my html code:
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
And here's my php code:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>
Is it possible to solve this problem with foreach? If so, how should I do that?
Try this (add as many file fields as you want):
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" />
Php:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
echo "<p>$status</p>";
}
}
?>
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[1]" multiple="multiple">
<input id="image" type="file" name="image[2]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
PHP
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image1']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image1']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image1']['tmp_name'], $path))
if( #is_uploaded_file($_FILES['image2']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image2']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image2']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
}}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>

Multiple File Upload PHP

I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories