Video Uploads in PHP, can't find upload directory? - php

im using this php video upload script. i have set my directory path to a folder called video which i have created with the same directory as the php file. But i can not find the video being uploaded.
It is not going to the directory i have asked it to? Why is this can someone please help me.
I am not receiving any errors.
Thanks.
HTML:
<form action="upload_videos_process.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadFile" id="uploadFile" />
<br />
<input type="submit" name="submit" value="Upload File" />
</form>
php file:
<?php
//This handles the maximum size for the video file in kbs
define ("MAX_SIZE","500");
//This function reads the extension of the file to ensure that it is an video file
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable handles an error and won't upload the file if there is a problem with it
$errors=0;
//checks if the form has been submitted
if(isset($_POST['Submit']))
{
//reads the name of the file the user submitted for uploading
$video=$_FILES['video']['name'];
//if it is not empty
if ($video)
{
//get the original name of the file from the clients machine
$video_filename = stripslashes($_FILES['video']['name']);
$video_extension = getExtension($filename);
$video_extension = strtolower($extension);
//if it is not a known extension, we will suppose it is an error and will not upload the file, otherwise we will do more tests
if (($video_extension != "mpeg") && ($video_extension != "avi") && ($video_extension != "flv") && ($video_extension != "mov"))
{
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the video
$size=filesize($_FILES['video']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
//give the video a unique name in case a video already exists with the name on the server
$video_name=time().'.'.$extension;
//assign a folder to save the video to on your server
$newname="video/".$video_name;
//verify that the video has been loaded
$copied = copy($_FILES['video']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessful!</h1>';
$errors=1;
}}}}
//If no errors registered, print the success message
if(isset($_POST['Submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully! Try again!</h1>";
}
?>

You've blindly assumed everything's working perfectly. Things fail. First step: check if the upload actually did anything:
if ($_FILES['video']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['video']['error']);
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php
As well, don't use copy() on the upload file, once you've verified the upload succeeded. There's move_uploaded_file() for a reason - it has extra security checks to ensure that the file hasn't been tampered with on the server, and it actually MOVES the file. copy() can kill performance, especially on large files, since you're duplicating the file, instead of just doing some filesystem housekeeping.
You're also trusting the user to not tamper with the filename. There is NOTHING to prevent a malicious user from doing ren nastyvirus.exe cutekittens.avi before uploading, and your script will happily accept that .exe, because its filename has simply been changed. Use server-side mime-detection (e.g http://www.php.net/manual/en/book.fileinfo.phpenter link description here) to get around this. NEVER trust ANYTHING from a user.

It might be because your php configuration does not allow to upload big files. Try setting
upload_max_filesize = 500M
or even larger than 500M in php.ini & also as ppl mention here in comments, enable the errors
ini_set('display_errors', 1);
ini_set('error_reporting', 8191);

Related

PHP - limit the file size but somehow got Warning: POST Content-Length exceeds the limit

I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.
Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
instead of the error message of "Sorry, your file is too large. Only 3MB allowed" from the php code.
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
<?php
include("config.php");
if(isset($_POST['submit']) ){
//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$allowed = array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext, $allowed)){
if($filesize > 3000000) {
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
else{
echo "Sorry, your file is too large. Only 3MB allowed";
}
}
else{
echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
}
//if user has no file to upload then proceed to this else statement
} else {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;
if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}
}
$con->close();
}
?>
I don't get it. What did I do wrong in this code?
I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.
Its not a problem with your code. The http request isnt going through php because of the post max size setting.
Find this line in your php.ini of the server and change it:
; http://php.net/post-max-size
post_max_size = [max uploadsize like '32M' or '1G']
Can you post the form HTML code ?
The problem is, php has a directive (post_max_size) that limits the size of what he allows in POST - before any execution of your script. So, if this limit is reached, the warning is emitted before your script is called, and $_POST is not filled in.
It would deserves additional testing, but be sure :
to include MAX_FILE_SIZE hidden field in your form (see http://php.net/manual/en/features.file-upload.post-method.php).
to set post_max_size to something largely greater to what you want to accept
to set upload_max_filesize to (at first sight) the value you want.
In addition, it would also be intersting to try setting the maxlength attributes on the input, as this is is stated in the RFC-1867.
If the INPUT tag includes the attribute MAXLENGTH, the user agent should consider its value to represent the maximum Content-Length which the server will accept for transferred files.
In this way, servers can hint to the client how much space they have available for a file upload, before that upload takes place. It is important to note, however, that this is only a hint, and the actual requirements of the server may change between form creation and file submission.
This would allow to forbid the upload directly in the browser that respect the RFC.

PHP uploading issues

I'm having strange issues when uploading to the server via PHP.
I get the type of the file (working properly, it shows them via echo)
$file = $_FILES['file'];
$typeFile = end(explode(".", $file['name']));
Then I make some comparasions to let them upload it or not, here are the fille types allowed
if($file['size'] <= 52428800) { //50MB, and my file is about 2,5MB
if($fileType == "nlpack" || $fileType == "nl2pkg" || $fileType == "nlpark") {
$id = add_to_db($file['name']); //Adding to database the name, this will return an id, it works
if($id) {
mkdir("uploads/".$id); //create a folder where to add the file, working fine!
if(move_uploaded_file($file['tmp_name']), ".uploads/".$id."/".$file['name']) {
echo "file uploaded correctly";
}
else {
echo "has been an error"; //it enters here, while the other file types enters in the if()
}
}
else {
echo "Has been an error";
}
} else {
//alert an error
}
}
The thing is, that "nlpack" file type doesn't uploads, and it enters the if() because I checked it with echos, while the other two are uploaded without problem.
I also check the file size, but that's running fine.
Any ideas of what is going on?
Thanks in advance
Make sure the filesize isn't exceeding the settings in your php.ini or the file will just fail to upload.
upload_max_filesize integer
The maximum size of an uploaded file.
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
AND if muliple:
max_file_uploads integer
The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

prevent uploading of large and unsupported files in image upload form

i have a php form with an image upload option as follows
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<label for="new_picture">Picture:</label>
<input type="file" id="new_picture" name="new_picture" />
and php script something like
if (!empty($new_picture)) {
if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
if ($_FILES['file']['error'] == 0) {
// Move the file to the target upload folder
$target = MM_UPLOADPATH . basename($new_picture);
if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
// The new picture file move was successful, now make sure any old picture is deleted
if (!empty($old_picture) && ($old_picture != $new_picture)) {
#unlink(MM_UPLOADPATH . $old_picture);
}
}
else {
// The new picture file move failed, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
}
}
}
else {
// The new picture file is not valid, so delete the temporary file and set the error flag
#unlink($_FILES['new_picture']['tmp_name']);
$error = true;
echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
}
}
every thing works fine but problem occurs when as a test i tried to upload a .zip file the image was not loaded but it flushed my database. all the entries for that user were deleted.
now i want a some suggessions about how to prevent this
thanks in advance
On the client side, there is not much you can do that you can actually rely on. But it can help prevent accidental problems.
Add this attribute to the file upload control to limit file types: accept="image/gif, image/jpeg"
Your validation needs to happen on server side if you want to be sure about what you are getting.
Check $_FILES['uploadctl']['size'] for the size of the file and see if it exceeds your limits.
You can force php to limit what size file uploads it accepts by setting upload_max_filesize in php.ini. Default for this is pretty low.
You cant really trust that the extension of an uploaded file is actually correct. Just because it says .jpg doesn't mean it really is. If all you are accepting is images, you should be able to verify the mimetype with getimagesize(). If you are accepting a larger range of files, check the file with Fileinfo.
If the entries in the database were deleted, you probably have a logic problem in code that you are not showing here.

Basic file upload - 500 Internal Server Error

Just playing around with uploading files as it's actually something I've never done before. I copied some supposedly working code from here.
I'm using cPanel hosting from Namecheap, with absolutely nothing changed from the default config.
I think the most likely problem is something very basic that I haven't activated. My HTML looks like this
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="photo" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and my PHP looks like this
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']
}
When I try to upload an image, I get a 500 Internal Server Error when I hit submit.
What am I missing?
Thanks
Get rid of the stuff at the bottom:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
Not sure what that was for... Also, try checking the Namecheap php.ini in your CPanel to see what the max upload size is so your users get your error, not a PHP error or a 500.

Upload script in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to do File Upload in PHP
I am trying to learn to write file upload script in PHP. I don't know why this doesn't work. Please have a look
<?php
$name=$_FILES["file"]["name"];
if(isset($name)) {
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
?>
It gives an error message Notice: Undefined index: file in
The html part is
<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" /></form>
I am using wamp on Windows. What may be the cause for the error ?
You need to check if the form was submitted before executing your PHP code:
<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {
if (isset($_FILES["file"]["name"])) {
$name = $_FILES["file"]["name"];
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
}
?>
The clue is in the error message. The index 'file' doesn't exist in the FILES array. At a guess because you have this code before you've sumitted the form?
check if it exists first,
if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded
then check your use of the field components.
$_FILES['userfile']['name'] # The original name of the file on the client machine.
$_FILES['userfile']['type'] # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] # The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] # The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] # The error code associated with this file upload

Categories