在 PHP 中写入二进制文件


Write binary file in PHP

我写了一个PHP文件,它将在服务器中保存一个JPEG文件,部分代码如下:

    //create folder if folder not exist
if (!is_dir($save_path)){
    $old = umask(0);
    $flag = @mkdir($save_path,0777);
    umask($old); 
if(isset($flag)){
    $string = 'Folder Create Success!'."'n";
}else{
    $string= 'Folder Create Fail!'."'n";
}
echo $string;
}else{
   echo "Folder exist!!!!";
}

//write the content to the server
$base=$_REQUEST['image'];
$binary=base64_decode($base);
header('Content-Type: image/jpg; charset=utf-8');
if(!$file = fopen($path, 'wb')){
    echo 'Image upload Fail!'."'n";
    return;
}
else
{
    fwrite($file, $binary);
    fclose($file);
}

问题是当我运行代码时,如果文件夹不存在,它只会创建文件夹,但内容无法保存在文件夹中。错误消息是:

[2012 年 7 月 5 日星期四 16:59:06] [错误] [客户端 10.95.61.220] PHP 警告:fopen(/mnt/csis/upload/newphoto/others/12346_test/12346_test_2012-07-05_others_abc.jpg):无法打开流:第 57 行的/var/www/html/upload_image.php 中的权限被拒绝

但是,如果我再次运行代码,由于该文件夹是过去创建的,因此它可以正常工作。内容可以保存在文件夹中...

我做错了什么?我试图在网上找到答案,但仍然无法解决问题。

任何人都可以提供帮助,非常感谢!

我会尝试更改文件夹的创建以使用递归标志:

$flag = @mkdir($save_path . "/" . $file,0777,true);