简体   繁体   English

使用php将文件上传到指定目录

[英]Upload a file to a specified directory using php

I'm trying to modify my php script to allow me to upload iamges and files to a specific folders within my program. 我试图修改我的php脚本,以允许将iamges和文件上传到程序中的特定文件夹。 At the moment I have a couple of php files that return a string of all the files held on my server and a script that only uploads images to the root of the server. 目前,我有几个php文件,它们返回服务器上保存的所有文件的字符串,以及一个仅将图像上传到服务器根目录的脚本。

For example my get directory script will return something like this: 例如,我的get目录脚本将返回以下内容:

Img1.jpg Img1.jpg

Img2.jpg Img2.jpg

Folder.folder 资料夹

I've got it so I can click and store what ever has been clicked on in this string and I want to pass it to my php script so that I can I upload my next image to folder.folder as opposed to the root. 我已经有了它,所以我可以单击并存储该字符串中曾经被单击的内容,我想将其传递给我的php脚本,以便我可以将下一个图像上传到folder.folder而不是根目录。

How can I go about doing that? 我该怎么做呢?

My php code for upload the file is as follows: 我上传文件的PHP代码如下:

<?
    $uploaddir = './';
    $file = basename($_FILES['file']['name']);
    $uploadfile = $uploaddir . $file;

    print_r($_FILES);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
        echo "http://ipAddress/serverFolder/{$file}";
     }
     else
     {
        echo "Failed to upload file";
      }
?>

Is there a best practise for going about doing what I wish to do? 做我想做的事是否有最佳实践?

I'm really new to PHP so any help would be appreciated. 我是PHP的新手,所以可以提供任何帮助。

Store the current directory in a session variable and then use that in your uploading script. 将当前目录存储在会话变量中,然后在上载脚本中使用它。

When a link is clicked: 单击链接时:

$_SESSION['directory'] = $_POST['directory'];

And then in your uploading script: 然后在您的上传脚本中:

$uploaddir = './'.$_SESSION['directory'];

After which you must perform some kind of validation to make sure that the directory being uploaded to is somewhere you actually want the files to be uploaded to. 之后,您必须执行某种验证,以确保要上传到的目录位于您实际希望将文件上传到的位置。 After that you can continue with the upload. 之后,您可以继续上传。

If I understand correctly, you are using form to upload a file and you want to specify a directory. 如果我理解正确,那么您正在使用表单上载文件,并且想要指定目录。 Simply add <input type="text" id="folder" name="folder"> where you can write directory path and then you can write it in in $uploaddir = $_POST['folder']; 只需添加<input type="text" id="folder" name="folder"> ,即可在其中写入目录路径,然后将其写入$uploaddir = $_POST['folder']; variable, assuming you are using post. 变量,假设您使用的是post。

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

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