dpmrakfbx820320638
2013-10-09 11:16
浏览 46
已采纳

PHP:如何创建foreach循环(简单代码)

I am new to PHP and have created a little code for a file upload on a form.

The code works fine but I was wondering if I could achieve the same using a foreach loop so that it could also handle more files and I dont have to write a separate line for each of them.

Can someone here help me with this and tell me how to write it properly.

My Code (working):

session_start();

$varUID = $_POST['UID'];
$varSender = $_SESSION['email'];

$varFile1 = $_FILES["file1"]["name"];
$varExt1 = pathinfo($varFile1, PATHINFO_EXTENSION);
$varFile2 = $_FILES["file2"]["name"];
$varExt2 = pathinfo($varFile2, PATHINFO_EXTENSION);
$varFile3 = $_FILES["file3"]["name"];
$varExt3 = pathinfo($varFile3, PATHINFO_EXTENSION);

move_uploaded_file($_FILES["file1"]["tmp_name"], "uploads/" . $varUID . "_1" . "." . $varExt1);
move_uploaded_file($_FILES["file2"]["tmp_name"], "uploads/" . $varUID . "_2" . "." . $varExt2);
move_uploaded_file($_FILES["file3"]["tmp_name"], "uploads/" . $varUID . "_3" . "." . $varExt3);

echo $varUID;

Thanks for any help with this, Tim

图片转代码服务由CSDN问答提供 功能建议

我是PHP的新手,并为表单上的文件上传创建了一些代码。

代码工作正常,但我想知道是否可以使用foreach循环实现相同的功能,这样它也可以处理更多文件,我不必为每个文件写一个单独的行 。

有人可以帮我这个并告诉我如何正确地写它。

我的代码(工作):

  session_start(); 
 
 $ varUID = $  _POST ['UID']; 
 $ varSender = $ _SESSION ['email']; 
 
 $ varFile1 = $ _FILES [“file1”] [“name”]; 
 $ varExt1 = pathinfo($ varFile1,  PATHINFO_EXTENSION); 
 $ varFile2 = $ _FILES [“file2”] [“name”]; 
 $ varExt2 = pathinfo($ varFile2,PATHINFO_EXTENSION); 
 $ varFile3 = $ _FILES [“file3”] [“name”  ]; 
 $ varExt3 = pathinfo($ varFile3,PATHINFO_EXTENSION); 
 
move_uploaded_file($ _ FILES [“file1”] [“tmp_name”],“uploads /”。$ varUID。“_ 1”。“。”。$  varExt1); 
move_uploaded_file($ _ FILES [“file2”] [“tmp_name”],“uploads /”。$ varUID。“_ 2”。“。”。$ varExt2); 
move_uploaded_file($ _ FILES [“file3”] [  “tmp_name”],“uploads /”。$ varUID。“_ 3”。“。”。$ varExt3); 
 
echo $ varUID; 
   
 
 

谢谢 对此有任何帮助, Tim

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • duanli6834 2013-10-09 11:19
    最佳回答
    foreach ($_FILES as $key => $file) {
        $name = $file["name"];
        $ext = pathinfo($name, PATHINFO_EXTENSION);
        preg_match('/(\d+)$/', $key, $match); // get 2 out of "file2"
        $nr = $match[1];
        move_uploaded_file($file["tmp_name"], "uploads/" . $varUID . "_" . $nr . "." . $ext);
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题