为什么这个php文件上传验证脚本不起作用?

时间:2010-09-20 10:32:48

标签: php

亲爱的朋友们,这是一个简单上传文件并将文件名插入数据库的脚本,为什么这不起作用?它只是上传文件并在验证后将文件名发送到db。请帮忙

<?php

//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];

//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
    return true;
}else{
    $form_error= "Upload file was not supported<br />";
    header('Location: apply.php?form_error=' .urlencode($form_error));
}


//file validation ends

//upload dir for pics
$uploaddir = './uploads/';


//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);


//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);



//upload the file now
    move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);

// $photo value is goin to db
$photo = $upload_filename;

4 个答案:

答案 0 :(得分:3)

function send_error($error = 'Unknown error accured')
{
    header('Location: apply.php?form_error=' .urlencode($error));
    exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part

$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()

//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}

//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
    send_error("Upload Directory Error");
}    

//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);

if(!file_exists($uploadfile ))
{
    send_error("File already exists!");
}

//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);

//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
    send_error('Upload Failed, cannot move file!');
}

// $photo value is goin to db
$photo = $upload_filename;

这是一个清理版本给你的,给你一个去看看你是否有任何错误

答案 1 :(得分:0)

您也可以使用此代码找到文件的扩展名。

$tmp = end(explode('.', $_FILES['photo']['name']));

现在$tmp获得了文件的扩展名。

答案 2 :(得分:0)

为什么不使用PHP的内置函数从文件名中提取扩展名?

$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);

如果文件扩展名有效,那么您将从函数返回而不做任何进一步的操作,如果它无效则您正在设置标题,但代码逻辑将继续进行文件处理

答案 3 :(得分:0)

你盲目地认为文件上传成功了,但是它失败的原因很多,这就是PHP在$ _FILES数组中提供['error']的原因:

if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
    // uploaded properly, handle it here...
} else {
    die("File upload error, code #" . $_FILES['photo']['error']);
}

错误代码为defined here