上传.txt文件并将内容插入数据库

时间:2011-03-20 03:53:33

标签: php mysql database text text-files

我正在尝试获取文本文件的内容,验证是否有60,000个字符或更少,并将其插入数据库。如果有超过60,000个字符,则应将其截断。

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:3)

<?php

// db connection here

// set path of uploaded file
$path = "./".basename($_FILES['filename']['name']); 

// move file to current directory
move_uploaded_file($_FILES['filename']['tmp_name'], $path)) {

// get file contents
$data = file_get_contents($path, NULL, NULL, 0, 60000);

// run the query
@mysql_query("INSERT INTO table (column) VALUES ('".$data."')");

// delete the file
unlink($path);

?>
<form enctype="multipart/form-data" action="" method="POST">
  <input name="filename" type="file" /><br />
  <input type="submit" value="upload file" />
</form>

答案 1 :(得分:1)

您实际上不需要先检查长度。截断可以隐含地完成:

$content = file_get_contents("asciiart.txt");
$content = substr($content, 0, 60000);

这是有效的,因为substr只会在字符串真正更长的情况下切断字符串。否则它会保留它。数据库插入应该没有问题:

$pdo->prepare("INSERT INTO textfiles (content) VALUES (?)")
    ->execute(array($content));

答案 2 :(得分:1)

很抱歉,如果您在我的iPad上遇到语法错误。

<?php
$txt = $_FILES['files'];
$dbTxt = mysql_real_escape_string($txt);
if((!strlen($txt) =< 60000) && ($txt['type'] == "text/plain")) {
    die("Error here");
}
// no need for else as txt above 60000 have been locked away
move_uploaded_file($txt['temp_name'], 'tmp/'.$_server['remote_addr']);
$contents = file_get_contents('tmp/'.$_server['remote_addr']);
mysql_query("INSERT INTO txtUpload(text, ip) VALUES ($contents, $_server['remote_addr']");


$myFile = ''tmp/'.$_server['remote_addr'];
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
Unlink($myFile);