Send an image from server to canvas on a page - javascript

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>";
}
?>

Related

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;

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/";

image not displaying in my form in php

I am having issues displaying image on the website i am developing. It a website that users can change their profile picture, as well as their basic profile information. bellow is my sample code.
profile.php
<?php
$studpix=$row_rsp['pix'];
$propix='<img class=
"profile-user-img img-responsive img-circle" src="...
/Student /imageupload/blank.png"
alt="profile picture">';
if($propix!=NULL)
{
$propix='<img class="profile-user-img
img-responsive img-circle" src="Student/imageupload/'.$studpix.'"
alt="profile picture">';
};
$profile_pic_btn =
' Profile pics';
$avatar_form = '<form id="avatar_form"
enctype="multipart/form-data" method="post" action="photoup.php">';
$avatar_form .= '<h4>Change your picture</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
<?php echo $propix?><?
php echo $avatar_form?><?php echo $profile_pic_btn;?>
//other codes goes here
imageupload.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]
["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "ERROR: That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
echo "ERROR: Your image file was larger than 1mb";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "ERROR: Your image file was not jpg, gif or png type";
exit();
} else if ($fileErrorMsg == 1) {
echo "ERROR: An unknown error occurred";
exit();
}
$sql = "SELECT pix FROM studentdetails WHERE email='%s'";
$query = mysqli_query($myconn, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../Student/imageupload/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file(
$fileTmpLoc, "../Student /imageupload /$db_file_name");
if ($moveResult != true) {
echo "ERROR: File upload failed";
exit();
}
include_once("../image_resize.php");
$target_file = "../Student/imageupload/$db_file_name";
$resized_file = "../Student/imageupload/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE studendetails SET pix='%s' WHERE email='%s' LIMIT 1";
$query = mysqli_query($myconn, $sql);
mysqli_close($myconn);
header("location: profile.php");
exit();
}
?>
Your help will be appreciated.
Try to debug your code step by step.
1. Check whether the file gets uploaded correctly and to the correct folder.
2. Check whether the data is updated correctly in the database.
3. Try to open the file by URL directly in the browser.
4. Check whether your HTML code is outputted correctly on the webpage and debug the outputted source code.
5. Make sure that your HTML code works properly.
There may be more steps to take, but this might give you some direction.

mouse location tracking on uploaded image using html and 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.

Upload Image Using Ajax and PHP and Return Uploaded Image URL

I am trying to upload image without refresh but i don't have much knowledge about ajax.
I have php file thy return image url when i submit post with ajax function.
Javascript
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}
}).submit();
});
});
PHP
<?php
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$imge1="uploads/".$actual_image_name;
echo $imge1;
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
HTML
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
<img src = "" id="thumb_img" />
Now result is image url. when image select ajax automatically post sand to php.Php save image and return url and this url show in target div.So now i need this url set as background url. Like image select target div background change.
I would just do something like:
$('#myForm').ajaxForm(function(url) {
$('#preview').css('background-image', "url(" + url + ")");
});

Categories