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;
Related
I would like to ask help with my current project. I have an application form that ask users to upload their attachments. Each application attachment varies from 1 to 10 and so I have to modify the current system that can only accept 1 upload per transaction. Here is the snippet of my attachment module.
$(document).ready(function() {
var html = '<tr><td><input class="form-control" type="file" name="FileToUpload[]" multiple=""></td><td><input class="btn btn-danger remove" type="button" name="remove" value="Remove"></td></tr>';
var max = 10;
var x = 1;
$("#add").click(function() {
if (x < max) {
$("#table_field").append(html);
x++;
}
});
$("#table_field").on('click', '.remove', function() {
$(this).closest('tr').remove();
x--;
});
});
Here is my HTML file
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Upload attachments
<div class="input_field">
<table id="table_field" class="table table-bordered">
<tr>
<th>
Image
</th>
<th>
Action
</th>
</tr>
<tr>
<td><input class="form-control" type="file" name="FileToUpload[]" multiple=""></td>
<td><input class="btn btn-primary" type="button" name="add" id="add" value="Add"></td>
</tr>
</table>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeGWochAAAAAJJYH17JqaBlkFJfSoJPvrPr2BI0"></div>
<span id="captcha_error" class="text-danger"></span>
</div>
Here is the upload php I used previously.
//ATTACH IMAGES CODE
$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($_SERVER["REQUEST_METHOD"] == "POST") {
$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"] > 5000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" && $imageFileType != "pdf" ){
echo "Sorry, only JPG, JPEG, PNG & GIF & PDF 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 {
$temp = explode(".", $_FILES["FileToUpload"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
if (move_uploaded_file($_FILES["FileToUpload"]["tmp_name"], "uploads/" . $newfilename)) {
echo "The file ". htmlspecialchars( basename( $_FILES["FileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
I have made a transactional table named images that will store the ID and filename of each image.
Please help me transform my code to accept multiple image uploads.
Thank you
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>";
}
?>
here is my problem : On my website I want to allow users to upload any type of video. But with the HTML5 tag only .mp4 video can be used.
So I want to convert any type of video submit by the user to MP4 then add the path to the databse.
I've read something about FFmpeg but I can't figure out how to use it. I tried to use shell_exec("ffmpeg -i ".$vid." -vcodec libx264 -crf 20 out.mp4 2>&1") without success.
The html
<form method="post" enctype="multipart/form-data" name="form" action="post.php">
<input type="file" name="media-vid" class=" file_multi_video" accept="video/*">
</form>
The php script:
if(file_exists($_FILES['media-vid']['tmp_name']) && is_uploaded_file($_FILES['media-vid']['tmp_name']))
{
$targetvid = md5(time());
$target_dirvid = "videos/";
$target_filevid = $targetvid.basename($_FILES["media-vid"]["name"]);
$uploadOk = 1;
$videotype = pathinfo($target_filevid,PATHINFO_EXTENSION);
if ($_FILES["media-vid"]["size"] > 500000000) {
$uploadOk = 0;
echo "Sorry, your file is too large.";
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your video was not uploaded.";
// if everything is ok, try to upload file
} else {
$target_filevid = strtr($target_filevid,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$target_filevid = preg_replace('/([^.a-z0-9]+)/i', '_', $target_filevid);
if (!move_uploaded_file($_FILES["media-vid"]["tmp_name"], $target_dirvid. $target_filevid)) {
echo "Sorry, there was an error uploading your file. Please retry.";
}else{
$vid= $target_dirvid.$target_filevid;
shell_exec("ffmpeg -i ".$vid." -vcodec libx264 -crf 20 out.mp4 2>&1");
}
}
}
Here is how I would do it:
Try out this code! ( Tested and works fine )
<form method="post" enctype="multipart/form-data" name="form">
<input type="file" name="media-vid" class=" file_multi_video" accept="video/*">
<input type="submit" name="submit" value="upload"/>
</form>
<?
if (isset($_POST['submit'])) {
if (file_exists($_FILES['media-vid']['tmp_name']) && is_uploaded_file($_FILES['media-vid']['tmp_name'])) {
$targetvid = md5(time());
$target_dirvid = "videos/";
$target_filevid = $targetvid . basename($_FILES["media-vid"]["name"]);
$uploadOk = 0;
$videotype = pathinfo($target_filevid, PATHINFO_EXTENSION);
//these are the valid video formats that can be uploaded and
//they will all be converted to .mp4
$video_formats = array(
"mpeg",
"mp4",
"mov",
"wav",
"avi",
"dat",
"flv",
"3gp"
);
foreach ($video_formats as $valid_video_format) {
//You can use in_array and it is better
if (preg_match("/$videotype/i", $valid_video_format)) {
$target_filevid = $targetvid . basename($_FILES["media-vid"] . ".mp4");
$uploadOk = 1;
break;
} else {
//if it is an image or another file format it is not accepted
$format_error = "Invalid Video Format!";
}
}
if ($_FILES["media-vid"]["size"] > 500000000) {
$uploadOk = 0;
echo "Sorry, your file is too large.";
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0 && isset($format_error)) {
echo $message;
// if everything is ok, try to upload file
} else if ($uploadOk == 0) {
echo "Sorry, your video was not uploaded.";
}
else {
$target_filevid = strtr($target_filevid, 'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$target_filevid = preg_replace('/([^.a-z0-9]+)/i', '_', $target_filevid);
if (!move_uploaded_file($_FILES["media-vid"]["tmp_name"], $target_dirvid . $target_filevid)) {
echo "Sorry, there was an error uploading your file. Please retry.";
} else {
$vid = $target_dirvid . $target_filevid;
}
}
}
}
?>
Test it and let me know how it goes. If you have any other questions or need anything else, please do not hesitate to ask. I am always here to help and I would like you to have this file fully coded. Good luck bro!
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/";
I have this simplified situation :
<form action='process.php' method='post'>
<div class="dropzone no-margin">
<div class="fallback">
<input name="file" type="file" multiple/>
</div>
</div>
</form>
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5
});
test2.php works just fine, it upload files dropped on the dropzone immediately. but, the problem is, I need to pass those file names of uploaded files to the form as hidden text input.
here's test2.php looks like :
<?php
$target_dir = "user/product/";
$target_file = $target_dir . basename($_FILES["file"]["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["file"]["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["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
I'm a beginner in javascript or jquery world. So, I really need your help to give me a clue how to pass the file names to the form as hidden text input so it can be written into database later on.
thank you so much and I really appreciate you help.
Try this :
there is method in Dropzone i.e sending that will use to send data before file is sent.if multiple files are uploaded then use sendingmultiple method.
$(".dropzone").dropzone({
url: "/test2.php",
maxFilesize: 2,
maxFiles: 5,
sending:function (data, xhr, formdata) {
console.log("data :",data);
//here you can get file name from data variable.you can add that to your form by following line.
formdata.append('hidden field name', 'file name');
//you can add as much parameter you want to pass to your post data by formdata.append() function. That will add data to your form data.you can refer that value by using $_POST['hidden_field_name'] at PHP side.
}
});
Please check following link for detail :
http://www.dropzonejs.com/#events