草庐IT

PHP 将 $_FILES 和 $_POST 作为参数传递给函数

coder 2024-04-15 原文

我在网上搜索了一个使用 ajax 进行 PHP 图片上传的代码。我找到了下面附上的代码。问题是我改变了一些东西(小调整)以使其在我的服务器上运行。最初它只是一个处理从表单发布的数据的 php 页面(不是类或函数)。我让它进入类然后发挥作用。我现在正在关注 OOP。我认为在从过程到 OOP 的转换中做事的最好方法是将 $_FILES 和 $_POST 传递给一个方法并在内部处理它们。我认为这没有用。查看示例,请就如何继续进行提出建议。

function uploadImageChosen($_FILES, $_POST){
            $path = "../uploads/images/";
            $valid_formats = array("jpg", "png", "gif", "bmp");
            $connectionInstance = new ConnectionClass();
            $connectionInstance->connectToDatabase();
            $imgName;
            $imgURL;
            $imgSize;
            $imgDir = $_POST['directory'];
            if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
            {
                $name = $_FILES['photoimg']['name'];
                $imgSize = $_FILES['photoimg']['size'];
                if(strlen($name))
                {
                    list($txt, $ext) = explode(".", $name);
                    if(in_array($ext,$valid_formats))
                    {
                        if($size<(1024*1024))
                        {
                            $imgName = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                            $tmp = $_FILES['photoimg']['tmp_name'];
                            if(move_uploaded_file($tmp, $path.$imgName))
                            {
                                $imgURL = $path.$imgName;
                                $connectionInstance->query("INSERT INTO imagesupload(id, title, url, size, directory) VALUES (null, '$imgName','$imgURL', '$imgSize', '$imgDir')");
                                //echo "<img src='uploads/".$imgName."'  class='preview'>";
                            }
                            else{
                                echo "failed";
                            }
                        }else{
                            echo "Image file size max 1 MB";                    
                        }
                    }else{
                        echo "Invalid file format..";   
                    }
            }else{
                echo "Please select image..!";
            }           

          }//end of if      

        }//end of function

关于调用类函数的页面,这里是:

<?php
    require_once("../classes/UploadImages.php");
    $uploadInstance = new UploadImages();
    $uploadInstance->uploadImageChosen($_FILES, $_POST);
    //header("LOCATION:portfolio.php");
?>

非常感谢:)

最佳答案

$_POST$_FILES 是超全局数组,它们总是可用的,在函数或方法中重新定义它们是个坏主意。

你可以这样做:

$uploadInstance->uploadImageChosen();

..

function uploadImageChosen(){
           $path = "../uploads/images/";
           $valid_formats = array("jpg", "png", "gif", "bmp");
...
$name = $_FILES['photoimg']['name'];
...

或者如果您需要本地范围内的副本,请这样做:

$uploadInstance->uploadImageChosen($_FILES, $_POST);

..

function uploadImageChosen($files, $post){
               $path = "../uploads/images/";
               $valid_formats = array("jpg", "png", "gif", "bmp");
...
$name = $files['photoimg']['name'];
...

关于PHP 将 $_FILES 和 $_POST 作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10738627/

有关PHP 将 $_FILES 和 $_POST 作为参数传递给函数的更多相关文章

  1. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  2. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  3. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

  4. ruby-on-rails - rails : How to make a form post to another controller action - 2

    我知道您通常应该在Rails中使用新建/创建和编辑/更新之间的链接,但我有一个情况需要其他东西。无论如何我可以实现同样的连接吗?我有一个模型表单,我希望它发布数据(类似于新View如何发布到创建操作)。这是我的表格prohibitedthisjobfrombeingsaved: 最佳答案 使用:url选项。=form_for@job,:url=>company_path,:html=>{:method=>:post/:put} 关于ruby-on-rails-rails:Howtomak

  5. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  6. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  7. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  8. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  9. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  10. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

随机推荐