简体   繁体   English

如何在 php 中创建文件夹并将图像保存在我的服务器上?

[英]How can a create a folder and save a image on my server in php?

Below I have left my code.下面我留下了我的代码。 It currently works in my development environment (localhost), but when I push the changes to my live server it seems like my php doesn't create the folder/file.它目前在我的开发环境(本地主机)中工作,但是当我将更改推送到我的实时服务器时,我的 php 似乎没有创建文件夹/文件。

public static function saveImage($image, $name, $path = '')
{
    $img_data = explode(',', $image);
    $mime = explode(';', $img_data[0]);
    $data = $img_data[1];
    $extension = explode('/', $mime[0])[1];
    if(!file_exists('../public/media/img/' . $path)){
        mkdir('../public/media/img/' . $path, 0755);
        echo('Test1');
    }
    echo('test2');
    file_put_contents('../public/media/img/' . $path . $name . '.' . $extension, base64_decode($data));
    return 'media/img/' . $path . $name . '.' . $extension;
}

Locally it will hit echo('test1') the first time, then it will only hit echo('test2').在本地它会第一次击中 echo('test1'),然后它只会击中 echo('test2')。 When its on the server it always hits the echo('test1')当它在服务器上时,它总是会遇到 echo('test1')

By default mkdir is not create a path recursively.默认情况下, mkdir 不会递归地创建路径。 An example if on your server you dont have a ../public/media folder, mkdir returns false and dont create a path.例如,如果您的服务器上没有 ../public/media 文件夹,则 mkdir 返回 false 并且不创建路径。 To solve this pass a third parameter to mkdir as true:为了解决这个问题,将第三个参数传递给 mkdir 为 true:

mkdir('../public/media/img/' . $path, 0755, true);

Do yourself a favour and use absolute pathes...帮自己一个忙并使用绝对路径...

You can use the constant __DIR__ to evaluate the folder in which the script actually resides.您可以使用常量__DIR__来评估脚本实际驻留的文件夹。 Relative pathes are calculated from the current working directory, which can be different than __DIR__相对路径是从当前工作目录计算的,可以不同于__DIR__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM