I have a form in which you can upload an image, which I then save to a folder on the server using php.
I'm storing the other data entered into the form in an xml-file, also using php. I now want to be able to store the pdf-file/the pdf-data in this xml-file as well for later use (the form acts as a template and I later want to store the entire information in another file and display it to the user).
I read about Base64 encoding etc. but I'm not sure if that applies to PDF-files as well because all I could find was how to do that for images or if there's an easier way to do it for my case?
Edit: Here's the HTML:
<form method="post" action="profile.php" enctype="multipart/form-data">
<input type="hidden" name="create_xml" value="true">
<label for="name">Name: </label><br>
<input type="text" name="name"><br>
<label for="email">E-mail: </label><br>
<input type="text" name="email"><br>
<label for="textbox">Write something: </label><br>
<textarea name="textbox" rows="5" cols="40"></textarea><br>
<label for="fileToUpload">Upload a PDF-file: </label>
<input type="file" name="fileToUpload" id="file-select">
<input type="text" name="filename" placeholder="Enter the name of your file"><br>
<input type="submit" value="submit" name="submit">
</form>
php that saves the data to the xml file:
if(isset($_POST['create_xml'])) {
$xml = new DOMDocument();
$newProfile = $xml->createElement('Profile');
$xml->appendChild($newProfile);
$name = $xml->createElement('Name', $name);
$newProfile->appendChild($name);
$email = $xml->createElement('EMail', $emailaddress);
$newProfile->appendChild($email);
$textbox = $xml->createElement('Text', $text);
$newProfile->appendChild($textbox);
$xml->formatOutput = true;
$xml->saveXML();
$xml->save($filename.".xml");
}
If you want to make xml at the time of insert data in DB:
if($this->input->post('submit')){
$name = $_POST['name'];
$email = $_POST['email'];
$filename = $_POST['filename'];
$year = gmdate("Y");
if($_FILES){
$_FILES['fileToUpload']['name'] = $files['fileToUpload']['name'];
$_FILES['fileToUpload']['type'] = $files['fileToUpload']['type'];
$_FILES['fileToUpload']['tmp_name'] = $files['fileToUpload']['tmp_name'];
$_FILES['fileToUpload']['error'] = $files['fileToUpload']['error'];
$_FILES['fileToUpload']['size'] = $files['fileToUpload']['size'];
$ext = pathinfo($_FILES['fileToUpload']['name'], PATHINFO_EXTENSION);
$mtime = uniqid(microtime());
$uniqueid = substr($mtime, 2, 8);
$pdfname = $uniqueid . '.' . $ext; // pdf file encrypt name here which need to save
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], 'uploads/' . $pdfname);
}
//Your insert query here remember here you should add $pdfname as pdflink
// If successful insertion than
$xml = new DOMDocument();
$newProfile = $xml->createElement('Profile');
$xml->appendChild($newProfile);
$name = $xml->createElement('Name', $name);
$newProfile->appendChild($name);
$email = $xml->createElement('EMail', $email);
$newProfile->appendChild($email);
$textbox = $xml->createElement('Text', $filename);
$newProfile->appendChild($textbox);
$pdflink = $xml->createElement('Text', $pdfname);
$newProfile->appendChild($pdflink);
$xml->formatOutput = true;
$xml->saveXML();
$xml->save($filename.".xml");
}
Related
I'm trying to upload an image of my HTML form into my MySQL blob column. the insertion is done successfully but the display of the image does not work properly knowing that images inserted directly into MySQL are displayed correctly.
HTML code:
<form class="form-horizontal" method='POST' action="add_question_submit.php" id="addQuestionForm" enctype="multipart/form-data">
<div class="form-group">
<textarea rows="4" cols="50" name="question" form="addQuestionForm" placeholder="Enter Question in brief.... " required></textarea><br>
<input type="file" class="form-control" id="image" name="image" required><br>
<input type="text" class="form-control" id="answer" placeholder="Enter Correct Answer" name="answer" required><br>
<input type="number" class="form-control" id="category_id" placeholder="Enter category id (only numeric)" name="category_id" required><br>
<input type="number" class="form-control" id="level_id" placeholder="Enter level id (only numeric)" name="level_id" required><br>
<input type="submit" name="submit" value="submit" class="btn btn-primary">
</div>
</form>
PHP code:
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image = getimagesize($file_temp);
$query = "INSERT INTO questions(question_name, image, answer, category_id,level_id)VALUES('$question', '$image','$answer', '$category_id', '$level_id')";
$result = mysqli_query($conn, $query);
header("Location: display_question.php");
display_question.php :
<td><?php echo '<img src="data:image/png;base64,'.base64_encode($row['image']).'" />'; ?></br><br/></td>
Below is the function which will upload the images to specific folder.
You can all below function like:
Param 1: is the folder where we need to store the new image
Param 2: is FILES
Param 3: if any prefix for the image we need to pass it.
Param 4: if there is any previously uploaded image for same record. It should be deleted from the folder. Generally it is usefull when you are editing particluar record.
uploadfile("profile",$_FILES,"profile_pic");
Code is here:
function uploadfile($folder,$data,$preFix = "logo_",$previousImage="") {
$location = (pathinfo($_SERVER['SCRIPT_FILENAME']));
$uploads_dir = $location['dirname'] . "/assets/uploads/" . $folder . "/";
$fileNames = "";
$tmp_name = $data["tmp_name"];
$name = $data["name"];
$fileExtension = pathinfo($name, PATHINFO_EXTENSION);
$newfilename = $preFix . date("ymdhms") . '.' . $fileExtension;
$fulldest = $uploads_dir . $newfilename;
if (move_uploaded_file($tmp_name, $fulldest)) {
if($previousImage != "")
$this->removePreviousImage($folder, $previousImage); //deleting existing image
return $newfilename;
} else {
exit("Error File Uploading");
}
}
First you are storing the wrong information onto the database, you are storing the file size and not the encoded image.
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image_size = getimagesize($file_temp);
$query = "INSERT INTO questions(question_name, image, answer, category_id,level_id)
VALUES('$question', '$file_temp','$answer', '$category_id', '$level_id')";
$result = mysqli_query($conn, $query);
header("Location: display_question.php");
Second, if you have stored the base64 encoded version of the file onto the database you do not need encode it again when you retrieve it from the database so your <img> tag should be
<?php echo "<img src='data:image/png;base64,$row[image]'/>"?>
</br><br/></td>
And thirdly and most importantly you need to be using parameterise bound queries to protect your app from SQL Injection Attack
$file_temp = base64_encode( file_get_contents( $_FILES['image']['tmp_name'] ) );
$image_size = getimagesize($file_temp);
$query = "INSERT INTO questions
(question_name, image, answer, category_id,level_id)
VALUES(?,?,?,?,?)";
$stmt = $conn->prepare($query);
$stmt->bind_params('sssss', $question,
$file_temp,
$answer,
$category_id,
$level_id);
$result = $stmt->execute();
if (!$result) {
echo $conn->error;
}
header("Location: display_question.php");
This code was run on my localhost. The images are uploaded to my mysql server using the localhost wampserver. Everything seems to be good. But when I migrate the code to the hosting site, I can't see the image uploaded in the mysql server. All I can see is my path "images-storage/" as the value of "photo" column, "images-storage" is empty and no image is stored.
This is the code:
My Form:
<form action="add.php" method="POST" enctype="multipart/form-data">
Firstname: <input type="text" name="firstname"><br />
Lastname: <input type="text" name="lastname"><br /><br />
<input type="file" name="image">
<input type="submit" value="Submit">
</form>
My form action:
<?php
include_once('config.php');
$fn = $_POST['firstname'];
$ln = $_POST['lastname'];
$name = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"];
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$error = $_FILES["image"]["error"];
if($error > 0) {
echo "Error";
} else {
$add_image = move_uploaded_file($temp,"uploaded/".$name);
$path = 'uploaded/'.$name;
$query = $mysqli->query("INSERT INTO info(fn,ln,name,photo) VALUES('$fn','$ln','$name','$path')");
}
header('Location: index.php');
?>
Just add "name" column in the database. Haha
I have a following code where I can upload a single image. This image gets stored in both database and folder. Now what I want is to add multiple images. How can I do that. Help me to come out of this.
<?php
$uploadDir ="C:/wamp/www/dragongym/customers/";
if(isset($_POST['submit']))
{
$intime =DATE("H:i", STRTOTIME($_POST['intime']));
$outtime =DATE("H:i", STRTOTIME($_POST['outtime']));
date_default_timezone_set('Asia/Calcutta');
$today = date("Y-m-d");
$msg="";
$res = "SELECT customer_id FROM customer ORDER by customer_id DESC LIMIT 1";
$qur = mysql_query($res);
while($row = mysql_fetch_array($qur, MYSQL_BOTH))
{
$last_id = $row['customer_id'];
$plus_id = 1;
}
if( $last_id !="")
{
$cust_id = $last_id + $plus_id;
}
$filePath="";
if($_FILES['cimage']['size'] > 0)
{
// echo $cust_id;
// Temporary file name stored on the server for pdf
$filename = basename($_FILES['cimage']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = $cust_id.'.'.$extension;
$tmpName1 = $_FILES['cimage']['tmp_name'];
$fileSize = $_FILES['cimage']['size'];
$fileType = $_FILES['cimage']['type'];
$filePath = $uploadDir . $new;
$resultes = move_uploaded_file($tmpName1, $filePath);
if (!$resultes)
{
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$new = addslashes($new);
$filePath = addslashes($filePath);
}
}
$sql = 'INSERT INTO customer(customer_name,roll_no,customer_number,customer_address,tariff_id,intime,outtime,customer_image,active,joining_date) VALUES("'.$_POST['name'].'","'.$_POST['roll'].'","'.$_POST['number'].'","'.$_POST['address'].'","'.$_POST['tariff'].'","'.$intime.'","'.$outtime.'","'.$filePath.'","1","'.$today.'")';
$msg="<p style=\"color:#99CC00; font-size:13px;\"> Successfully!</p>";
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
}
?>
<form action="#" method="post" enctype="multipart/form-data">
<h2>Registration Form</h2><?php echo $msg; ?>
<label>Name</label>
<input type="text" value="" name="name" id="name" required class="txtfield">
<label>Roll Number</label>
<input type="text" value="" name="roll" id="roll" required class="txtfield">
<label>Mobile Number</label>
<input type="text" value="" name="number" required class="txtfield" id="mobnum">
<label>Address</label>
<textarea name="address" class="txtfield"></textarea>
<label>Upload Photo</label>
<input type="file" value="" name="cimage" class="txtfield">
<!-- <label style="display: block">Timing</label>
<input type="text" value="" name="intime" placeholder="Intime" required class="timefield timepicker">
<input type="text" value="" name="outtime" placeholder="Outtime" required class="timefield timepicker">-->
<input type="submit" value="Save" name="submit" class="btn buttonside1">
</form>
You can use jquery plugin for that..
there is lots of plugin available on google..try this one http://blueimp.github.io/jQuery-File-Upload/
to do multiple file upload you should first have multiple="true" in your tab like so
<input type="file" name='files[]' multiple='true'/>
then use foreach loop to upload files.
Apologies if this is a duplicate question it just seems that every article i visit doesnt work for me.
I have a basic form which has two fields and a file.
<form action="make_announce.php" method="post" enctype="multipart/form-data" data-ajax="false">
<label>Enter Subject Line (500char max):
<input name="subject" type="text" id="subject" size="50"/></label>
<label>Announcement :
<textarea name="announce" cols="50" rows="10" id="announce"></textarea></label>
<label>Post Image (Leave Blank for NONE)<br>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="file" name="image" /><br /></label>
<div align="center">
<input type="submit" name="Submit" value="OK" />
</div>
</form>
And my PHP File minus most of the variables.
if (!empty($_FILES["image"])) {
$myFile = $_FILES["image"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
$sql="...
mysqli_query($con,$sql);
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
$sql="...
mysqli_query($con,$sql);
exit;
}
else
{
chmod(UPLOAD_DIR . $name, 0644);
$sql="...
mysqli_query($con,$sql);
exit;
}
}
mysqli_close($con);
Although this may not be the best way to do this it does work fine on a basic php web page. however when i put it into a jquery mobile web page it again works but doesnt seem to be posting the file im uploading. even after finding lots of articles telling me to add the data-ajax="false" to my form.
Any help would be very much appreciated.
Thanks in advance.
Turn off Ajax navigation using data-ajax="false" on your form definition because you can't upload files using Ajax.
I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.
I'm using the following code, but it isn't adding any data to the database;
(The session.php include contains the database connectivity.)
<?php include('includes/session.php');
$uploadDir = 'submitted/pictures/';
if(isset($_POST['submit']))
{
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$title = $_POST['title'];
$description = $_POST['description'];
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
mssql_query($query);
}
?>
The form code;
<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
<input type="submit" name="submit" value="Upload" class="button" />
</form>
I was wondering if someone could tell me what might be going wrong?
Thank you.
This code do not work because of several problems.
First, you should rename one of html fields or change field name when you are checking for upload:
<input type="submit" name="Upload" value="Upload" class="button" />
or
if(isset($_POST['submit']))
Second one, this script will not store any data into DB.
You should get, sanitize and write data into according fields, for example:
$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";
You should make sure these fields present in DB, if not - you should create them:
ALTER table user_pictures ADD column description text, add column title varchar(255);
You has an error at this line if(isset($_POST['Upload']))
Change this to the if(isset($_POST['submit']))
is the 'submitted/pictures/' writable? also you might want to run is_uploaded_file() for an extra layer of security.
Also your query seems to be wrong
"INSERT INTO $user_pictures ( file ) VALUES ('$filePath')"
$user_pictures needs to be a table
try
"INSERT INTO `user_pictures` ( `file` ) VALUES ('$filePath')"