我已尝试使用此代码上传文件。我正在尝试使用rand()+time()
制作目录并在其中上传文件。
代码出了什么问题?
if(!empty($_POST['title']) ) {
if(isset( $_FILES['img']['name'])
&& (
$_FILES['img']['type'] == "image/jpeg"
|| $_FILES['img']['type'] == "image/jpg"
)){
$temp = explode(".",$_FILES['img']['name']);
$newfilename = ($new_name = ( rand(1,99999) + time() ) ). '.' .end($temp);
mkdir($adr = '../news_img/'.$new_name);
move_uploaded_file( $_FILES['img']['tmp_name'] , $adr.'/'.$newfilename );
$connect = mysqli_connect('localhost' , 'root' , '' , 'project' );
$sql = "
insert into `news` values(
NULL,
'$_POST[title]' ,
'$_POST[text]' ,
'$_POST[date]' ,
'$_POST[cat]' ,
'$_POST[sub]' ,
'".$adr.'/'.$newfilename."',
'$_POST[pub]' ,
'$_POST[top_or_main]',
'$_POST[src]' )";
mysqli_query($connect , $sql );
}
}
?>
如果您认为代码没问题,其他部分可能会出现什么错误(例如html或phpmyadmin)
答案 0 :(得分:0)
您的代码存在很多问题。
最令人担忧的是SQL注入: http://en.wikipedia.org/wiki/SQL_injection
您要将两个整数一起添加,最终可能会出现重复目录。您希望将两个整数连接成一个字符串。我为你创建了一个功能。
/**
* Creates a new directory with a random name based on the time and a randomly
* generated number.
*
* @param string $baseDirectoryPath The base directory where the new directory will be created
* @return string The path to the new directory
*/
function createRandomDirctory($baseDirectoryPath) {
$randomDirectoryName = time() . '-' . rand(1, 99999);
$directoryPath = $baseDirectoryPath . DIRECTORY_SEPERATOR . $randomDirectoryName;
if (mkdir($directoryPath)) {
return $directoryPath;
}
throw new Exception('Directory was not created: ' . $directoryPath);
}
$baseDirectoryPath = '../news_img';
if (!empty($_POST['title'])) {
if (isset($_FILES['img']['name']) &&
$_FILES['img']['type'] == "image/jpeg" ||
$_FILES['img']['type'] == "image/jpg") {
$temp = explode(".", $_FILES['img']['name']);
$newFileName = end($temp);
$randomDirectory = createRandomDirctory($baseDirectoryPath);
$imageDestination = $randomDirectory . DIRECTORY_SEPARATOR . $newFileName;
move_uploaded_file($_FILES['img']['tmp_name'], $imageDestination);
$connect = mysqli_connect('localhost', 'root', '', 'project');
// always escape user input that goes into an SQL statement.
foreach($_POST as $key => $value) {
$_POSY[$key] = mysql_real_escape_string($value);
}
$sql = " insert into
`news`
values( NULL ,
'$_POST[title]' ,
'$_POST[text]' ,
'$_POST[date]' ,
'$_POST[cat]' ,
'$_POST[sub]' ,
'$imageDestination',
'$_POST[pub]' ,
'$_POST[top_or_main]',
'$_POST[src]' )";
mysqli_query($connect, $sql);
}
}