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

时间:2014-12-22 12:36:07

标签: php html file rename

所以目前我有一个用户提交的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"));

?>

1 个答案:

答案 0 :(得分:1)

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

因此您可以使用

创建下载链接
echo '<a href="temp/tmp/server'.$id.$ext.'">download</a>';

在你的php文件中的fclose()之后的结尾。

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

登录AS ROOT:

# 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已经启用,默认情况下AllowOverride设置为“All”。 请注意,.htaccess只是更改.txt文件。对于其他扩展,您需要调整它。