开发者

How can I get the contents of a document and upload to a Mysql blob field using PHP?

When I run this code, and $testpage is an alphameric string, it is uploaded perfectly. However, when $testpage is defined using file_get_contents(...), it does not upload at all.

<?
...
...

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;   
?> 

I understood from the PHP docs that file_get_contents(...) was the preferred way to convert files into a string that could be stored in a binary field. I am aware that ther开发者_Go百科e are some more security issues that I will have to deal with but first I just want to be able to do the raw upload and proceed from there. Is there any reason why this should not work and if so, what is the best way to do this? Or am I just missing something?

Thanks!

R


You need to properly escape the string.

$testpage = file_get_contents(..);
$testpage = mysql_real_escape_string($testpage);

mysql_query("INSERT INTO theTable(Description,Document) VALUES('PHP Webpage test','$testpage')");


I would really look into getting yourself a wrapper class for your database queries. There's a great one that I use at http://stefangabos.ro/php-libraries/zebra-database/.

Using that wrapper, the query would simply be:

$db->insert('theTable', array(
    'description' => $msg,
    'document' => $testpage
));

As the wrapper already escapes strings automatically, you reduce code while retaining security and functionality.


I suggest you use stream_get_contents instead of file_get_contents if you would like to actually request for a webpage and save it in MySQL:

<?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);
}
...
...

I think you can just alter the fopen and point it to your uploaded document (or file):

<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

$stream = fopen($_FILES['userfile']['tmp_name'], 'r');
// continue with the above code...

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜