how to insert video path, video name in mysql database in php.? - php

I want to store video path and name in MySQL database but actually only stored the some fields information which i used in the form. and video stored the test upload folder
I have tried but video path(location) and name not store in database.
Here my code,
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br><br>
<input type="button" value="Upload File" onclick="uploadFile()">
</form>
Controller:
public function Insert_vedio()
{
$vedio_data=array(
'title'=>$this->input->post('Title'),
'v_name'=>$this->input->post('fileName'),
);
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
}

Actually I have not mention Title and name in view part. Here My actual code. name is video file name, but don't understand how to give the vedio name.
<form id="upload_form" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="e1"> Title</label>
<input type="text" placeholder="Movie Tile" name="Title" id="e1" class="form-control">
<input type="file" name="file1" id="file1"><br><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h6 id="status" style="color:red"></h6>
<p id="loaded_n_total"></p>
<div class="osahan-area text-center mt-3">
<button class="btn btn-outline-primary">Save Changes</button>
</div>
</div>
</form>

Here my Javascript
<script>
function _(el)
{
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
if(typeof file === "undefined") {
_("status").innerHTML = "ERROR: Please browse for a file before clicking the upload button";
_("progressBar").value = 0;
return;
}
$.get('Upload_vedio/Insert_vedio?getsize', function(sizelimit) {
if(file.type !== "video/mp4") {
var typewarn = "ERROR: You have to select a MP4-File";
_("status").innerHTML = typewarn;
_("progressBar").value = 0;
return;
}
if(sizelimit < file.size) {
var sizewarn = "ERROR: The File is too big! The maximum file size is ";
sizewarn += sizelimit/(1024*1024);
sizewarn += "MB";
_("status").innerHTML = sizewarn;
_("progressBar").value = 0;
return;
}
var formdata = new FormData();
formdata.append("file1", file);
formdata.append("size", file.size);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "Upload_vedio/Insert_vedio");
ajax.send(formdata);
});
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
</script>

Related

How to upload multiple files using Jquery/Ajax

I m trying to upload two different files using Jquery and Ajax along with a text box.
However I can able to upload a single file and textbox using the code I have, but when I try to add another input type file, it breaks and doesn't upload any.
The code for single input type file I have: (upload fine)
test.php
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'><p class="temp"></p></div>
<div >
<input type="text" id="title" name="title" />
<input type="file" id="image" name="image" />
<input type="file" id="image" name="image2" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#image')[0].files;
var title = $("#title").val();
fd.append('image',files[0]);
fd.append('title',title);
$.ajax({
url:'test2.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$(".temp").html(response);
$('.preview').show();
}else{
alert('File not uploaded');
}
}
});
});
});
</script>
test2.php
<?php
/* Getting file name */
$filename = $_FILES['image']['name'];
$title = $_POST['title'];
/* Location */
$location = "images-main/post-images/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['image']['tmp_name'],$location)){
$response = $title;
}
}
echo $response;
exit;
The code for multiple input type file I have: (doesn't upload anything)
test.php
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'><p class="temp"></p></div>
<div >
<input type="text" id="title" name="title" />
<input type="file" id="image" name="image" />
<input type="file" id="image" name="image2" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#image')[0].files;
var filess = $('#image')[1].filess;
var title = $("#title").val();
fd.append('image',files[0]);
fd.append('image2',filess[0]);
fd.append('title',title);
$.ajax({
url:'test2.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$(".temp").html(response);
$('.preview').show();
}else{
alert('File not uploaded');
}
}
});
});
});
</script>
test2.php
<?php
/* Getting file name */
$filename = $_FILES['image']['name'];
$filename2 = $_FILES['image2']['name'];
$title = $_POST['title'];
/* Location */
$location = "images-main/post-images/".$filename;
$location2 = "images-main/post-images/".$filename2;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Check file extension */
if(in_array(strtolower($imageFileType), $valid_extensions)) {
/* Upload file */
if(move_uploaded_file($_FILES['image']['tmp_name'],$location)){
if(move_uploaded_file($_FILES['image2']['tmp_name'],$location2)){
$response = $title;
}
}
}
echo $response;
exit;
Any help is greatly appreciated...
This works fine. Thanks to #CBroe:
Here what did the trick.
test.php
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div class='preview'><p class="temp"></p></div>
<div >
<input type="text" id="title" name="title" />
<input type="file" id="image" name="image" />
<input type="file" id="video" name="video" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#image')[0].files;
var filess = $('#video')[0].files;
var title = $("#title").val();
fd.append('image',files[0]);
fd.append('video',filess[0]);
fd.append('title',title);
$.ajax({
url:'test2.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response){
if(response != 0){
$(".temp").html(response);
$('.preview').show();
}else{
alert('File not uploaded');
}
}
});
});
});
</script>
test2.php
<?php
/* Getting file name */
$filename = $_FILES['image']['name'];
$filename2 = $_FILES['video']['name'];
$title = $_POST['title'];
/* Location */
$location = "images-main/post-images/".$filename;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$location2 = "images-main/post-images/".$filename2;
$imageFileType2 = pathinfo($location2,PATHINFO_EXTENSION);
$imageFileType2 = strtolower($imageFileType2);
/* Valid extensions */
$valid_extensions = array("jpg","jpeg","png");
$response = 0;
/* Upload file */
if(move_uploaded_file($_FILES['video']['tmp_name'],$location2)){
$response = $title;
}
if(move_uploaded_file($_FILES['image']['tmp_name'],$location)){
$response = $title;
}
echo $response;
exit;

Ajax upload script + file type filtering

I have an ajax upload script which i will post below. It will upload any file with any extention. I want it to only upload .png files but i dont know how to do that.
Here are my files:
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
PHP:
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Sorry, i'm new and code blocks wont work for me. If someone could update, that would be great.
Client side
change your input file field this only works for modern browsers IE10+
Google Chrome 8.0+ and Firefox 4.0+
<input type="file" size="60" name="myfile" accept="image/png" />
PHP
$ext = pathinfo( $file_name , PATHINFO_EXTENSION );
if(strtolower($ext) == 'png' && $_FILES["file"]['type'] == "image/png")
{
// upload file
} else{
// not allowed
}
You can check file extension or mime type at server side.
// check extension
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
// return error
}
// or check file mime type
if (mime_content_type($_FILES['myfile']['name']) !== 'image/png') {
// return error
}
Example php:
$output_dir = "uploads/";
$upload_name = $_POST['upload_name'];
if(isset($_FILES["myfile"])) {
// Check upload errors
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
return;
}
// Check extensions
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
echo "Error: Only .png files are allowed";
return;
}
// Upload file
$file_name = $upload_name . $info->getExtension();
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $file_name);
echo "Uploaded File :" . $file_name;
}

Uploading files in to Files folder

I want to upload files in to webroot/files folder, but my controller doing nothing, is there any mistake ?
View file name: uploadfile.ctp
Controller name: UploadFileController.php
Model name: UploadFile.php
In my view file I have:
<div class="files">
<input type="file" name="files[]" /><br/>
</div>
<button type="button" class="plus">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php echo $this->Html->script('addFile');
addFile script :
$(document).ready(function() {
$(".plus").click(function() {
$(".files").append("<input type='file' name='files[]'/><br/>");
});
});
And my Controller, I think that a mistake is somewhere here :
public function uploadFile() {
$uploadedFile = $this->request->params['UploadFile']['files[]']['tmp_name'];
$dir = WWW_ROOT . 'files/';
if ( !is_dir( $dir ) ) {
mkdir($dir);
chmod( $dir , 777);
}
$fileName = 'file_' . date( 'Y_m_d_h_i_s', time() );
move_uploaded_file( $uploadedFile, $dir. $fileName);
}
I got one Notice to:
Notice (8): Undefined index: UploadFile [APP\Controller\UploadFileController.php, line 7]
Thank you for any clue !
Solution
View File (uploadfile.ctp) :
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
Controller (UploadFileController.php) :
class UploadFileController extends AppController {
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
//print_r($this->data); die;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
return false;
}
echo "Filename: $filename<br>";
}
}
}
}
Script (addFile.js) :
$(document).ready(function() {
var max_fields = 2;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x <= max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[]' id='uploadFilefiles'/><button href='#' class='remove_field'>Kustuta</button></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on kustuta text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});

Tracking upload progress

I want to track the upload progress of a file to my server so I read this (German) article. I already checked my PHP.ini:
session.upload_progress.enabled = 1
session.upload_progress.cleanup = 1
session.upload_progress.prefix = upload_progress_
session.upload_progress.name = PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.freq = 1%
session.upload_progress.min_freq = 1
upload_max_filesize = 128M
I began to write a very simple script that only shows a form and uploads a file, when submitted:
<!-- upload.php -->
<?php
session_start();
$maxSize = 10485760;
$uploadName = "test";
if (#$_POST["upload"] ?: 0) { // Check, if upload is in progress
$t = getcwd() . "\\" . basename($_FILES["file"]["name"]);
if ($_FILES["file"]["size"] > $maxSize) {
echo "Upload " . (move_uploaded_file($_FILES["file"]["tmp_name"], $t) ? "succeeded" : "failed"); // Return, if upload is succeeded or failed
}
} else {
?>
<form action="<?= basename(__FILE__); ?>" enctype="multipart/form-data" id="frmUpload" method="POST" target="upload">
<input name="file" type="file" />
<input type="submit" value="Upload" />
<input name="MAX_FILE_SIZE" type="hidden" value="<?= $maxSize; ?>" />
<input name="upload" type="hidden" value="1" />
<input name="<?= ini_get("session.upload_progress.name"); ?>" type="hidden" value="<?= $uploadName; ?>" /> <!-- Set session name -->
</form>
<div style="display: none; ">
<iframe id="upload"></iframe>
</div>
<?php
}
?>
My second script should check the upload progress with the session name
// uploadProgress.php
<?php
session_start();
$pName = ini_get("session.upload_progress.prefix") . "test";
echo json_encode(#$_SESSION[$pName] ?: []);
?>
I created a 10mb file, to ensure a long upload time. Everytime I call uploadProgress.php while the upload is running $_SESSION[$pName] is not set and I cannot find my mistake. Is there something I overlooked or something I made wrong?
Forgive me as I'm not used to the syntax you're using... Not sure why you're using ternary operators in your IF statements, or why you're suppressing the $_SESSION and $_POST variables.
The only thing that stands out to me in your examples is I don't see any call to session_start()?
Here is another article that may help.
Solved the problem. Found a way to track the progress with JavaScript. Here is my solution:
/**********************\
| Script of upload.php |
\**********************/
var ui = { elems: ["dUploads", "fFile", "frmUpload", "pbPercent", "pbUpload", "pbWrpUpload"] }; for (var n = 0; n < ui.elems.length; n++) { ui[ui.elems[n]] = document.getElementById(ui.elems[n]); } delete ui.elems;
function refreshUploads (files) {
var tmp;
while (tmp = dUploads.firstChild) {
tmp.remove();
}
for (var file in files) {
var a = document.createElement("a");
a.setAttribute("href", "uploads/" + files[file]);
a.setAttribute("target", "_blank");
a.appendChild(document.createTextNode(files[file]));
var div = document.createElement("div");
div.appendChild(a);
ui.dUploads.appendChild(div);
}
}
ui.frmUpload.onsubmit = function (e) {
e.preventDefault();
var ajax = new XMLHttpRequest();
var data = new FormData();
data.append("ajax", 1);
data.append("file", ui.fFile.files[0]);
ajax.upload.onprogress = function (e) {
var percent = Math.floor(e.loaded / e.total * 100) + "%";
ui.pbUpload.style.left = percent;
ui.pbPercent.style.left = percent;
ui.pbPercent.innerHTML = percent;
};
ajax.onreadystatechange = function (e) {
if (ajax.readyState == 4 && ajax.status == 200) {
ui.pbWrpUpload.style.opacity = "0";
refreshUploads(eval(ajax.responseText));
}
};
ui.pbWrpUpload.style.opacity = "1";
ajax.open("POST", "upload.php", true);
ajax.send(data);
};
refreshUploads([]); // Normally all already existing files are loaded via PHP

Uploading Image one by one

hi guys I have codes here that allow you to choose image and preview it right away. But i have problem when choosing an image in one by one because when I go to the next page I just get only the last image that I selected. How can I save all the images that selected one by one in an array and pass it to the next page. Its working when you are selecting multiple images in once but then in one by one it just get the last image.
<div id='upload' style="margin-left:5px;border-radius:5pt;background:#fff;width:710px;height:230px;color:white;font-size:11pt;font-weight:bolder">
<div id="list" style="float:left;width:700px;height:auto"></div>
</div>
<div style='margin-top:15px;margin-left:20px;float:left;width:700px;'>
<form method="post" action="index.php?pg=preview" enctype="multipart/form-data">
<input type="file" id="files" name="files[]" multiple />
<input id="but" type="submit" name="cancel" value="Cancel" onclick="history.go(-1)"style="margin-left:225px" ></input>
<input id="but" type="submit" name="next" value="Next"></input>
</form>
</div>
</div>
<script>
function check()
{
$("#show").show();
$("#show").load('check_image.php');
}
var x = 0;
var y = 0;
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
var name = files.item(0).name;
//alert(name);
if(x > 9)
{
alert('Total of 10 Images are acceptable');
}
else
{
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<div id="image"><img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/></div>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
y = i + x;
x = 0 + y;
i = 0;
}
document.getElementById('files').addEventListener('change', handleFileSelect, true);
</script>
<?php
$photo[] = '';
for($i=0; $i<count($_FILES['files']['name']); $i++)
{
if(isset($_FILES["files"]["name"]))
{
if ((($_FILES["files"]["type"][$i] == "image/gif")||
($_FILES["files"]["type"][$i] == "image/jpeg")||
($_FILES["files"]["type"][$i] == "image/jpg")||
($_FILES["files"]["type"][$i] == "image/png")||
($_FILES["files"]["type"][$i] == "image/pjpeg"))&&($_FILES["files"]["size"][$i] < 10000000))
{
if ($_FILES["files"]["error"][$i] > $i)
{
echo "Error: ".$_FILES["files"]["error"][$i]."<br />";
}
else
{
move_uploaded_file($_FILES["files"]["tmp_name"][$i],"pics/".$_FILES["files"]["name"][$i]);
$photo[$i] = "pics/".$_FILES["files"]["name"][$i];
}
}
else
{
$photo[$i]="";
}
}
}
?>
You can modify your code like this:
<form method="post" action="index.php?pg=preview" enctype="multipart/form-data">
$picture_count = 10;
for($i = 0; $i<10;++$i){?>
<input type="file" id="files" name="files[]" 0) echo 'style="display:none;"'?>/>
<input id="but" type="submit" name="cancel" value="Cancel" onclick="history.go(-1)"style="margin-left:225px" ></input>
<input id="but" type="submit" name="next" value="Next"></input>
</form>
<script>
function check() {
$("#show").show();
$("#show").load('check_image.php');
}
var x = 0;
var y = 0;
var j = 0;
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) { </p>
var name = files.item(0).name;
//alert(name);
if(x > <?php echo $picture_count-1;?>)
{
alert('Total of 10 Images are acceptable');
} </p>
else
{
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<div id="image"><img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/></div>'].join('');
document.getElementById('list').insertBefore(span, null);
document.getElementById('files'+j).style.display = 'none';
document.getElementById('files'+(++j)).style.display = 'block';
};
})(f); </p>
// Read in the image file as a data URL.
reader.readAsDataURL(f);</p>
}
}
y = i + x;
x = 0 + y;
i = 0;
}
document.getElementById('files').addEventListener('change', handleFileSelect, true);
</script>
This code will upload all allowed files to the server.
$picture_count - the maximum count of images for upload.
But, I would advise you to use scripts like jquery.uploadify, it is handier and works with many browsers

Categories