简体   繁体   English

在上传之前显示文件大小...?

[英]Show the size of file before upload…?

I need the php to work with javascript... :| 我需要php才能使用javascript ...:|

I want the user to upload only max 5MB files, but PHP detects it only after the upload is done... example: 我希望用户最多只能上传5MB的文件,但是PHP仅在上传完成后才能检测到它。例如:

if ($_FILES["ftu"]["size"] > 5242880) {
        echo "<br /><font color='#FF4747'>Sorry, but maximum size of the uploaded file must not exceed 5MB</font>";
}

It works, but it echoes only after the file is actually uploaded... and I don't want it... Another option is to check it with javascript: 它可以工作,但只有在文件实际上传后才回显...而我不想要...另一个选择是使用javascript检查它:

$(document).ready(function(){
        $('#upheadinp').bind('change', function() {
            if(this.files[0].size > 5242880){
            $('#uploadspan').html("<font color='#FF4747'>Max file size is 5MB</font>");
            }
        });
    });

Yeah so this works too, but it's only to show the error message... How could I merge php if function with this javascript function ? 是的,所以这也可行,但这仅是显示错误消息...我如何将php if function与此javascript function合并?

My expectations are something like: 我的期望是这样的:

<?php
if("<script>(this.files[0].size)</script>" > 5242880){
echo "error";
}
?>

Could someone help me out? 有人可以帮我吗? Thanks! 谢谢!

The above comments are obviously correct. 以上评论显然是正确的。 JS is a client-side scripting and PHP is server-side. JS是客户端脚本,PHP是服务器端。 The two do not directly interact for obvious reasons. 由于明显的原因,两者不直接相互作用。

The best solution would be to prevent the form from being able to submit. 最好的解决方案是阻止表单能够提交。 This would achieve what I interpret to be what you are looking for. 这将实现我认为是您正在寻找的东西。 A way to prevent someone from submitting in addition to the PHP prevention. 除了防止PHP外,还可以防止他人提交。 Proper programming convention would dictate any user submitted data (text, uploads, etc) should be validated both on the client and server ends. 正确的编程约定将指示在客户端和服务器端均应验证任何用户提交的数据(文本,上载等)。 Never trust client data and never assume it was properly validated. 永远不要信任客户端数据,也不要假设它已正确验证。

$("theformyouareusing").submit(function(e) {
    if($('input[type=file]').files[0].size > 5242880){
         e.preventDefault();
        }
    });

You may also want to have a check for older browsers that do not support .files.size and decide how you want to handle those cases. 您可能还需要检查一下不支持.files.size较旧的浏览器,并决定如何处理这些情况。

For additional security, you should add these lines into your php.ini: 为了提高安全性,您应该将以下几行添加到php.ini中:

post_max_size = 5M
upload_max_filesize = 5M

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM