douren4075 2014-12-09 19:28
浏览 65

文件存在时Php fopen错误

I have the following script to write a file that i grabbed from online.

$newfname = $data['transferPath'] . '/' . $data['filename'];
$file = fopen ($data['filePath'], "rb");

if(!$file) {
    throw new Exception('Unable to open file for reading ' . $file);
}

if($file) {
    $newf = fopen ($newfname, "wb");

    if(!$newf) {
        throw new Exception("Cant open file for writing");
    }

    if($newf) {
        while(!feof($file)) {
            fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
        }
    }
}

if($file) {
    fclose($file);
}

if($newf) {
    fclose($newf);
}

when i post the data and run this script I keep getting the exception for cant open file for writing because there already is a file but that name in the same directory. Im trying to overwrite the file with the new file any ideas what i can do. iv tried using the options for fopen using w and w+. I need to completely overwrite the file there if exists otherwise create the file.

  • 写回答

1条回答 默认 最新

  • doudui6756 2014-12-09 19:38
    关注

    Try using the a+ ending parameter to the fopen() function.

    Look here for a complete list of the possible parameters and what they do to find the right one for your purpose!

    If none of these satisfy your needs then you could do something like this:

    $fopen($data['filePath'], "r");
    if($file){
        unlink($data['filePath']);
    }
    

    Then after it deletes the file, if it's there, then just do another fopen with the w parameter.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度