Hello have successfully built a web application that allows users upload videos, but i am trying to compress videos before uploading them so as to save bandwidth. Please how do I go about these? e.g, In pictures compression it is GD library but in video searched post on Youtube and stack overflow, none answers my question these is my code. NOTE:these code works perfectly but I am trying to compress the video before upload in php. Thanks in advance..
I looked at this post Server-side video conversion and compression not really what i am looking for because i have never really worked with ffmpeg
<?php include "connect.php"; ?>
<?php
if ((isset($_POST['videoname'])) && (isset($_POST['aboutvideo'])) && (isset($_POST['timestart'])) && (isset($_POST['timestop'])) && (isset($_POST['streamersid']))){
$videoname=$_POST['videoname'];
$aboutvideo=$_POST['aboutvideo'];
$timestart=$_POST['timestart'];
$timestop=$_POST['timestop'];
$streamersid=$_POST['streamersid'];
$streamerstype=$_POST['streamerstype'];
$streamersname=$_POST['streamersname'];
$date=$_POST['date'];
$fileName = $_FILES["file1"]["name"]; //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
$tex = pathinfo($fileName, PATHINFO_EXTENSION); //get video extension
if($tex=='mp4' || $tex=='avi' ||
$tex=='webm' || $tex=='flv' ||
$tex=='MP4' || $tex=='3gp')
{
$rand = substr(md5(microtime()),rand(0, 26) , 26);
#$filez = $rand.$_FILES['file1']['name'];
$videoname= mysqli_real_escape_string($con, $videoname);
$aboutvideo= mysqli_real_escape_string($con, $aboutvideo);
$timestart = mysqli_real_escape_string($con, $timestart);
$timestop = mysqli_real_escape_string($con, $timestop);
//compression script from here video would be compressed before path being being saved to database and moved to folder
if(move_uploaded_file($fileTmpLoc, "plays/$filez")){
$insert="INSERT INTO `plays`(`streamers_id`, `file1`, `video_name`, `about_video`, `streamers_type`, `time_start`, `time_stop`, `date`, `streamers_name`) VALUES ('$streamersid','$filez','$videoname','$aboutvideo','$streamerstype','$timestart','$timestop','$date','$streamersname')";
$run=mysqli_query($con, $insert);
echo "Upload complete ";
} else {
echo "Upload Failed";
}
} else {
echo "Invalid video";
}
}
?>
You are looking to compress BEFORE upload, then it must be done using code running on the client. Your PHP runs on the server. Therefore, you must write some sort of app that the user can download that can compress and upload.
Related
I already searched lots of stuff, some of them are from stackoverflow. But none of them helped me. What I want to do is reduce the image file size, and after reducing the image will now be uploaded. Here's my current code:
<?php
include 'cloud_functions.php';
// GET THE USER'S ID
$userid = _clean($con, $_POST['userid']);
if(!is_dir("uploads/user/".$userid."/")){
mkdir("uploads/user/".$userid."/", 0755);
}
$temp = explode(".", _clean($con,$_FILES["file"]["name"]));
$targetPath = "uploads/user/".$userid."/";
// RENAME THE IMAGE USING ROUND();
$newFN = round(microtime(true)) . '.' . end($temp);
$targetPath = $targetPath . $newFN;
// GET THE FILE EXTENSION
$type = pathinfo(_clean($con, $_POST['filename']), PATHINFO_EXTENSION);
$all_types = array('jpg', 'png', 'jpeg');
$type = strtolower($type);
if(in_array($type, $all_types)){
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetPath)){
// image uploaded w/o compressing size
echo "1/".$newFN;
}else{
echo $targetPath;
echo "There was an error uploading the file, please try again!";
}
}else{
echo "Please upload a valid image.";
}
?>
In that way I can upload image successfully without compressing its size. Please tell me how to do compress image size before upload. Thanks.
You need to compress image on client side. All the code you posted here is of server side. This code will run after uploading the image to the server.
There are lot of client side libraries for this purpose.
This link will further help. You can choose use any library of your choice.
https://github.com/brunobar79/J-I-C - js library
I think better way - compress image on server after uploading, that to decrease using user memory. It's special important for slow smartphones.
I'm using a goDaddy server and cPanel to make a website, and I want to make a feature that lets users upload videos, save them on the server, then display them elsewhere on the site.
displaying uploaded videos:
echo "<video controls><source src='{$video_row[$i]}'></video>";
But I found out that most browsers can only play a few video formats like mp4. So I want to convert them all to mp4 before saving them to the server. So sometime before running the move_uploaded_file() function.
Is there something I can download and put on the server that will let me do that? From other questions I found about FFmpeg, but i couldn't figure out how to use it and if I can even install it on a godaddy server.
Php code:
if (isset($_FILES["submit_file"])) { //this comes from an html form
$name = $_FILES['submit_file']['name'];
$original_name = $name;
$size = $_FILES['submit_file']['size'];
$tmp_name = $_FILES['submit_file']['tmp_name'];
$target_dir = null;
$finfo = finfo_open(FILEINFO_MIME_TYPE); //get mime type
$mime = finfo_file($finfo, $tmp_name);
if ($mime == "video/mp4" || $mime == "video/wmv" || $mime == "video/avi" || $mime == "video/mov") {
if ($mime != "video/mp4") {
//CONVERT TO MP4
}
$target_dir = "uploads/videos/";
$path = $target_dir.basename($name);
if (move_uploaded_file($tmp_name, $path) == true) {
//moved
}
} else {
//error: Unsupported File Type
}
}
How do others deal with videos? I was able to upload and play mp4 videos fine with my method, but html5 can't seem to play other types, and I don't want to limit users to only upload mp4
I am trying to upload images onto server.
On the Server the folder name:{photo}
I check the permissions on the folder and it currently on 0755.
When I run my php code, I get this error code:
"Error uploading file - check destination is writeable."
The post that was similar to my issues is this: How to upload photo to my hosting server folder directory
but I already have these functions in my code:
Here my php code:
<?php
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filesize = $_FILES["file_img"]["size"];
$fileinfo = getimagesize($_FILES["file_img"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../photo/".$filename;
$filepath_thumb = "../photo/thumb/".$filename;
if($_POST['btn_upload'])
{
$sPhotoFileName = $filename;
$nPhotoSize = $filesize;
$sTempFileName = $filetmp;
chmod($filepath_thumb,0755);
chmod($filepath,0755);
if(file_exists('photo/' . $_FILES['file_img']['name'])){
die('File with that name already exists.');
}else{
if ($sPhotoFileName) // file uploaded
{ $aFileNameParts = explode(".", $sPhotoFileName);
$sFileExtension = end($aFileNameParts); // part behind last dot
if ($sFileExtension != "jpg"
&& $sFileExtension != "png"
&& $sFileExtension != "gif")
{ die ("Choose a JPG for the photo");
}
}
if($_FILES['file_img']['error'] > 0){
die('An error ocurred when uploading.');
}
if ($nPhotoSize == 0)
{ die ("Sorry. The upload of $sPhotoFileName has failed.
Search a photo smaller than 300K, using the button.");
}
if ($nPhotoSize > 30240000000)
{ die ("Sorry.
The file $sPhotoFileName is larger than 300K.
Advice: reduce the photo using a drawing tool.");
}
// read photo
$oTempFile = fopen($sTempFileName, "r");
$sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
// Try to read image
$nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
$oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
error_reporting($nOldErrorReporting);
if (!$oSourceImage) // error, image is not a valid jpg
{ die ("Sorry.
It was not possible to read photo $sPhotoFileName.
Choose another photo in JPG format.");
}
}
$nWidth = imagesx($oSourceImage); // get original source image width
$nHeight = imagesy($oSourceImage); // and height
// create small thumbnail
$nDestinationWidth = 80;
$nDestinationHeight = 60;
//$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
$oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
/*$oResult = imagecopyresampled(
$oDestinationImage, $oSourceImage,
0, 0, 0, 0,
$nDestinationWidth, $nDestinationHeight,
$nWidth, $nHeight); // resize the image
*/
imagecopyresized($oDestinationImage, $oSourceImage,0, 0, 0, 0,$nDestinationWidth, $nDestinationHeight,$nWidth, $nHeight); // resize the image
ob_start(); // Start capturing stdout.
imageJPEG($oDestinationImage); // As though output to browser.
$sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
ob_end_clean(); // Dump the stdout so it does not screw other output.
// attempt insert query execution
$sql = "INSERT INTO UploadImg (img_name, img_path, img_type) VALUES ('$sPhotoFileName', '$filepath', '$filetype')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(!move_uploaded_file($_FILES["file_img"]["tmp_name"],"../photo/".$_FILES["file_img"]["name"])){
die('Error uploading file - check destination is writeable.');
echo "Error Code: " .$_FILES["file_img"]["name"] . "<br>";
}else{
$sBinaryThumbnail = addslashes($sBinaryThumbnail);
$oDatabase = $link;
mysqli_select_db("upload", $oDatabase);
$sQuery = "insert into Uploadimg (thumbnail) VALUES ('$sBinaryThumbnail')";
echo $sQuery;
mysqli_query($sQuery, $oDatabase);
die('File uploaded successfully.');
mysqli_close($link);
}
}
?>
Now I read an article say that even if your folder permission setup up to do all three read, write, and executed on all three level. the code still will not be able to read it depending on the settings on the server.
So I am confused and looking for clarification. Please assist me?
You can upload the image by binary data encoded and save the file with the image format on the server.
755 means it is not world writable. You can set it writable and executable with 777.
This is still vulnerable as anyone with access to your server os can write to the folder, so you should probably just make the web server user the owner of the folder and keep the permissions as they are now. If you're running apache, the user is usually www-data or apache.
I figure it out you gotta set the GID and UID permissionsfilepermission
The set group identification GID allows the owner to execute all applications to read, write and pull to the folder.
Same thing with the User identification UID. the problem is the your folder will be wide open for strangers to manipulate it but it works.
My images are uploading into the folder. Tell me what yall think?
First in your php.ini put
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to upload:
<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">
Make sure that the form uses method="post"
Then use the php code below to upload image
<?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;
}
}
?>
I've read the Secure PHP Upload Scripts thread but I'm having difficulty getting this known good script to accept changes. I want this script to only allow .jpeg, .png, and .gif files. Could someone advise me on how to modify this script to do so?
<?php
$result=0;
if (trim($_POST["action"]) == "Upload File") { //**** User Clicked the Upload File Button
//*********** Execute the Following Code to Upload File *************
$imagename = basename($_FILES['image_file']['name']); // grab name of file
$result = #move_uploaded_file($_FILES['image_file']['tmp_name'], $imagename); // upload it
if ($result==1) echo("Successfully uploaded: <b>".$imagename."</b>"); // did it work?
} // end if
?>
<?php
if ($result==1) echo("<img src='".$imagename."'>"); // display the uploaded file
?>
$filename = $_FILES['image_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext !== 'jpg' && $ext !== 'png' && $ext !== 'gif') {echo 'error';}
is a very bad idea for validation.
echo '<pre>';
$filename = 'image.php\0.jpg';
$extension = pathinfo($filename, PATHINFO_EXTENSION);
var_dump($ext);
The var_dump displays jpg
And the php function move_uploaded_file is vulnerable with null bytes \0.
After the move_uploaded_file the server will create a image.php file..
If you want to stop the upload before it reaches your server, you can filter it with javascript. See this SO answer for more information: stackoverflow.com/questions/71944/… – Kevin Apr 26 at 22:13
Never never never never neverever put trust in client side validation...
Coding a safe upload is hard. Very hard.
You can't trust file extensions or mime type because clients can change this.
If you only want an upload for gif, jpeg or png you could take these steps. With png you can have trouble because of the encoding that can bypass some of these.
Read the temp file by file_get_contents().
Run strip_tags() on it.
Create new images with the GD library
Serve the image by read() - Don't use include() or require()
Disable php engine on that directory
For the sake of brevity, i'm not doing any error checking.. but you can evaluate the extension of a file like this:
$filename = $_FILES['image_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext !== 'jpg' && $ext !== 'png' && $ext !== 'gif') {echo 'error';}
Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}