mouse location tracking on uploaded image using html and javascript - javascript

I have written a code for tracking mouse location but my code is only working for the string but not for the image I am uploading.
It is generating the image icon but not the image.
<form action="click.php" method="post" enctype="multipart/form-data">
<h3>Select image to upload:<br/></h3>
<input type="file" name="fileToUpload" id="fileToUpload" accept="image/*"/>
click.php
<script>
function getPos(e) {
x = e.clientX;
y = e.clientY;
cursor = "Your Mouse Position Is : " + x + " and " + y ;
document.getElementById("displayArea").innerHTML=cursor
}
function stopTracking() {
document.getElementById("displayArea").innerHTML="";
}
</script>
</head>
<body>
<div id="focusArea" onmousemove="getPos(event)" onclick="merge" onmouseout="stopTracking()">
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check !== false) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$uploadOk = 1;
} else {
$uploadOk = 0;
}
}
header("Content-type: image/png");
imagepng($target_file);
imagedestroy($target_file);
?>
</div>
<p id="displayArea"></p>

Headers cannot be set after anything, they must be the first lines of any output.
This line:
header("Content-type: image/png");
Does not belong there. Enable errors as follows:
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
And you will get the error telling you that headers cannot be set.

Related

Send an image from server to canvas on a page

I have a form on page A.
I upload an image and post it to server.
Server uploads the image and redirects the user to page B.
I have a canvas on page B on which I want to draw that image using JavaScript.
Question:
How can the server send the image to page B?
here is my idea to to get path from server
<form action="pageA.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
pageA.php:
<?php
session_start();
$todir = "uploads/";
$file = $tooir . basename($_FILES["fileToUpload"]["name"]);
$_SESSION['img']=$todir;
$checkimg = 1;
$imageType = strtolower(pathinfo($file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$checkimg = 1;
} else {
echo "File is not an image.";
$checkimg = 0;
}if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $file)) {
$up=1 ;
$_SESSION['img']=$todir;
$_SESSION['up']=$up;
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
header("location:./pageB.php");
} else {
up=o;// checking whether file is uploaded
echo "Sorry, there was an error uploading your file.";
}
}
?>
pageB:(write session_start() at top & script at bottom of the page)
<?php
session_Start();
if($_SESSION['up'])
{
echo "<script>window.onload = function() {
var canvas=document.getElementById('myCanvas');
var context=c.getContext('2d');
var image=document.getElementById('draw');
ctx.drawImage(image,10,10);
};</script><img src=$_SESSION['img'] id=draw > <canvas id=myCanvas> </canvas>";
}
?>

Upload Images as array

I am trying to upload multiple images to a folder and is working properly. I have a problem when i am trying to store the name of images in database. If i upload just one is working. If i upload more than one I get just one name in my database.
Whats the way to upload, making an array with images titles, to my db?
Here is the code:
<div id="maindiv">
<div id="formdiv">
<h4>Upload Image for </h4>
<form enctype="multipart/form-data" action="" method="post">
<p class="alert alert-info">Only JPEG,PNG,JPG Type Image Uploaded. Image Size Should Be Less Than 100KB.</p>
<hr/>
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="add_images" id="upload" class="upload"/>
</form>
</div>
And here is my php:
if (isset($_POST['add_images'])) {
$j = 0;
$target_path = "images/";
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['file']['name'][$i]));//store extensions in the variable
$name_of_img = basename($_FILES['file']['name'][$i]);
$target_path = $target_path . $name_of_img;
$j = $j + 1;
if (($_FILES["file"]["size"][$i] < 1000000)
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
print_r($name_of_img);
$query = "UPDATE post SET ";
$query .= "images = '{$name_of_imgs}' ";
$query .= "WHERE post_id = {$the_post_id}";
$update_cruise_img = sqlsrv_query($con, $query);
} else {
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">Wrong file Size or Type</span><br/><br/>';
}
}
}
I tried by creating array like this $name_of_imgs = json_encode($_POST['file']);
but is not working
You need to update the post table outside the for loop.
if (isset($_POST['add_images'])) {
$j = 0;
$name_of_imgs = [];
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {
$validextensions = array("jpeg", "jpg", "png");
$ext = explode('.', basename($_FILES['file']['name'][$i]));//store extensions in the variable
$name_of_img = basename($_FILES['file']['name'][$i]);
// define target path here so that it won't concat the last value
$target_path = "images/" . $name_of_img;
$j = $j + 1;
if (($_FILES["file"]["size"][$i] < 1000000) && in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
$name_of_imgs[] = $name_of_img;
} else {
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">Wrong file Size or Type</span><br/><br/>';
}
}
// update here
$query = "UPDATE post SET ";
$query .= "images = '" . implode(',', $name_of_imgs) . "' ";
$query .= "WHERE post_id = {$the_post_id}";
$update_cruise_img = sqlsrv_query($con, $query);
}
You may consider creating another table for images.
Hello you have run update query in upload file. it's make sure this_post_id in single that's way may be update record in single file name.

How to display PHP echo with JavaScript in HTML?

I want to transfer PHP echo text into HTML through JavaScript.I've seen that it can be done with the function document.getelementbyid() and innerHTML but I tried and it did not work.
This PHP Code:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 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["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I want to echo the text displays in HTML Without switching to upload.php!!
On id statusbar I want to show echo text!
This HTML code:
<form action="../assets/php/upload.php" method="post" enctype="multipart/form-data">
<label>Izaberi fotografiju:</label>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit" onClick="info()">
<p id="statusbar"></p>
</form>
let's say you have to print this in your uploading html page
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
change this to below
if ($uploadOk == 0) {
$message = "Sorry, your file was not uploaded.";
header("Location: /index.php?message="$message);
// if everything is ok, try to upload file
}
then get the message and print in your html page
You have to write code inside <?php ?> tag.Like this.
<script type="text/javascript">
//js code..
<?php echo "Sory, only PNG, JPG, GIF"; ?>
</scrip>
You can directly echo things to html. You can also echo things to a js variable directly like this, then set the html content with js.
<script>
var string = <?php echo "Sory, only PNG, JPG, GIF"; ?>
document.getElementById("notify-container").innerText = string;
</script>
Say your HTML element was the following:
<div id="error"></div>,
you'd assign the error message to a JavaScript variable like so: <script>
var errorMsg = <?php echo "Sory, only PNG, JPG, GIF"; ?>
</script>
Then you can show the message like so:
document.getElementById('error').innerHTML = errorMsg;

Get bytes transferred using PHP5 for POST request

Note I am new to PHP, Apache and programming for servers so more thorough explanations will be appreciated.
Context
I created - in javascript - a progress bar to display when a file is uploaded. Current I have the progress bar update at a set frame-rate (to see if it works).
Clearly to make this an accurate progress bar, everything should in relation to the number of bytes transferred in comparison to the total number of bytes.
Question
using PHP5 how can I get information regarding the number of bytes transferred in relation to the total number of bytes of the file, such that I can pass that to a JS function updateProgress(bytesSoFar, totalBytes) to update my progress bar? Please verbosely walk me through the modifications needed to the code below to get this to work. I have seen xhr examples, but they are not thoroughly accessible.
I have just set up LocalHost and am using W3Schools' PHP File Upload tutorial. To get the simulated ''upload'' to work, I changed the local permissions as suggested in this S.O. post. I don't necessarily need to read the file, I just want to know many bytes have been transferred.
Code
Currently I have two files:
index.php
upload.php
index.php
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 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["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Update
I have found this code:
test.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
// move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
move_uploaded_file($_FILES["userfile"]["tmp_name"], "uploads/" . $_FILES["userfile"]["name"]);
}
?>
<html>
<head>
<title>File Upload Progress Bar</title>
<style type="text/css">
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="status"></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST" id="myForm" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
<script type="text/javascript">
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("myForm").onsubmit = startUpload;
})();
</script>
</body>
</html>
progress.php
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
$message = ceil($current / $total * 100) : 100;
$message = "$message"
echo "<script type='text/javascript'>alert('$message');</script>";
}
else {
echo 100;
}
?>
Which, like my previous code, transfers the file. However, this doesn't show the bytes until the end (even though it should alert for that), also it opens a new window with the "Done." statement in the previous window.
You can check out this Php File Upload Progress Bar that may help you get started in case you insist on using Php to display progress. This uses the PECL extension APC to get uploaded file progress details. It is possible to calculate the number of bytes received by the server using the response of
apc_fetch() as per the first link.
Another interesting Track Upload Progress tutorial that uses Php's native Session Upload Progress feature.
Lastly, if you are a little open to using Javascript (or a JS library), that would be ideal. An easy to use, easy to setup, well known and a maintained library that I know of is FineUploader
You can use the Session Upload Progress feature. It's native but require some php.ini configuration.
Please, take a look at the PHP manual.
UPDATE 1
Note, you don't need to change your upload.php. You can create a new php file (ex. progress.php) and make requests to them to check the upload progress with your JS.
progress.php
<?php
$upload_id = $_GET['upload_id];
print json_encode($_SESSION['upload_progress_'.$upload_id]);
Then your JS will make a GET request to progress.php?upload_id=YourIdValue and you will receive a JSON with all progress information.

PHP File upload not working after completing all the steps. (I think)

Here's my background:
I'm using Amazon EC2 Linux Instance running Apache and LAMP.
I'm trying to make a PHP image upload.
I got the code from W3Schools.
I have tried signing in as Superuser (su) and changing the permissions on the upload folder (/var/www/html/photo/backend/images/uploads) to chmod 755.
I have tried running print_r($_FILES); and get Array ( ).
I've changed these things in php.ini:
set file_uploads to on
set max_execution_time to 300 (seconds)
set max_file_size to 100 (MB)
I've tried and Googled everything I can think of and I still can't figure out why my image doesn't upload. I'm sorry if this is broad, but I really don't know what the problem is.
Issue:
Image doesn't upload (no idea why, I think I've followed all the steps, see above)
Here's my code:
<?php
$target_dir = "/backend/images/uploads";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// 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["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
print_r($_FILES);
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="/backend/images/upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Thanks for reading, and if anything doesn't make sense, please comment!
add / after uploads
change
$target_dir = "/backend/images/uploads";
to below code
$target_dir = "/backend/images/uploads/";

Categories