PHP file database upload - php

don't have much experience with php programming and web in general, so I've build this code from tutorials and what it supposed to do is to store data in database, but it seems like it completely ignores any statement(e.g. exception when choosing incorrect data format) and it sort of just refreshes the page after hiting submit button, any ideas how to fix this?
<div id='box'>
<form method='post' enctype='multipart/form-data'>
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['size'];
$randon_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'MP4' && $type != 'flv' && $type !='avi'){
$message = "bad format";
}
else{
mysql_query("INSERT INTO videos VALUES('', '$name', 'videos/$randon_name.$type')");
$message = "successful upload";
}
echo $message;
}
?>
Choose file : <br/>
<input type='file' name='video'/>
<br/><br/>
<input type='submit' value='Upload'/>
</form>
</div>

It seems to be the case that you selected a file larger than your upload_max_filesize or post_max_size.
If this is the case then the $_FILES variable is empty and you see nothing. If you select a smaller file you should see something when doing a print_r($_FILES) at the top of your script.
if you run php in apache as a module you can try to add a .htaccess like this:
php_value upload_max_filesize 200M
php_value post_max_size 200M
Otherwise you need to edit your php.ini. As far as i know you cannot set these php.ini values via ini_set().

Related

I cannot upload files > 100K

I am not able to upload files larger than 100KB. Uploading multiple smaller files is OK. This is LAMP running on Fedora 27.
Here are the pertinent code snippets. The return value is "2", which I believe means that the file is too big. I've already set and adjusted the usual suspects in php.ini. I am not getting to $mail->AddAttachment so I don't expect that it is a phpmailer issue.
Front End Code :
<form method="post" enctype="multipart/form-data"\>
<input name="file_arr[]" id='userfiles' type="file" multiple="multiple"/ >
<input type='submit' name='submit' id='submit' value='Send' />
Back End Code :
$mail = new PHPMailer;
.
foreach ($_FILES["file_arr"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file_arr"]["tmp_name"][$key];
$fname = $_FILES["file_arr"]["name"][$key];
$mail->AddAttachment($tmp_name, $fname);
$fcnt++;
} else {
return($error);
}
}
Adjust php.ini
You need to check php.ini to see what your max file upload size is set to. You can adjust memory_limit, upload_max_filesize, post_max_size variables accordingly.
Get php.ini Location
To find your php.ini, run phpinfo() and echo the results: echo phpinfo();
You may or may not need to echo phpinfo().

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 file upload error tmp_name is empty

I have this problem on my file upload. I try to upload my PDF file while checking on validation the TMP_NAME is empty and when I check on $_FILES['document_attach']['error'] the value is 1 so meaning there's an error.
But when I try to upload other PDF file it's successfully uploaded. Why is other PDF file not?
HTML
<form action="actions/upload_internal_audit.php" method="post" enctype="multipart/form-data">
<label>Title</label>
<span><input type="text" name="title" class="form-control" placeholder="Document Title"></span>
<label>File</label>
<span><input type="file" name="document_attach"></span><br>
<span><input type="submit" name="submit" value="Upload" class="btn btn-primary"></span>
</form>
PHP
if(isset($_POST['submit'])){
$title = $_POST['title'];
$filename = $_FILES['document_attach']['name'];
$target_dir = "../eqms_files/";
$maxSize = 5000000;
if(!empty($title)){
if(is_uploaded_file($_FILES['document_attach']['tmp_name'])){
if ($_FILES['document_attach']['size'] > $maxSize) {
echo "File must be: ' . $maxSize . '";
} else {
$result = move_uploaded_file($_FILES['document_attach']['tmp_name'], $target_dir . $filename);
mysqli_query($con, "INSERT into internal_audit (id, title, file) VALUES ('', '".$title."', '".$filename."')");
echo "Successfully Uploaded";
}
}else
echo "Error Uploading try again later";
}else
echo "Document Title is empty";
}
I just check the max size in phpinfo();
Then check if php.ini is loaded
$inipath = php_ini_loaded_file();
if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
Then Change the upload_max_filesize=2M to 8M
; Maximum allowed size for uploaded files.
upload_max_filesize = 8M
; Must be greater than or equal to upload_max_filesize
post_max_size = 8M
Finally reset your Apache Server to apply the changes
service apache2 restart
var_dump($_FILES['file_flag']['tmp_name']); // file_flag file key
will return empty string
array (size=1)
'course_video' =>
array (size=5)
'name' => string 'fasdfasdfasdfsd.mp4' (length=19)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0) <===== *** this point
'error' => int 1
'size' => int 0
This happen because WAMP server not accepting this much size to uploaded on server.
to avoid this we need to change php.ini file.
upload_max_filesize=100M (as per your need)
post_max_size = 100M (as per your need)
finally restart server
another option is to add a separate config file with upload limits.
i created uploads.ini:
memory_limit = 64M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 60
and placed it in conf.d directory
in my case using Docker: /usr/local/etc/php/conf.d/uploads.ini
that way i could keep my production php.ini and add this just for uploads control

PHP uploading a file not working

The code below is to upload files to a local folder. Once I select a file from the Dialog Box, it should display "OK" to confirm selection of file. But the code below is not working as required.
<?php
if(isset($_FILES['file']['name']))
$name = $_FILES['file']['name'];
if(isset($_FILES['file']['tmp_name']))
$tmp_name = $_FILES['file']['tmp_name'];
if(isset($name))
{
if(!empty($name))
echo 'OK';
else
echo 'Please chose a file';
}
?>
<form action="up.php" method="POST" encrypt="multipart/form-data">
<input type="file" name="file"><br><br>
<input type="submit" value="Submit">
</form>
First try:
var_dump($_FILES);
If you are not seeing anything in there on post, then you may need to set the following in your php.ini file:
file_uploads = On;
You may also need to change the allowed file sizes in the php.ini file if the file you are trying to upload is bigger than what is allowed:
post_max_size = 8M; make larger if needed
upload_max_filesize = 8M; make larger if needed*
After making these changes make sure to restart your webserver (apache/nginx.)
* upload_max_filesize should never be bigger than post_max_size
......

Max_File_Uploads directive php.ini

Im trying to do a simple file upload. I've done it many times before and it's been fine. For some reason this time I keep getting error UPLOAD_ERR_INI_SIZE coming up. Even though i've uploaded bigger files on the same server before. Here is my PHP.INI:
display_errors = On
short_open_tag = On
memory_limit = 32M
date.timezone = Europe/Paris
upload_max_filesize = 10M
post_max_size = 10M
And my HTML form:
<form action="/settings/upload-image" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="<?=(1024*1024*1024);?>">
<input name="files[]" id="attachfile" type="file" />
<br /><br />
<input type="submit" class="submit" value="Upload New Profile Image">
</form>
And my code:
foreach($files as $file)
{ $ext = strtolower(pathinfo($file[0], PATHINFO_EXTENSION));
if(in_array($ext,$allowed_upload_ext)===TRUE)
{
if(!$file[3]) { // If no error code
//$newFile = $me['id'].".$ext";
$newFile = $file[0];
resizeImage($file[2],PROFILE_IMAGES."/".$newFile,$ext,500);
genThumbFile($file[2],PROFILE_IMAGES."/thumb/".$newFile);
runSQL("UPDATE `users` SET `image`='{$file[0]}' WHERE `id`='{$me['id']}';");
array_push($msgs,"Image uploaded successfully.");
$me = select("SELECT * FROM `users` WHERE `id`='{$me['id']}';",true);
} else {
array_push($msgs,"!".fileError($file[3]));
}
} else {
array_push($msgs,"!The file ".$file[0]." could not be uploaded as it is the wrong file type.");
}
}
The only difference this time is that I am resizing and genorating thumbs with the temporary upload file instead of copying over the file first. Could that be the problem? I dont think so, because if the image is small it works perfectly fine. But I try anything like 2mb and it throws a fit.
Suggestions?
Thanks for ALL YOUR HELP guys. :P
I solved it - Missing line in PHP.INI:
file_uploads = On
Just for anyone who fins this.

Categories