How to create a php image uploader with file system in which i could preview the thumb of image before uploading it to server and also validate the file before uploading.
I am using following code for image manipulation and saving.
HTML code:
<form id="imageform" enctype="multipart/form-data" method="post" action='upload.php'>
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" />
</div>
PHP Code:
<?php
// include ImageManipulator class
require_once('ImageManipulator.php');
if ($_FILES['fileToUpload']['error'] > 0) {
echo "Error: " . $_FILES['fileToUpload']['error'] . "<br />";
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newNamePrefix = 'Thumb' . '_';
$newNamePrefix1 = 'Highdef' . '_';
$manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
$manipulator1 = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
// resizing to 200x200
$newImage = $manipulator->resample(200, 200);
$newImage1 = $manipulator1->resample(1024, 768);
// saving file to uploads folder
$manipulator->save('uploads/thumbs/' . $newNamePrefix . $_FILES['fileToUpload'] ['name']);
$manipulator1->save('uploads/highDef/' . $newNamePrefix1 . $_FILES['fileToUpload']['name']);
echo 'Done ...';
$folder = 'uploads/thumbs/';
$filetype = '*.*';
$files = glob($folder . $filetype);
$count = count($files);
echo '<table>';
for ($i = 0; $i < $count; $i++) {
echo '<tr><td>';
echo '<a name="' . $i . '" href="#' . $i . '"><img src="' . $files[$i] . '" /></a>';
echo substr($files[$i], strlen($folder), strpos($files[$i], '.') - strlen($folder));
echo '</td></tr>';
}
echo '</table>';
} else {
echo 'You must upload an image...';
}
}
?>
Related
Any suggestion of how the "old_photo" variable could be specific name?
When this code is processed, the "old_photo" variable is only picked a random file. But, the variable "photo_input" is working fine.
In the HTML generated, all variables are correct, the main problem is in the reception of the "old_photo" variable.
// Images directory
if (is_dir($directorio)) {
if ($dh = opendir($directorio)) {
while (($file = readdir($dh)) !== false) {
if (strcmp($file, ".") and strcmp($file, "..")) {
list($ancho, $alto) = getimagesize(getcwd() . $separator . "images" . $separator . $file);
echo "<form action='" . htmlspecialchars($_SERVER['PHP_SELF']) . "' style='width:150px; height:150px; display:inline;' enctype='multipart/form-data' method='post' >";
echo "<input type='hidden' name='old_photo' value='".$file. "'>";
//echo "<input type='hidden' name='".$file."' value='".$file. "'>";
echo "<label for='photo_input'>";
echo "<img src='" . basename($directorio) . $separator . $file . "' height='100px' width='100px'/>";
echo "</label>";
echo "<input type='file' style='display:none;' id='photo_input' name='photo_input' onchange='this.form.submit()'>";
echo "</form>";
}
}
closedir($dh);
}
}
The values are collected by these functions:
function test_input($data)
{
return trim(stripslashes(htmlspecialchars($data)));
}
$cadena = "old_photo";
//$cadena = $value;
$imagen_antigua = test_input(filter_input(INPUT_POST, $cadena));
var_dump($imagen_antigua); // Nunca es correcta
I want to add image and text based mark on every image.
I am using this JavaScript for uploading multiple images.
<script>
$(document).ready(function() {
$(".add").click(function() {
$('<div><input class="files" name="user_files[]" type="file" ><span class="rem" ><a href="javascript:void(0);" >Remove</span></div><br />').appendTo(".contents");
});
$('.contents').on('click', '.rem', function() {
$(this).parent("div").remove();
});
});
</script>
For Uploading multiple images
<div class="form-group">
<div class="col-lg-10">
<input class="files" name="user_files[]" type="file" >
<br />
<span><a href="javascript:void(0);" class="add" >Add More</a></span>
<div class="contents"></div>
<div class="height10"></div><br />
<div><input type="submit" name="sub2" value="Upload Images" /> </div>
Here is the php which using for uploading & inserting into database
<!-- Image code starts here -->
<?php
$strmodelid=$_POST['txtmodelid'];
$strphotocat=$_POST['rbtnalbum'];
error_reporting(E_ALL & ~E_NOTICE);
#ini_set('post_max_size', '64M');
#ini_set('upload_max_filesize', '64M');
/* * *********************************************** */
// database constants
define('DB_DRIVER', 'mysql');
define('DB_SERVER', 'localhost');
define('DB_SERVER_USERNAME', 'admin');
define('DB_SERVER_PASSWORD', 'admin');
define('DB_DATABASE', 'databasename');
$dboptions = array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$DB = new PDO(DB_DRIVER . ':host=' . DB_SERVER . ';dbname=' . DB_DATABASE, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $dboptions);
} catch (Exception $ex) {
echo $ex->getMessage();
die;
}
//include"config/conn.php";
if (isset($_POST["sub1"]) || isset($_POST["sub2"])) {
// include resized library
require_once('imagecode/php-image-magician/php_image_magician.php');
$msg = "";
$valid_image_check = array("image/gif", "image/jpeg", "image/jpg", "image/png", "image/bmp");
if (count($_FILES["user_files"]) > 0) {
$folderName = "modelimgs/";
$sql = "INSERT INTO photogallery (catid,modelid,imgurl) VALUES ('$strphotocat','$strmodelid',:img)";
$stmt = $DB->prepare($sql);
for ($i = 0; $i < count($_FILES["user_files"]["name"]); $i++) {
if ($_FILES["user_files"]["name"][$i] <> "") {
$image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_FILES["user_files"]["tmp_name"][$i])));
// if valid image type then upload
if (in_array($image_mime, $valid_image_check)) {
$ext = explode("/", strtolower($image_mime));
$ext = strtolower(end($ext));
$filename = rand(10000, 990000) . '_' . time() . '.' . $ext;
$filepath = $folderName . $filename;
$filetitle = $_POST[txtname];
if (!move_uploaded_file($_FILES["user_files"]["tmp_name"][$i], $filepath)) {
$emsg .= "Failed to upload <strong>" . $_FILES["user_files"]["name"][$i] . "</strong>. <br>";
$counter++;
} else {
$smsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> uploaded successfully. <br>";
$magicianObj = new imageLib($filepath);
$magicianObj->resizeImage(295, 295);
$magicianObj->saveImage($folderName . 'thumb/' . $filename, 100);
/* * ****** insert into database starts ******** */
try {
$stmt->bindValue(":img", $filename);
$stmt->execute();
$result = $stmt->rowCount();
if ($result > 0) {
// file uplaoded successfully.
} else {
// failed to insert into database.
}
} catch (Exception $ex) {
$emsg .= "<strong>" . $ex->getMessage() . "</strong>. <br>";
}
/* * ****** insert into database ends ******** */
}
} else {
$emsg .= "<strong>" . $_FILES["user_files"]["name"][$i] . "</strong> not a valid image. <br>";
}
}
}
// $msg .= (strlen($smsg) > 0) ? successMessage($smsg) : "";
//$msg .= (strlen($emsg) > 0) ? errorMessage($emsg) : "";
header("location:photo_add.php");
} else {
$msg = errorMessage("You must upload atleast one file");
}
}
?>
<!-- image code ends here -->
You would do something like this:
// *** Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// *** Add watermark to bottom right, 50px from the edges
$magicianObj -> addWatermark('monkey.png', 'br', 50);
// *** Save watermarked image as a PNG
$magicianObj -> saveImage('racecar_small.png');
See: this page
So I've created this function where you upload an image to the server together with some information.
The text information is saved to a database while the image is saved to a folder.
Then I echo out the image together with the information that was stored in the database.
But I want to enchance it some by adding a rating system.
The rating system that I have created store the stastistics inside a txt-file.
What I need help with is to swap the saving with statistics from the txt-file and store it inside the database instead.
This is how I echo out the image, along with the information and star function:
<?php
//Sortering
$order = "";
if(isset($_GET['order'])){
if($_GET['order'] == "date"){
$order = " ORDER BY date DESC";
}
}
if(isset($_GET['order'])){
if($_GET['order'] == "uppladdare"){
$order = " ORDER BY uppladdare";
}
}
//Database connection
$dbcon = mysqli_connect("");
$selectall = "SELECT * FROM mountains $order";
$result = mysqli_query($dbcon, $selectall);
while($row = mysqli_fetch_array($result)){
$information = ' Titel: ' . $row['titel'] . ' Uppladdare: ' . $row['uppladdare'] . ' Filnamn: ' . $row['filname'] . ' History: ' .$row['History'] . ' Datum: ' . $row['date'];
//Print out correct information to the uploaded image
echo "<br>";
echo "Title: " . $row['titel'] . "<br>";
echo "Uploader: " . $row['uppladdare'] . "<br>";
echo "Imagename: " . $row['filname'] . "<br>";
echo "History: " . $row['History'] . "<br>";
echo "Date: " . $row['date'] . "<br>";
echo "Image:";
echo "<br>";
echo "<form name='rating' id='rating'>
<div id='rating-area' class='shadow'>
<img src='stjärna.png' id='thumb1' data-value='1' />
<img src='stjärna.png' id='thumb2' data-value='2' />
<img src='stjärna.png' id='thumb3' data-value='3' />
<img src='stjärna.png' id='thumb4' data-value='4' />
<img src='stjärna.png' id='thumb5' data-value='5' />
</div>
</form>";
?>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ rating : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
<script>
$(document).ready(function(){
setInterval(function(){
$('#resultat').load('ajax.php');
},500);
});
</script>
<?php
$original = $row['filname'];
echo "<a class='fancybox' rel='massoravbilder' href='bilder/$original'> <img src='bilder/thumb_" . $row['filname'] . "' alt='$information' /></a>" . "<br>";
}
?>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ rating : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
Im still quite a beginner so I would appreciate if anyone could show me an easy way to solve this. Prefer it to be simple, like without restrictions when it comes to the vote.
Just upload each rate-onclick and echo the average of all the votes right beneath the stars.
Notes: The rating system works fine when just using textfile. ajax.php is the calculation master behind the function. And post.php sends the rating statistics to the tex-file.
You should do something like this. I don't know if fields exist but it's the way to follow. I hope it's give you an idea.
In your form
//...
while($row = mysqli_fetch_array($result)){
$information = ' Titel: ' . $row['titel'] . ' Uppladdare: ' . $row['uppladdare'] . ' Filnamn: ' . $row['filname'] . ' History: ' .$row['History'] . ' Datum: ' . $row['date'];
//Print out correct information to the uploaded image
echo "<br>";
echo "Title: " . $row['titel'] . "<br>";
echo "Uploader: " . $row['uppladdare'] . "<br>";
echo "Imagename: " . $row['filname'] . "<br>";
echo "History: " . $row['History'] . "<br>";
echo "Date: " . $row['date'] . "<br>";
echo "Image:";
echo "<br>";
// Add the input with image id value (I suppose it exist)
echo "<form name='rating' id='rating'>
<div id='rating-area' class='shadow'>
<input type='hidden' name= 'image_id' value = $row[image_id]>
<img src='stjärna.png' id='thumb1' data-value='1' />
<img src='stjärna.png' id='thumb2' data-value='2' />
<img src='stjärna.png' id='thumb3' data-value='3' />
<img src='stjärna.png' id='thumb4' data-value='4' />
<img src='stjärna.png' id='thumb5' data-value='5' />
</div>
</form>";
Ajax
<script>
jQuery('div#rating-area img').click(function(e){
// serialize the form and retrieve all value in PHP with $_POST['theNameOfInput']
jQuery.post('post.php',{ form : $(this).serialize() },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
post.php
<?php
$imageId = (int) $_POST['image_id'];
// ... Your database treatments
$sql = "UPDATE image SET image_rating = image_rating + 1 WHERE image_id = $imageId";
//... Your code
i have the following HTML, JavaScript and PHP code to upload a text file which has a table and display it in the same page,
HTML:
<panel action="#" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" onchange="return ajaxFileUpload(this);">
</panel>
<iframe width="300px" height="300px" name="upload_iframe" id="upload_iframe" ></iframe>
JavaScript:
function ajaxFileUpload(upload_field)
{
var filename = upload_field.value;
upload_field.form.action = 'upload_file.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
return true;
}
PHP:upload_file.php
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$filepath = $_FILES["file"]["name"];
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
echo '<table border=1>';
while (!feof($file)) {
$line = fgets($file);
$first_char = $line[0];
if ($first_char != '*' && $first_char != '^' && trim($line) != '') {
if (strstr($line, '|')) {
$split = explode('|', $line);
echo '<tr>';
foreach($split as $line) {
echo '<td>'.$line.'</td>';
}
echo '</tr>';
} else {
echo '<tr><td>'.$line.'</td></tr>';
}
}
}
echo '</table>';
} else {
echo 'the file does not exist';
}
}
?>
Now, i have the following php code to read/extract the file contents and display it in another text file, but i cannot get the output with this code. This code works fine when i tried to read/extract the values form an input in html page, am i thinking in the right direction ? how can i achieve this?
PHP:
file_put_contents($file, "\n File Contents: ", FILE_APPEND | LOCK_EX);
//$ret = file_put_contents($file, $_POST['file'], FILE_APPEND | LOCK_EX);
ajaxFileUpload cannot send a $_FILESvariable (only with exporer or old browsers)
I sugest you to Upload your file with normal file input.
You don't need copy the uploaded file to a directory after sent form.
Only get the temporany file contents with file_get_contents of $_FILES["file"]["tmp_name"];
I have the following code stored in a 'genxml.php' that generates markers on google maps. The file is called from another file 'mobileInterface.php'. If I add another marker location in the database everything is working fine on a computer browser, the only problem that I have is when loading from a mobile browser, markers do no update instantly, I have to exit the browser and load it again to update. Else I have to load the 'genxml.php' directly from the URL, sort of downloading the contents and then load 'mobileInterface.php' again.
I have tried not caching the page contents but still I have this problem. Any ideas please?
//genxml.php
$query = "SELECT * ,DATE_FORMAT( ts, '%d-%m-%Y : %H.%i.%s' ) as tz FROM dataentry WHERE caseStatus = 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'id="' . parseToXML($row['id']) . '" ';
echo 'riskCategory="' . parseToXML($row['riskCategory']) . '" ';
echo 'EventAccidentSubject="' . parseToXML($row['EventAccidentSubject']) . '" ';
echo 'description="' . parseToXML($row['description']) . '" ';
echo 'peopleInvolved="' . parseToXML($row['peopleInvolved']) . '" ';
echo 'hazards="' . parseToXML($row['hazards']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'caseStatus="' . parseToXML($row['caseStatus']) . '" ';
echo 'ts="' . $row['tz'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
//mobileInterface.php
var mobileInterfaceServer = "http://10.0.0.21/genxml.php";
downloadUrl(mobileInterfaceServer, function(markers) {//replace markers with data
var xml = markers.responseXML;//replace markers with data
var markers = xml.documentElement.getElementsByTagName("marker");
selectBox = document.getElementById('destination');
for (var i = 0; i < markers.length; i++) {
var riskCategory = markers[i].getAttribute("riskCategory");
var EventAccidentSubject = markers[i].getAttribute("EventAccidentSubject");
var address = markers[i].getAttribute("address");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
html = "<b>" + EventAccidentSubject + "</b> <br/>" + address;
displayLocation(markers[i]);
//displayLocation(point);
addOption(selectBox, markers[i].getAttribute("EventAccidentSubject"), point);
bindInfoWindow(marker, map, infoWindow, html);
}
Add a timestamp to the request for data from the server as described in this answer