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