无法通过PHP将图像文件保存到服务器

时间:2015-10-04 23:13:36

标签: php html

那里。我对PHP不是很熟悉,但我一直负责修改一个非常重的PHP网站。部分功能是上传图像并将其显示在页面上。我已经获得了要写入数据库的图像名称以及当数据库字段不为空时要显示的图像HTML。但是,我无法弄清楚如何将图像保存到服务器。任何帮助将不胜感激!

HTML:

<form action="<?php echo $editFormAction; ?>" method="post" enctype="multipart/form-data" name="form1" id="form1">
    <label for="logo">Primary Logo Upload:</label> <input type="file" id="logo" name="logo" class="fullWidth" ><br>
    <input type="submit" value="Save Changes">
    <input type="hidden" name="logo" value="<?php echo $row_RecordsetCity['logo']; ?>" />
</form>

PHP:

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
    $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) {

    $location = $_FILES['logo'];
    $image = rand(1,2);
    $image = $image * time();
    $image = $image."-lp".".jpg";
    $filename = $image;
    $path="./_citylogo/logo/".$filename;
    $tempname=$location['tmp_name'];
    copy($tempname,$path);
    if ($location['name'] == "") {
        $_POST['logo'] = $_POST['logo'];
    } else {
       $_POST['logo'] = $image;
    }
}

2 个答案:

答案 0 :(得分:2)

$tempname= $location['tmp_name'];
$name = $location['tmp_name'];
$folder_directory = 'foldername/';
$check_folder_exists = is_dir($folder_directory);

if(!$check_folder_exists){
    mkdir($folder_directory , 0755, true);
//create folder if it doesn't exists.
//0755 - the image file can be access for the owner, while other can read and execute it.

}

$file_directory = $folder_directory.$name;
$move_temp_file = move_uploaded_file($tempname, $file_directory);

//note: This next part is optional.
if($move_temp_file){
    chmod($file_directory, 644);
//chmod() change the image file so it can't to executable by other in your server incase some hacker, upload a bad image.
}

答案 1 :(得分:0)

确保$path="./_citylogo/logo/".$filename;可写