如何重命名文件并为其创建下载链接 PHP


How to rename a file and create a download link for it PHP

所以目前我有一个用户提交的 html 表单,然后创建一个文件并使用 PHP 给出一个随机名称,我将如何获取用户创建的文件并重命名它,然后为其创建下载链接?

在简短的步骤中,用户填写表单,单击提交,创建具有随机名称的文件(例如434242.txt(,显示下载链接页面,用户单击下载链接,他们创建的文件作为新文件名下载到他们的计算机(例如customname.txt(。

我不知道我是如何做到这一点的,所以任何指导都会很棒!

这是我的 html 表单;

<form id="msform" action="result.php" method="post">
    <!-- progressbar -->
    <ul id="progressbar">
        <li class="active">Basic Details</li>
        <li>Server Options</li>
        <li>Final Touches</li>
    </ul>
    <!-- fieldsets -->
    <fieldset>
        <h2 class="fs-title">Add some basic details...</h2>
        <h3 class="fs-subtitle">This is step 1</h3>
        <input type="text" name="levelName" placeholder="Level Name" />
        <input type="text" name="messageOFTD" placeholder="Message of The Day" />
        <input type="text" name="port" placeholder="Server Port (Default is 25565)" />
        <input type="button" name="next" class="next action-button" value="Next" />
    </fieldset>
    <fieldset>
        <h2 class="fs-title">Customize your server...</h2>
        <label for="players">Max No. of Players</label>
        <input type="text" name="maxPlayers" placeholder="Maximum No. of Players" />
        <label for="select">Default Gamemode</label>
        <select value="select" name="defaultGamemode">
            <option value="SURVIVAL" name="survival">Survival</option>
            <option value="CREATIVE" name="creative">Creative</option>
            <option value="ADVENTURE" name="adventure">Adventure</option>
            <option value="SPECTATOR" name="spectator">Spectator</option>
        </select>
        <p>Force Gamemode</p>
        <input type="checkbox" name="forceGamemode" />
        <p>Difficulty</p>
        <select value="select" name="difficulty">
            <option value="0">Peaceful</option>
            <option value="1">Easy</option>
            <option value="2">Normal</option>
            <option value="3">Hard</option>
        </select>
        <p>Allow Flight</p>
        <input type="checkbox" name="allowFlight" />
        <p>Enable PvP</p>
        <input type="checkbox" name="enablePVP" />
        <p>Enable Command Blocks</p>
        <input type="checkbox" name="enableCommandBlock"  />
        <p>Spawn Animals</p>
        <input type="checkbox" name="spawnAnimals"  />
        <p>Spawn NPC's</p>
        <input type="checkbox" name="spawnNPC" />
        <p>Spawn Monsters</p>
        <input type="checkbox" name="spawnMobs" />
        <p>Hardcore Mode</p>
        <input type="checkbox" name="hardcoreMode" />
        <p>Allow Nether</p>
        <input type="checkbox" name="allowNether" />
        <p>Generate Structures</p>
        <input type="checkbox" name="generateStructure" />
        <p>Announce Achievements</p>
        <input type="checkbox" name="announceAchievements" />

        <input type="button" name="previous" class="previous action-button" value="Previous" />
        <input type="button" name="next" class="next action-button" value="Next" />
    </fieldset>
    <fieldset>
        <h2 class="fs-title">A few more settings</h2>
        <h3 class="fs-subtitle">You're almost done!</h3>
        <p>Online Mode</p>
        <input type="checkbox" name="onlineMode" />
                <p>Enable Query</p>
        <input type="checkbox" name="enableQuery" />
        <p>Enable Snooper</p>
        <input type="checkbox" name="enableSnooper" />
        <p>Enable RCON</p>
        <input type="checkbox" name="enableRCON" />
        <p>View Distance</p>
        <input type="text" name="viewDistance" placeholder="Default is 10" />
        <p>Level Seed</p>
        <input type="text" name="levelSeed" />
        <p>Resource Pack</p>
        <input type="text" name="pack" placeholder="Place URL of Pack Here" />
        <input type="button" name="previous" class="previous action-button" value="Previous" />
        <input type="submit" value="Submit" />
    </fieldset>
</form>

这是我的PHP文件;

<?php
//this code below generates a random string with 3 chars.. call it using radom_string(3);
function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));
    for ($i = 0; $i < $length; $i++) {
       $key .= $keys[array_rand($keys)];
    }
    return $key;
}
$id = random_string(3);
$ext = ".properties"; //adds file extension
$generatedBy = "#Generated by Serve A Server! Visit at http://serve.minecraftserver.uk.to/";
//force values for user file
$spawnProtection = "spawn-protection=16";
$maxTickTime = "max-tick-time=60000";
$genSettings = "generator-settings=";
$playerIdleTimeout = "player-idle-timeout=0";
$opPermissionLevel = "op-permission-level=4";
$levelType = "level-type=DEFAULT";
$networkThresh = "network-compression-threshold=256";
$maxWorldSize = "max-world-size=29999984";
$serverIP = "server-ip=";
$resourcePackHash = "resource-pack-hash=";
$whitelist = "white-list=false";
$maxBuildHeight = "max-build-height=256";
//prefixes for user file
$levelName = "level-name=";
$motd = "motd=";
$port = "server-port=";
$maxPlayers = "max-players=";
$viewDistance = "view-distance=";
$levelSeed = "level-seed=";
$pack = "resource-pack=";
//wrting to the file
$myfile = fopen("temp/tmp/server" . $id  . $ext , "w") or die("Unable to open file!");
//adding generated by Serve A Server
//fwrite($myfile, $generatedBy . "'r'n");
//$txt = isset($_POST["levelName"]) ? $levelname . $_POST["levelName"] . "'n" : '';
//fwrite($myfile, $txt);
//$txt = isset($_POST["messageOFTD"]) ? $motd . $_POST["messageOFTD"] . "'n" : '';
//fwrite($myfile, $txt);
//$txt = isset($_POST["port"]) ? $port . $_POST["port"] . "'n" : '';
//fwrite($myfile, $txt);
//$txt = isset($_POST["maxPlayers"]) ? $maxPlayers . $_POST["maxPlayers"] . "'n" : '';
//fwrite($myfile, $txt);
//$txt = isset($_POST["viewDistance"]) ? $viewDistance . $_POST["viewDistance"] . "'n" : '';
//fwrite($myfile, $txt);
//$txt = isset($_POST["levelSeed"]) ? $levelSeed . $_POST["levelSeed"] . "'n" : '';
//fwrite($myfile, $txt);
//$txt = isset($_POST["pack"]) ? $pack . $_POST["pack"] . "'n" : '';
//fwrite($myfile, $txt);
//adding the values created by the user (Note: There is an IF statement for each $_POST Variable).
fwrite($myfile, $spawnProtection . "'r'n");
fwrite($myfile, $maxTickTime . "'r'n");
fwrite($myfile, $genSettings . "'r'n");
if (isset($_POST["forceGamemode"])){
        $txt = "force-gamemode=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "force-gamemode=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["allowNether"])){
        $txt = "allow-nether=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "allow-nether=false" . "'n";
        fwrite($myfile, $txt);
    } 
switch($_POST['defaultGamemode']){
case 'SURVIVAL':
    $txt = "gamemode=0" . "'n";
    fwrite($myfile, $txt);
break;
case 'CREATIVE':
    $txt = "gamemode=1" . "'n";
    fwrite($myfile, $txt);    
break;
case 'ADVENTURE':
    $txt = "gamemode=2" . "'n";
    fwrite($myfile, $txt);    
break;
case 'SPECTATOR':
    $txt = "gamemode=3" . "'n";
    fwrite($myfile, $txt);  
break;
default:
    $txt = "SOMETHING WENT WRONG!" . "'n";
    fwrite($myfile, $txt);    
}
if (isset($_POST["enableQuery"])){
        $txt = "enable-query=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "enable-query=false" . "'n";
        fwrite($myfile, $txt);
    } 
fwrite($myfile, $playerIdleTimeout . "'r'n");
switch($_POST['difficulty']){
case '0':
    $txt = "difficulty=0" . "'n";
    fwrite($myfile, $txt);
break;
case '1':
    $txt = "difficulty=1" . "'n";
    fwrite($myfile, $txt);    
break;
case '2':
    $txt = "difficulty=2" . "'n";
    fwrite($myfile, $txt);    
break;
case '3':
    $txt = "difficulty=3" . "'n";
    fwrite($myfile, $txt);  
break;
default:
    $txt = "SOMETHING WENT WRONG!" . "'n";
    fwrite($myfile, $txt);    
}
if (isset($_POST["spawnMobs"])){
        $txt = "spawn-monsters=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "spawn-monsters=false" . "'n";
        fwrite($myfile, $txt);
    } 
fwrite($myfile, $opPermissionLevel . "'r'n");

fwrite($myfile, $resourcePackHash . "'r'n");
if (isset($_POST["announceAchievements"])){
        $txt = "announce-player-achievements=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "announce-player-achievements=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["enablePVP"])){
        $txt = "pvp=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "pvp=false" . "'n";
        fwrite($myfile, $txt);
    } 

if (isset($_POST["enableSnooper"])){
        $txt = "snooper-enabled=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "snooper-enabled=false" . "'n";
        fwrite($myfile, $txt);
    } 
fwrite($myfile, $levelType . "'r'n");
if (isset($_POST["hardcoreMode"])){
        $txt = "hardcore=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "hardcore=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["enableCommandBlock"])){
        $txt = "enable-command-block=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "enable-command-block=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["maxPlayers"])){
    if($_POST["maxPlayers"] != ""){
        $txt = $maxPlayers . $_POST["maxPlayers"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "max-players=20" . "'n";
        fwrite($myfile, $txt);
    } 
}
fwrite($myfile, $networkThresh . "'r'n");
fwrite($myfile, $maxWorldSize . "'r'n");
if (isset($_POST["port"])){
    if($_POST["port"] != ""){
        $txt = $port . $_POST["port"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "server-port=25565" . "'n";
        fwrite($myfile, $txt);
    } 
}
fwrite($myfile, $serverIP . "'r'n");
if (isset($_POST["spawnNPC"])){
        $txt = "spawn-npcs=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "spawn-npcs=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["allowFlight"])){
        $txt = "allow-flight=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "allow-flight=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["levelName"])){
    if($_POST["levelName"] != ""){
        $txt = $levelName . $_POST["levelName"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "level-name=NO_NAME_GIVEN" . "'n";
        fwrite($myfile, $txt);
    } 
}
if (isset($_POST["viewDistance"])){
    if($_POST["viewDistance"] != ""){
        $txt = $viewDistance . $_POST["viewDistance"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "view-distance=10" . "'n";
        fwrite($myfile, $txt);
    } 
}
if (isset($_POST["pack"])){
    if($_POST["pack"] != ""){
        $txt = $pack . $_POST["pack"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "resource-pack=" . "'n";
        fwrite($myfile, $txt);
    } 
}
if (isset($_POST["spawnAnimals"])){
        $txt = "spawn-animals=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "spawn-animals=false" . "'n";
        fwrite($myfile, $txt);
    } 
fwrite($myfile, $whitelist . "'r'n");
if (isset($_POST["generateStructures"])){
        $txt = "generate-structures=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "generate-structures=false" . "'n";
        fwrite($myfile, $txt);
    } 
if (isset($_POST["onlineMode"])){
        $txt = "online-mode=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "online-mode=false" . "'n";
        fwrite($myfile, $txt);
    } 
fwrite($myfile, $maxBuildHeight . "'r'n");
if (isset($_POST["levelSeed"])){
    if($_POST["levelSeed"] != ""){
        $txt = $levelSeed . $_POST["levelSeed"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "level-seed=" . "'n";
        fwrite($myfile, $txt);
    } 
}
if (isset($_POST["messageOFTD"])){
    if($_POST["messageOFTD"] != ""){
        $txt = $motd . $_POST["messageOFTD"] . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "motd=Server Props. file created with ServeAServer!" . "'n";
        fwrite($myfile, $txt);
    } 
}
if (isset($_POST["enableRCON"])){
        $txt = "enable-rcon=true" . "'n";
        fwrite($myfile, $txt);
    } else {
        $txt = "enable-rcon=false" . "'n";
        fwrite($myfile, $txt);
    } 
//close the operation
fclose($myfile);
//list files
$log_directory = 'temp/tmp/';
$results_array = array();
if (is_dir($log_directory))
{
        if ($handle = opendir($log_directory))
        {
                //Notice the parentheses I added:
                while(($file = readdir($handle)) !== FALSE)
                {
                        $results_array[] = $file;
                }
                closedir($handle);
        }
}
//Output findings -- Debug Purposes 
foreach($results_array as $value)
{
    echo $value . '<br />';
}

//this delets the file after all above is done..
//array_map('unlink', glob("temp/tmp/*.properties"));
?>

您需要在 httpdocs-dir 中创建文件以使其可下载。在我看来,您的文件是在目录"temp/tmp/"中创建的,它应该在您的 http 目录中。

因此,您可以使用

echo '<a href="temp/tmp/server'.$id.$ext.'">download</a>';

在 php 文件中的 fclose(( 之后的末尾。

[编辑]如果要强制下载而不是查看文件,则需要在 apache 上启用mod_headers:

以根用户身份登录:

# a2enmod headers
# /etc/init.d/apache2 reload

更改主机的 http.conf(名称和位置取决于 Linux 发行版和服务器配置(:

AllowOverride All

在下载目录中创建一个 .htaccess 文件:

<FilesMatch "'.(?i:txt)$">
      ForceType application/octet-stream
      Header set Content-Disposition attachment
</FilesMatch>

如您所见,强制下载文件而不是查看,对于没有经验的用户来说有点棘手。最好用这样的文本标记下载链接:

(要下载文件,请按鼠标右键 ->保存链接(

当然,您可以在下载目录中创建.htaccess,并希望mod_headers已启用,并且默认情况下将AllowOverpred设置为"全部"。请注意,.htaccess只是更改.txt文件。对于其他扩展,您需要对其进行调整。