将图像上传到服务器

时间:2013-04-15 06:26:29

标签: php html mysql

我想知道如何将图片上传到服务器目录?有人可以教我,因为我也想了解更多关于这件事。这是因为我不熟悉这种编码。我试图将图像上传到数据库,它的工作原理,但图像没有进入服务器。只有文件名插入数据库。请帮帮我 !谢谢

<?php
include("db.php");
 $id = $_POST['id'];
 $bg = trim($_POST['com_bg']);
 $ben = trim($_POST['com_benefit']);
 $rem = trim($_POST['com_remark']);
//print_r($_FILES);
//echo "<br><br>";
$name = $_FILES['file']['name'];
$format = substr($name, strpos($name, '.'), strlen($name) - 1);

//if they DID upload a file...
if($_FILES['file']['name'])
{
//Check if the file is JPEG,PNG or GIF image
if(($_FILES["file"]["type"] == "image/jpeg")||($_FILES["file"]["type"] == "image/png")||($_FILES["file"]["type"] == "image/gif"))
{
    $newname = dirname(__FILE__).'/upload/'.$name;
    //Check if the file with the same name is already exists on the server
    if (!file_exists($newname)) 
    {   
        //move it to where we want it to be
        move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" .        $_FILES["file"]["name"]);
        $sql= "UPDATE company SET com_logo='$name' WHERE com_idx = '$id'";
        $result = mysql_query($sql);
    }
    else 
    {
        header("Location: profile_2.php?note=1");
        //echo "Error: File ".$_FILES["file"]["name"]." already exists";
    }
}
else
{
    header("Location: profile_2.php?note=2");
    //echo 'wrong extension ';
}

}

$sql= "UPDATE company SET com_intro='$bg',com_description='',com_benefit='$ben',com_remark='$rem' WHERE com_idx = '$id'";
$result = mysql_query($sql);
header("Location: profile_2.php");

?>

2 个答案:

答案 0 :(得分:0)

首先,您应该在php.ini文件中检查这些配置

file_uploads
upload_max_filesize
max_input_time
memory_limit
max_execution_time
post_max_size

其次确保yopu想要上传文件的文件夹必须存在并且应该具有适当的权限

<强>建议 避免使用mysql_ *函数学习PDO或mysqli

答案 1 :(得分:0)

试试这个例子

 <header>
    <?php
    function UploadOne($fname)
    {
    $uploaddir = 'uploadedfiles/';
    if (is_uploaded_file($fname['tmp_name']))
    {
    $filname = basename($fname['name']);
    $uploadfile = $uploaddir . basename($fname['name']);
    if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
    $res = "File " . $filname . " was successfully uploaded and stored.<br>";
    else
    $res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
    }
    else
    $res = "File ".$fname['name']." failed to upload.";
    return ($res);
    }
    ?>
    </header>
    <body>
    <?php
    if ($_FILES['picture']['name'] != "")   
    {
    $res = UploadOne($_FILES['picture']);
    $filname = $_FILES['picture']['name'];
    echo ($res);
    }
    ?>
    <h1>UPLOADING FILES</h1>
    <form name="fupload" enctype="multipart/form-data" action="upfiles.php" method="post">
    <input type="file" name="picture" />
    <input type="submit" value="Submit" />
    </form>
    </body>