I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.
Related
Hello I am trying to check the size of a file in PHP but it does not seem to work. My input page is
<html>
<title>File Upload</title>
<body>
<h1>
Upload Files
</h1>
<form action = "yes.php" method = "POST" enctype="multipart/form-data">
Upload your file
<input type = "file" name = "file" id = "fileToUpload">
<input type ="submit" name ="submit" value = "Start Upload">
</form>
</body>
</html>
This is the yes.php
<?php
$filename = $_FILES["file"]["name"];
$filesize = $_FILES["file"]["size"];
if (isset($_POST["submit"])) {
echo "$filename";
echo "\n$filesize";
if ($filesize < 4) {
echo "good";
} else {
echo "bad";
}
}
?>
It outputs
disc.mp4 0good
The file disc.mp4 is 5.8 MB but it returns as 0 MB even when it correctly identifies the name of the file. How can I fix this?
The different keys of the $_FILES array are explained here. Your code is taking for granted that every script invocation contains a valid file upload, which of course if often untrue: just open yes.php in your browser and you'll see (or you should see) lots of error messages. You're also making a strange check: the upload is valid if the file size is 0 to 3 bytes :-!
The bare minimum you need is:
Accommodate the fact that $_FILES['file'] may or may not exist.
Verify whether the upload succeeded.
If you expect a 5.8 MB file, don't require it to have an arbitrary smaller size.
Following you code style, I'd be something like:
<?php
$error = $_FILES["file"]["error"] ?? null;
$filename = $_FILES["file"]["name"] ?? null;
$filesize = $_FILES["file"]["size"] ?? null;
$expected_size = 5.8 * 1024 * 1024; # Assuming you want to enforce this for some reason
if ($error === UPLOAD_ERR_OK) {
echo "$filename";
echo "\n$filesize";
if ($filesize != $expected_size) {
echo "good";
} else {
echo "bad";
}
} elseif($error !== UPLOAD_ERR_NO_FILE) {
echo "upload failed";
}
I have written a script to upload a file and store the path in a database table so it be downloaded. I have the following code:
<?php require("includes.php");
?><!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if(isset($_FILES["upload"])==TRUE)
{
$errors = array();
$excluded = array("exe", "zip", "js", "msi");
/* If the contents of the file are to be held in the database then checking the extension is somewhat unneccessary but, hey, lets get rid of the files we know we don't want and then check the mime type. */
$name = $_FILES["upload"]["name"];
$size = $_FILES["upload"]["size"];
$type = $_FILES["upload"]["type"];
$temp = $_FILES["upload"]["tmp_name"];
$extension = explode(".", $name);
$extension = end($extension);
if(in_array($extension, $excluded)==TRUE)
{
$errors[] ="This file may not be uploaded";
}
if(empty($errors)==FALSE)
{
foreach($errors as $error)
{
echo "<p>{$error}</p>\n";
}
}
else
{
$year = date("Y");
$month = date("m");
$day = date("d");
$name = strtolower(str_replace(" ", "_", $name));
$path = "uploads/{$day}-{$month}-{$year}";
if(file_exists($path)==FALSE)
{
mkdir($path);
}
elseif(file_exists("{$path}/{$name}")==FALSE)
{
move_uploaded_file($temp, "{$path}/{$name}");
$add = add_file_to_database($connection, "{$path}/{$name}");
if($add[0]==TRUE)
{
$url = "http://example.com/uploads.php?id={$add[1]}";
echo "<p>This file has been uploaded, it can be found at: {$url}</p>";
}
else
{
echo "<p>I'm sorry but an error happened</p>";
}
}
}
}
?>
<form action="index.php" method="post" enctype="multipart/form-data">
<label for="upload">Upload a file: </label><input type="file" name="upload" id="upload"><br>
<input type="submit" value="Upload" name="submit">
</form>
</body>
</html>
The code in uploads.php is:
<?php require("includes.php");
$file = get_uploaded_file($connection, $_GET["id"]);
header("Content-Type:{$file[0]}");
echo file_get_contents($file[1]);
?>
If I upload a jpeg file, a PDF or txt file then it displays in the browser as I want it to do but if I upload a word file or a MP3 then I want it to download as the normal file instead of being uploads.php
Not sure how I am going to achieve this. Can you give me some ideas as to how I do this so if I upload "demo.mp3" and I get an ID of 1 then I want it to download a file entitled "demo.mp3". Just thinking that MS Word doesn't recognise its own MIME type
I am using php to upload and move a file to a desired location...
while using move_uploaded_file, it says that the file has moved successfully but the file does not show up in the directory.
THE HTML AND PHP CODE IS BELOW...
<form action="test_upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="test_pic">Testing Picture</label>
<input type="file" name="test_pic" size="30" /><br />
</fieldset>
<fieldset>
<input type="submit" value="submit" />
</fieldset>
</form>
THe php goes like :
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
?>
when i run this page and upload a legitimate file - the test_upload.php echoes file uploaded successfully. but when i head on to the folder "vidit" in the root of the web page. the folder is empty...
I am using wamp server .
You need to append filename into your destination path. Try as below
$doc_path = realpath(dirname(__FILE__));
if(move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$doc_path.$upload_dir.'/'.$_FILES[$image_fieldname]['name']) && is_writable($upload_dir)){
$display_message = "file moved successfully";
}
else{
$display_message = " STILL DID NOT MOVE";
}
See PHP Manual for reference. http://php.net/manual/en/function.move-uploaded-file.php
<?php
$image_fieldname = "test_pic";
$upload_dir = "/vidit";
$display_message ='none';
if (move_uploaded_file($_FILES[$image_fieldname]['tmp_name'],$upload_dir . '/' . $_FILES[$image_fieldname]['name'] && is_writable($upload_dir)) {
$display_message = "file moved successfully";
} else {
$display_message = " STILL DID NOT MOVE";
}
?>
Added indenting as well. The file name needs to be applied, or it's like uploading the file as a extensionless file.
Use this it may work
$upload_dir = "vidit/";
$uploadfile=($upload_dir.basename($_FILES['test_pic']['name']));
if(move_uploaded_file($_FILES['test_pic']['tmp_name'], $uploadfile) ) {
}
Create tmp directory in root(www) and change directory path definitely it works
/ after your directory name is compulsory
$upload_dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];
I have made an application to upload files and it's working out well. Now I want to upload my files on a database, and I also want to display the uploaded files names on my list by accessing the database.
So please help me do this. My code is given below:
function uploadFile() {
global $template;
//$this->UM_index = $this->session->getUserId();
switch($_REQUEST['cmd']){
case 'upload':
$filename = array();
//set upload directory
//$target_path = "F:" . '/uploaded/';
for($i=0;$i<count($_FILES['ad']['name']);$i++){
if($_FILES["ad"]["name"])
{
$filename = $_FILES["ad"]["name"][$i];
$source = $_FILES["ad"]["tmp_name"][$i];
$type = $_FILES["ad"]["type"];
$name = explode(".", $filename);
$accepted_types = array('text/html','application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type)
{
if($mime_type == $type)
{
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "F:" . '/uploaded/'.$filename;
// change this to the correct site path
if(move_uploaded_file($source, $target_path )) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("F:" . '/uploaded/'); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
echo "Your .zip file was uploaded and unpacked.";
$template->main_content = $template->fetch(TEMPLATE_DIR . 'donna1.html');
break;
default:
$template->main_content = $template->fetch(TEMPLATE_DIR . 'donna1.html');
//$this->assign_values('cmd','uploads');
$this->assign_values('cmd','upload');
}
}
my html page is
<html>
<link href="css/style.css" rel="stylesheet" type="text/css">
<!--<form action="{$path_site}{$index_file}" method="post" enctype="multipart/form-data">-->
<form action="index.php?menu=upload_file&cmd=upload" method="post" enctype="multipart/form-data">
<div id="main">
<div id="login">
<br />
<br />
Ad No 1:
<input type="file" name="ad[]" id="ad1" size="10" /> Image(.zip)<input type="file" name="ad[]" id="ad1" size="10" /> Sponsor By : <input type="text" name="ad3" id="ad1" size="25" />
<br />
<br />
</div>
</div>
</form>
</html>
Why not save the uploaded filename as a field in the db?
Looking at your code you have implemented the "Upload" you dont seem to be storing the file location into a database, you need to do the following:
On upload, store the details of the filename and path into a database table
To display these as a list - query the database, and write back to HTML page.
There are loads of examples of this on the internet, PHP.net is a good place to start.
If all you need to do is display the contents of a directory, then you can achieve a listing without the need of a database.
If you really need to upload onto the database you can use BLOBs (Binary Large Object) to achieve this:
See these links:
Wikipedia - Binary large object
MySQL - The BLOB and TEXT Types
PostgreSQL - Large Objects (BLOBs)
Also, rephrase your question!