dprnr5559
dprnr5559
2017-09-02 21:30

将else添加到rename()函数

已采纳

I'm writing a simple rename form that renames the folder name. It works fine, but if the file doesn't exist PHP gives me an error.

<form> 
    <input type="text"  value="folder name you want to rename">
    <input type="submit">
</form>

And this is my PHP code:

<?php
session_start();
$_SESSION['name'] = $_POST['name'];

rename("../folders/".$_POST['name']."","../renamed/new-name");
?>

The code works perfectly, but I want to add an if/else statement because when I run the script for a folder that does not exist, I get this error.

Does not exist

I want to remove the error, and simply output "doesn't exist".

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dtebrq0245 dtebrq0245 4年前

    You could always just use a simple if statement to check that rename() worked, since it returns a boolean (true, or false) value. Read more on PHP manual.

    So you could write something along these lines:

    if(rename("../folders/".$_POST['name']."","../renamed/new-name"))
    {
        echo "Folder renamed";
        // more code...
    }
    else
    {
        echo "Folder does not exist.";
        // more code...
    }
    
    点赞 评论 复制链接分享
  • duandangqin0559 duandangqin0559 4年前
    if (isset($_POST["name"]) && !empty($_POST["name"]) && file_exists("../folders/".$_POST['name'])) {
    $_SESSION['name'] = $_POST['name'];
    rename("../folders/".$_POST['name']."","../renamed/new-name")
    }
    else
    {
    echo "Folder does not exist.";
    //ToDo
    }
    

    Just another different simple algorithm.

    I rather prefer this algorithm if you need to make rename() more functional and complicated. And it validate the form text box at same time.

    For example, if you wish to generate the new name at server's side I would go for this solution.

    点赞 评论 复制链接分享
  • duanfu7994 duanfu7994 4年前

    Not sure how you're able to send the form data without any name attribute or how you're able to get the data using $_POST when there's no method attribute included in your form. By default, it would have been sending form data using GET method. I believe you're taking care of all these things.

    Now having said that, first check whether that particular directory exists or not, and then rename it accordingly or just prints a message directory doesn't exist if the directory user is trying to rename doesn't exist.

    if(file_exists("../folders/".$_POST['name'])){
        rename("../folders/".$_POST['name'],"../renamed/new-name");
    }else{
        echo "directory doesn't exist";
    }
    

    Here's the reference: http://php.net/manual/en/function.file-exists.php

    file_exists — Checks whether a file or directory exists

    点赞 评论 复制链接分享

相关推荐