How to Show result after uploaded file in PHP - javascript

I have a script that uploads the video to a server, everything is correct but there is a problem, after the upload of the video to the server is completed
it shows all the uploaded files in the (uploads) folder as array!
I only want the result of the file I just uploaded, and it doesn't show me the previous files!
I need ffmpeg to improve video quality
index.php
<?php
//index.php
?>
<!DOCTYPE html>
<html>
<head>
<title>Personal Video Uploader</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/dropzone.js"></script>
<link rel="stylesheet" href="css/main.css">
</head>
<body class="bg-body">
<div class="container">
<form action="upload.php" class="dropzone font" id="dropzoneFrom">
</form>
</form>
<br />
<div id="preview"></div>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
Dropzone.options.dropzoneFrom = {
autoProcessQueue: true,
timeout: 300000,
acceptedFiles:"video/*",
init: function(){
var submitButton = document.querySelector('#submit-all');
myDropzone = this;
submitButton.addEventListener("click", function(){
myDropzone.processQueue();
});
this.on("complete", function(){
if(this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0)
{
var _this = this;
_this.removeAllFiles();
}
list_image();
});
},
};
list_image();
function list_image()
{
$.ajax({
url:"upload.php",
success:function(data){
$("#preview").html(data);
}
});
}
$(document).on('click', '.remove_image', function(){
var name = $(this).attr('id');
$.ajax({
url:"upload.php",
method:"POST",
data:{name:name},
success:function(data)
{
list_image();
}
})
});
});
</script>
upload.php
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$result = array();
$files = scandir('upload');
$output = '<div class="row">';
if(false !== $files)
{
foreach($files as $file)
{
if('.' != $file && '..' != $file)
{
$output .= '
<img src="thumb/'.$file.'.png" class="img-thumbnail" width="246px" height="138px" style="height:138px;" />
<button type="button" class="btn btn-link remove_image" id="'.$file.'">Remove</button>
';
}
}
}
$output .= '</div>';
echo $output;
?>
EDIT:
I put the example on an Array, I don't want it, I just want it to show the downloaded video I just uploaded as a result.
EDIT 2 :
There are some who say type $location and it displays the downloaded file, but this does not work!!!
I just tried more than once and with several uses, there is no display where the text is empty
This is an example of that
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
if(isset($_POST["name"]))
{
$filename = $folder_name.$_POST["name"];
$imagename = $thumb_name.$_POST["name"].$imageext;
unlink($filename);
unlink($imagename);
}
$output .= 'Successfly file is "'.$location.'"';
echo $output;
?>
Result : Successfly file is ""
no name file :(
EDIT 3 :
this code upload.php
functions not working
<?php
//upload.php
$folder_name = 'upload/';
$tumb_name = 'thumb/';
$imageext = '.png';
if(!empty($_FILES))
{
$temp_file = $_FILES['file']['tmp_name'];
$location = $folder_name . $_FILES['file']['name'];
move_uploaded_file($temp_file, $location);
$upload = $_FILES['file']['name'];
$uploadStr = str_replace(" ", "\ ",$upload);
$locationStr = str_replace(" ","\ ",$location);
$cmd = "ffmpeg -y -i {$locationStr} -ss 00:00:15 -vframes 1 thumb/{$uploadStr}.png 2>&1";
echo shell_exec($cmd);
}
echo "The file " . $location . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $upload . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $uploadStr . " has been uploaded";
// not working
echo "<br>";
echo "The file " . $locationStr . " has been uploaded";
// not working
?>
this error:
[23-Apr-2022 12:31:56 Asia/Riyadh] PHP Notice: Undefined variable: location in /home/prdix/public_html/test/upload.php on line 38
line 38: echo $location;
About the developer solution Markus AO
I did the experiment and it is quite good, but dropzone is still missing, because I will upload a large video and the normal upload compresses the video before uploading, here is a picture from my mobile while uploading, but this does not happen with dropzone
I want to implement this in dropzone as well, because this library does not compress the video, but upload it in full size.
Thank you bro.

Related

Get statement not adding to database

i'm trying to use a get statement in a variable to add data to a data base, when i try to do this nothing is added under folder however if i add plain text it is added. (i'm trying to add to the folder section)
My entire html document is provided below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="newfile.css">
<title>Folder</title>
</head>
<body>
<?php
include_once 'dbh.php';
echo $_GET["data"];
if(isset($_GET["data"])) {
$location = $_GET["data"];
$sql = "SELECT * FROM posts WHERE folder LIKE '%$location%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result))
{
echo $row['content'];
}
} else {
echo "There are no results matching your search!";
}
}
?>
<?php
$uploadpath = 'postimages/'; // directory to store the uploaded files
$max_size = 3116718; // maximum file size, in KiloBytes
$alwidth = 100000; // maximum allowed width, in pixeli
$alheight = 100000; // maximum allowed height, in pixeli
$allowtype = array('bmp', 'gif', 'jpeg', 'jpg', 'jpe', 'png', 'docx', 'psd', 'pdf', 'pptx', 'html', 'php', 'css', 'js', 'mp4', 'mp3'); // allowed extensions
if(isset($_FILES['fileup'])) {
$uploadpath = $uploadpath . basename( $_FILES['fileup']['name']);
$name = basename( $_FILES['fileup']['name']);
$type = end(explode('.', strtolower($_FILES['fileup']['name'])));
list($width, $height) = getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = '';
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*900000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x
'. $alheight;
// If no errors, upload the image, else, output the errors
if($err == '') {
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_GET['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
if($result !== false) {
header("Location: fold.php?data=Math");
}else{
echo "fail";
}
}
else echo '<b>Unable to upload the file.</b>';
}
else echo $err;
}
?>
<div class="upform">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="image-upload">
<label for="file-input">
<img src="add-file.png" />
</label>
<input id="file-input" type="file" name="fileup"/>
</div>
<input class="noshow" type="text" id="wow" placeholder="<?php echo $_GET['data']; ?>" name='name'>
<input type="submit" id="submit" name='submit' value="U P L O A D" />
</form>
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
$('input:file').change(
function(){
if ($(this).val()) {
$("#submit").show();
// or, as has been pointed out elsewhere:
// $('input:submit').removeAttr('disabled');
}
}
)
});
</script>
</body>
</html>
url= http://localhost/smart%20assist/fold.php?data=Math
Any help would be awesome, Thanks
So, if you doing file uploading you are using post method in your form with multi-part, right.
now, if you want to send something with your url as query params, then you have to use $_REQUEST. In your case,
if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) {
$content = $name;
$realfiledest = $uploadpath;
$username = 'user';
$folder = $_REQUEST['data'];
$sql = "INSERT INTO posts (content, img, folder, date) VALUES ('$content', '$realfiledest', '$folder', NOW());";
$result = mysqli_query($conn, $sql);
If you facing the same problem, I need to check your HTML form, to help you in a better way.
I think you made below mistakes.
You are not posting "data" field value in your HTML.
You must put the name field for get data.
You are posting the form for using post method. So you should be used $_POST[] or $_REQUEST[].
please verify your HTML.

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.

Call the canvas image to another div or page

Can anybody help me with this I'm solving this problem for almost a week and never get success. I want to happen is to call the image that was been created the image goes to "image" in a div and I want to call that image to the another page but No image show. Please take a look my code.
<script>
function myFunction(){
html2canvas([document.getElementById('card-container')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
// AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
}
</script>
<button onclick="myFunction()" >Try it</button>
<div id="image">
<p>Image:</p>
</div>
<form enctype="multipart/form-data" action="sample.com" method="post" onsubmit="this.divcontent.value = document.getElementById('image').innerHTML;" >
<input type="hidden" name="image" id="divcontent" value="" />
<input type="submit" value="Submit" />
</form>
Here is the ready-image.php
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Please help me guys. Thank you very much.
I am not sure if this is what you want. Since the ajax part is missing from your code, I am just trying to pass the image captured to the ready-image.php and display it.
I am assuming that the codes are on 2 separate files.
<script>
function myFunction() {
html2canvas([document.getElementById('card-container')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
$("#divcontent").val(data); //save the image base64 string to a hidden input
}
});
}
</script>
<div id="card-container">
<button onclick="myFunction()" >Try it</button>
<div id="image">
<p>Image:</p>
</div>
<form action="ready-image.php" method="POST">
<input type="hidden" name="divcontent" id="divcontent" />
<input type="submit" value="Submit" />
</form>
</div>
ready-image.php:
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Update:
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$filteredData = substr($img, strpos($img, ",") + 1);
$decodedData = base64_decode($filteredData);
$file = UPLOAD_DIR . uniqid() . '.png';
$fp = fopen($file,'wb');
if ($fp) {
fwrite($fp, $decodedData);
print $file;
} else {
print 'Unable to save the file.';
}
fclose($fp);
?>
I commented out the download part because I am not sure how exactly you call the ajax to save the file, so that part is omitted from my solution.

get < image> src php to display in html

This is my javascript code :
$(document).ready(function() {
$('.aire-force,.army').click(function() {
var storedData;
var qString = 'categorie=' +$(this).text();
$.post('getimage.php', qString, processResponse);
});
function processResponse(data) {
$('.results').html(data);
storedData = data;
alert(storedData);
document.getElementById('test').innerHTML = test;
}
});
and this my file PHP (getimage.php):
<?php
$con = mysql_connect("localhost","root","");
if(!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("DB", $con);
$categorie = $_POST['categorie'];
$q = "SELECT title from designs WHERE categorie='$categorie'";
$r = mysql_query($q);
while( $array = mysql_fetch_array($r)){
echo $array['title'];
}
?>
and i need to get the tile of image in my code HTML :
require_once('getimage.php');
<img src="images/ echo $array['title']; />
require_once('getimage.php');
< img src="images/ echo $array['title']; />
Should be replaced by:
<?php include('getimage.php'); ?>
<img src="images/<?php echo $array['title']; ?>" />
This should work.. Save this html file also as a .php ;)
document.getElementById('test').innerHTML = test;
You never set test variable.

replace php script with javascript or jquery to decode base64

I use the following code to save my canvas to the server as an png:
Now, I want to replace the php with js or jquery but I have no idea to do this with base64 decoding.
Folder: imgs
HTML:
Link with id="save" to open a thumbnail with download-link
Javascript:
$("#save").click(function () {
$("#result").html("<img src=" + d.toDataURL() + ' /><br /><a href="#" id="get" class="minimal" >Download This</a>');
$("#data").val(d.toDataURL());
$("#get").click(function () {
$("#frm").trigger("submit")
})
});
$("#clear").click(function () {
e.fillStyle = "#fff";
e.fillRect(0, 0, d.width, d.height);
e.strokeStyle = "red";
e.fillStyle = "red"
})
})
function saveRestorePoint() {
var oCanvas = document.getElementById("can");
var imgSrc = oCanvas.toDataURL("image/png");
restorePoints.push(imgSrc);
}
PHP:
<?php
if (isset($_POST['data'])) {
$data = $_POST['data'];
//removing the "data:image/png;base64," part
$uri = substr($data, strpos($data, ",") + 1);
$filenamex = time();
$filename = 'imgs/' . $filenamex . '.png';
// put the data to a file
file_put_contents($filename, base64_decode($uri));
///*
//force user to download the image
if (file_exists($filename)) {
// We'll be outputting a PNG
header('Content-type: image/png');
// It will be called wow.png
header('Content-Disposition: attachment; filename="' . $filename . '"');
// The PDF source is in wow.png
readfile($filename);
exit();
}
}
?>

Categories