How to get image src in php/javascript - javascript

I have an HTML image tag with the source blank. The source will change based on input type file when the user uploads an image. So how do I get the image source? I can't hardcode the source as it will change based on what the user selects.So i want to retrieve the image src based on the file user has selected.
Here are the codes i used:
i want to get the image directory by retrieving image src so i can check if there's an XML file created in the folder which has the same name as the image.
thank you

I believe the PHP code you are specifically asking for is
$_FILES["fileToUpload"]["name"]
However, take a look at the tutorial from w3schools.
HTML upload form
<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>
Php uploader
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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;
}
}
?>

Related

Jquery & Ajax -> File upload not possible

I got totally lost.
Ive tried to make some Image Upload function in PHP and everything works fine. Because i dont want the whole Page to reload, when uploading a File i wanted to use AJAX with Jquery, to send the Form Content (Image) via POST to a file like upload.php with an hidden ajax request.
No matter what i try its impossible to send anything with formData(). I copied & pasted several Sample Codes, tried changing the Code, nothing happens when i use formData().
A normal request with Jquery / Ajax, using POST works fine.
Here ist the Sample of my last used Code..
Could my XamPP has been misconfigured, or what could cause that really not one of the Scripts from google, tutorial pages etc works?
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
<button id="Knopf">Knopf</button>
<div id="Disp">fghfgh</div>
</body>
<script>
$(document).ready(function(){
$("#Knopf").click(function(){
var formData = new FormData(Test);
$.ajax({
url : "uploadtest2.php",
type : "POST",
data : formData,
cache : false,
contentType : false,
processType : false,
success : function() {
$("#Disp").html(result);
}
});
});
});
</script>
</html>
<?php
$target_dir = "Media/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(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 ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
The problem is this:
if(isset($_POST["submit"])) {
There's no element named submit in the form, so this check fails. Even if you had a submit button in the form, it wouldn't be included in formData, because buttons are only automatically included in POST data when they trigger normal form submission.
You can add that to formData.
var formData = new FormData(Test);
formData.set("submit", "1");
Or you could change your test to
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
Please see: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
You must use a Form Element:
An HTML <form> element — when specified, the FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.
Consider the following example.
$(function() {
$("#Test").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "uploadtest2.php",
type: "POST",
data: formData,
cache: false,
contentType: false,
processType: false,
success: function(result) {
$("#Disp").html(result);
}
});
});
$("#Knopf").click(function() {
$("#Test").submit();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="Test" action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload" />
</form>
<button id="Knopf" type="submit">Knopf</button>
<div id="Disp">fghfgh</div>
It is better to bind to the submit callback. This way, if the User submits the form or clicks Submit, the callback is triggered. We need to .preventDefault() on the Event to ensure the Form doesn't post or submit the data. Now we can then perform the AJAX call without the page being refreshed.
In your success callback, you must pass in a variable to be used for the returned data. Otherwise result will be undefined.
With the proper FormData, there should be no issue uploading. this in the callback refers to the Form Element itself.
Consider updating your PHP as well:
if(isset($_POST["submit"])) {
Change this to:
if(isset($_POST["fileToUpload"])) {

PHP - Auto-submit forms in PHP using onchange

I am trying to create a form where when the user chooses a file, the file chosen will automatically upload to the database by going to the action in form. I used the onchange function and it just sends me to my php file in which that file contains my uploading system. What i think my problem is about my $_POST['asdasd'], but i cant really think of any other solutions to this.
Here is my form:
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
</form>
The PHP File:
if (isset($_POST['submit'])) {
$target_dir = "../users/".$_SESSION['u_id']."/image/";
$str = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
$rand = substr(str_shuffle($str), 0, 10);
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $rand . '.' . end($temp);
$target_file = $target_dir . $newfilename;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ". <br/>";
$uploadOk = 1;
} else {
echo "File is not an image. <br/>";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. <br/>";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 5000000) {
echo "Sorry, your file is too large. <br/>";
$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. <br/>";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. <br/>";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
require 'database_inc.php';
$sql = "UPDATE `users` SET `user_profile` = '$newfilename' WHERE 1";
if (mysqli_query($conn,$sql)) {
$_SESSION['profile_picture'] = $newfilename;
header("Location: ../profile.php");
} else {
echo "The query has not been updated. <br/>";
}
} else {
echo "Sorry, there was an error uploading your file. <br/>";
}
}
}
It is not saving because in the php file you have the line
if (isset($_POST['submit'])) {
add in the form a hidden field
<form action="includes/profile_picture_inc.php" method="POST" enctype="multipart/form-data" id="form">
<input type="file" name="file" id="upload" onchange="document.getElementById('form').submit();">
<input type="hidden" name="submited" value="1" />
</form>
And in php change the line
if (isset($_POST['submit'])) {
to
if (isset($_POST['submited'])) {
That should do it
Instead of doing the $_POST['submit'] validation, try to check if the request is a $_POST.
To do that you can use something like
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }
or
if ($_SERVER['REQUEST_METHOD'] === 'POST') {…}
i recommend you to use the first one.
PHP doc: http://php.net/manual/pt_BR/function.filter-input.php

How to call a php function from javascript alert

Basically what i am trying to do is- create a page to upload file. Below is the code and its working fine:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function wow_default_alert() {alert("Successfully saved!"); }
</script>
</head>
<body>
<form action="index.php" method="post" name="myForm" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if (!file_exists('.\\tigerimg\\'))
{
mkdir('.\\tigerimg\\', 0777, true);
}
$target_dir = '.\\tigerimg\\';
$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
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
"File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
"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.";
echo '<script type="text/javascript">
wow_default_alert();
</script>';
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
But the problem is that if i refresh the page again -after uploading one file successfully, it works with the same post values.
Previously i used the below code to unset post data-which worked for other pages.
clear Code-1
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
unset($_SESSION['postdata']);
}
?>
But i cant use it in this one. It shows error:
Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 41
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 47
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\up\index.php on line 47
Notice: Undefined index: fileToUpload in C:\xampp\htdocs\up\index.php on line 62
So, i tried to also clear the FILES array too by adding 3 lines with the above code.
clear Code-2
<?php
session_start();
if( strcasecmp($_SERVER['REQUEST_METHOD'],"POST") === 0)
{
$_SESSION['postdata'] = $_POST;
$_SESSION['filedata'] = $_FILES; //new code
header("Location: ".$_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING']);
exit;
}
if( isset($_SESSION['postdata']))
{
$_POST = $_SESSION['postdata'];
$_FILES = $_SESSION['filedata']; //new
unset($_SESSION['postdata']);
unset($_SESSION['filedata']); //new
}
?>
But now its showing only one error:
Warning: getimagesize(C:\xampp\tmp\php1A2F.tmp): failed to open stream: No such file or directory in C:\xampp\htdocs\up\index.php on line 51.
>>> So, here is one question- why is this happening?
Ok, now i tried another way put the above [clear Code-1] inside a php function function remove_post() and call it just after the code of successful uploading- where i called the alert.
This time its working fine. But now the problem is that the alert doesn't appear. So, is it possible to call the function remove_post() when user clicks the ok in alert.
It looks like you are trying to copy from W3Schools web site, which is not the greatest of places. At any rate, in this instance, I think you may want to do all your processing at the top of your page like so:
<?php
// Not sure if you are storing anything in sessions...
session_start();
// Create a root
define("ROOT_DIR",__DIR__);
// Create a function so you can customize it if you want to
function SaveFileToDisk($dir = '/tigeimg/',$allow = array("image/png","image/jpeg","image/gif"))
{
// Make directory if not exists
if(!is_dir($mkdir = ROOT_DIR.$dir)) {
if(!mkdir($mkdir,0755,true))
return 'mkdir';
}
// Filter filename
$name = preg_replace("/[^0-9a-zA-Z\.\_\-]/","",$_FILES["fileToUpload"]["name"]);
// Assign name
$filename = (!empty($name))? $name : false;
// If empty, record error
if(!$filename)
$error[] = 'nofile';
// Get mime type
$mime = (!empty($_FILES["fileToUpload"]["tmp_name"]))? getimagesize($_FILES["fileToUpload"]["tmp_name"]) : false;
// Record if invalid
if(!$mime)
$error[] = 'invalid';
// Filter out double forward slashes (if user decides to change $dir)
// and adds too many forward slashes
$final = str_replace("//","/",ROOT_DIR."/".$dir."/".$filename);
// If file exists, record error
if(is_file($final))
$error[] = 'exists';
// If too big record error
if($filename > 500000)
$error[] = 'size';
// If not in the allowed file types, record error
if(!in_array($_FILES["fileToUpload"]["type"],$allow))
$error[] = 'type';
// Return array of errors
if(!empty($error))
return $error;
// True or false if no errors are recorded previously
return (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$final));
}
// Just create a simple error returning function
// This is expandable by adding error descriptions stored in database if desired
function ErrorReporting($value = false)
{
$msg['invalid'] = "INVALID File!";
$msg['type'] = "The file you are trying to upload is not a valid image type.";
$msg['exists'] = "The file you are trying to upload is already uploaded.";
$msg['size'] = "The file you are trying to upload is too large.";
$msg['nofile'] = "The file you are trying to upload has no name.";
if($value === true)
return "Successfully uploaded!";
elseif(is_array($value)) {
foreach($value as $error) {
$err[] = (!empty($msg[$error]))? $msg[$error]:"";
}
if(!empty($err))
return implode("",$err);
}
else
return "File failed to upload.";
}
// If post is submitted
if(isset($_POST["submit"]))
// Run the uploader function
$success = SaveFileToDisk();
?><!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
<?php
// if there is an upload, run the js alert
if(isset($success)) {
?>
function error_alert(errmsg)
{
alert(errmsg);
}
error_alert("<?php echo ErrorReporting($success); ?>");
<?php }
?>
</script>
</head>
<body>
<form action="" method="post" name="myForm" 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>
After user clicks OK for alert you can call the php function as
alert('Your alert');
document.write(' <?php remove_post(); ?> ');
Your remove_post() function will get called after user click OK on alert

How do I upload an image using PHP? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How do I upload an image and store it into a cookie? I want to be able to upload an image with limitations on e.g. file size restrictions.
Here is my 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.";
}
}
?>
In this code is the function to upload a file with restrictions on.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<link href="bitnami.css" media="all" rel="Stylesheet" type="text/css" />
<link href="test.php"/>
</head>
<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>
You have multiple faults in your logic.
1) You never check if an upload was actually performed. You just start working on the ['tmp_name'] without ever checking if it actually exists. Your FIRST action on processing an upload must be to check for errors:
if ($_FILES["fileToUpload"]['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['fileToUpload']['error']);
}
2) You're checking file types based on filename extensions. Nothing says a user can't do ren nastyvirus.exe cutekittens.jpg and get through your filename check. You're already using getimagesize() later on, so the extension check is pointless:
$info = getimagesize($_FILES['fileToUpload']['tmp_name']);
if ($info === false) {
die("Not an image at all");
}
if (($info[2] != IMGTYPE_GIF) && ($info[2] != IMGTYPE_JPG) && ($info[2] != IMGTYPE_PNG)) {
die("Not a gif/jpg/png");
}
if (($info[0] > $maximum_width) || ($info[1] > $maximum_height)) {
die("Too tall/wide");
}
And then, after all that - why store it in a cookie? Cookies are naturally limited in the maximum amount of data that can be stored. You shouldn't exect to be able to store more than a couple kilobytes at most. Since you've set your upload size limit at 500k, you WILL end up with corrupted/truncated images if you do store a 500k into that 1-2k cookie.

html2canvas capturing div image

im working on my wordpress site in which i want a div to be converted to image.. im using html2canvas javascript and it works perfect. when i capture a post it saves it to the server has "Captured.jpg". all good till here.. but when i click capture again on a different post it replaces the previous image "captured.jpg". i want all the images of the posts that i capture to be saved on server with post names may be? is it possible?
Header
<script type="text/javascript">
function capture() {
$("#quotesingle").html2canvas({
canvas: hidden_screenshot,
onrendered: function() {
var img = $("#hidden_screenshot")[0].toDataURL();
img= img.replace('data:image/png;base64','');
$form = '<form name="frmact" action="result.php" method="post" ><input type="hidden" name="img" value="' + img + '" /></form>';
$('body').append($form);
frmact.submit();
$('body').remove($form);
}
});
}
</script>
Results.php
<?php
$canvasImg = $_POST['img'];
$data = base64_decode($canvasImg);
$File = "captured.jpg";
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
fclose($Handle);
?>
captured.jpg is saved.
single.php
//POSTLOOP
<input type=button value="Screenshot" onclick="javascript:capture();" /><br /><br /></div>
<canvas id="hidden_screenshot" style="display:none;" >
is there any way if i trigger the capture for a post to save in a different name or post name or post id.. so it saves it to the server without replacing the old?
thanks
Result.php
Simple change the file name as below:
$File = "screens/" . time() . ".jpg";

Categories

Resources