[英]How can I get the contents of a document and upload to a Mysql blob field using PHP?
当我运行此代码时,$testpage 是一个字母字符串,它被完美上传。 但是,当使用 file_get_contents(...) 定义 $testpage 时,它根本不会上传。
<?
...
...
mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die("Unable to select database");
$testpage = file_get_contents('http://us3.php.net/manual/en/function.file-get-contents.php');
$testpage = mysql_real_escape_string($testpage);
mysql_query("INSERT INTO theTable(Description,Document) VALUES('PHP Webpage test','$testpage')");
mysql_close;
?>
我从 PHP 文档中了解到 file_get_contents(...) 是将文件转换为可以存储在二进制字段中的字符串的首选方法。 我知道还有一些我必须处理的安全问题,但首先我只想能够进行原始上传并从那里继续。 有什么理由为什么这不起作用,如果是这样,最好的方法是什么? 还是我只是错过了什么?
谢谢!
R
您需要正确转义字符串。
$testpage = file_get_contents(..);
$testpage = mysql_real_escape_string($testpage);
mysql_query("INSERT INTO theTable(Description,Document) VALUES('PHP Webpage test','$testpage')");
如果您想实际请求网页并将其保存在 MySQL 中,我建议您使用stream_get_contents
而不是file_get_contents
:
<?php
if ($stream = fopen('http://us3.php.net/manual/en/function.file-get-contents.php', 'r')) {
// get the entire page
$webpage = stream_get_contents($stream);
fclose($stream);
}
...
...
我认为您可以更改 fopen 并将其指向您上传的文档(或文件):
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$stream = fopen($_FILES['userfile']['tmp_name'], 'r');
// continue with the above code...
希望这可以帮助!
我真的会考虑为您的数据库查询提供一个包装器 class 。 我在http://stefangabos.ro/php-libraries/zebra-database/使用了一个很棒的。
使用该包装器,查询将只是:
$db->insert('theTable', array(
'description' => $msg,
'document' => $testpage
));
由于包装器已经自动转义字符串,您可以在保留安全性和功能的同时减少代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.