add multiple pdf files to blobs usng php - php

I have to migrate a legacy database up to MySQL using PHP. One of the components of the old system is a large (>1000) list of attached files (mostly .pdf, some are .doc/.docx).
I have so far done the following:
created mysql table, with a blob to contain the file (this method has
been chosen for valid reasons)
imported all the data except the attachments
extracted all the attachments into a folder, naming each file with a unique name
added and populated in mysql a column containing the unique name of the attachment
created a file containing the full names of all the attachments in the folder.
To add a single file is the only solution that I found in stack
But my requirement is to RECURSIVELY go through the list of filenames and find the matching row in mysql, then insert the file from the folder into the blob
example ...
I have a text file with entries like this (filename, date created, size)..
024048DE44C-RUE_MA.pdf,05/24/2013,80233
024048DE44C-RUE.pdf,06/21/2013,85151
... (1000 more)
I have a file with name 024048DE44C-RUE_MA.pdf in the folder
I have a row column filename containing 024048DE44C-RUE_MA.pdf in mysql database
I think the solution is something like this, but need help in the middle bit.
$myfile = fopen("filelist.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$attfile =fgets($myfile);
...upload the file
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'dbase');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `deal_attachment` (
`deal_att_name`, `deal_att_mime`, `deal_att_size`, `deal_att_content`, `deal_att_created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
}
fclose($myfile);

Why don't you just use mysql LOAD_FILE function if you already have a table with the filename?
UPDATE mytable SET blobdata=LOAD_FILE(concat("/path/to/", filename));
Your files need to be on your mysql server in order for it to work.
If your only problem is how to read the CSV file you can do:
list($filename,$date, $size)=explode(",", $attfile);

Adam's suggestion worked perfectly for me with the important proviso in Windows that file path must contain double backslashes (so you would construct it like this
$path = 'c:\\dir\\subdir\\' . trim($filename) ;.
Following snippet of code shows the call ..
$query = "UPDATE `attachments` SET `att_content`=LOAD_FILE('" .$path . "') WHERE `att_name` = '" . $filename ."'" ;
$result = mysqli_query($dbcon,$query) ;
// Check if it was successful (maybe add some more insurance by going back to the database to see if the file is there - it can be that no error was reported but LOAD_FILE didn't work (like if the path is invalid)
if (false === $result) {
echo mysqli_error($dbcon);
die ;
} else { echo 'Success! Your file was successfully added!'; }

Related

Excel file upload in PHP

I am trying to upload Excel file using PHP. I am using WAMP server and written PHP code to upload Excel file in the same folder.
I have saved an Excel file so if I upload the saved file then it works fine but if I try to upload another Excel file from different location i.e. from desktop it is showing that abc.xls is not readable.
My code is as follows:
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
require_once 'db.php';
if(isset($_POST["btnImport"]))
{
if(!empty($_FILES["excelFile"]["tmp_name"]))
{
$fileupload = $_FILES["excelFile"]["name"];
$fileName = explode(".",$_FILES["excelFile"]["name"]);
if($fileName[1]=="xls"||$fileName[1]=="xlsx")
{
$data = new Spreadsheet_Excel_Reader($fileupload);
//echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count(#$data->sheets[$i]['cells'])>0) // checking sheet not empty
{
// echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
#$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
#$data->sheets[$i]['cells'][$j][1];
#$ques = mysql_real_escape_string($data->sheets[$i]['cells'][$j][1]);
$opt1 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][2]);
$opt2 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][3]);
$opt3 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][4]);
#$opt4 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][5]);
#$correct = mysql_real_escape_string($data->sheets[$i]['cells'][$j][6]);
#$Level = mysql_real_escape_string($data->sheets[$i]['cells'][$j][7]);
#$Category = mysql_real_escape_string($data->sheets[$i]['cells'][$j][8]);
#$explain = mysql_real_escape_string($data->sheets[$i]['cells'][$j][9]);
$nithi = "INSERT INTO `question` VALUES (NULL,'".$ques."','".$opt1."','".$opt2."','".$opt3."','".$opt4."','".$correct."','".$Level."','".$Category."','".$explain."')";
if (!mysql_query($nithi,$connection))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
}
}
}}}}
if(#$result){
echo "Questions uploaded successfully";
}
?>
How can I upload Excel file from different location?
When a file is uploaded in PHP, it is put into temp folders.
In your code, there is no call for moving the uploaded file from temporary location into the desired one. Instead you are only checking $_FILES["excelFile"]["tmp_name"] and then directly using $_FILES["excelFile"]["name"] which is obviously incorrect.
Use move_uploaded_file() function to move the file, see the docs: http://php.net/move_uploaded_file

Uploading 1000 images via url using PHP

I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress

Audio files to be stored into database

Prior to this link:What is the best way to store media files on a database?
The answer stated:
(
Every system I know of that stores large numbers of big files stores them externally to the database. You store all of the queryable data for the file (title, artist, length, etc) in the database, along with a partial path to the file. When it's time to retrieve the file, you extract the file's path, prepend some file root (or URL) to it, and return that.
)
My questions are:
a)How do you store the partial path of the file?
b)How do you extract the file's path?
c)How do you prepend some file root and return it?
(Sorry I am very new and this bit I don't quite get. Any input or examples would be lovely.)
Btw, these are my codes for uploading the file, I just don't know the retrieve bit.
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '', 'spellingbee');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$location = $dbLink->real_escape_string($_FILES['uploaded_file']['location']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `location`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$location}', {$size}, '{$data}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
As far as I understand your problem you want to upload a audio file and save its name to database and then You want to retrieve it.
To do so just after your all validations (I am writing this code as if want to create a directory)
if(is_dir("audio")
{}
else
{mkdir("audio");}
$path = "http://www.domain.com/audio/".$_FILES['file']['name']; //prepend any path
// insert in database
move_uploaded_file($_FILES['file']['tmp_name'],$path);
And to retrive it:
just fetch the value of path from database.
Fetch From DB:
$q = mysql_query("select * from tablename");
while($r = mysql_fetch_array($q))
{
$path = $r['columnNameofPathinDatabase'];
echo $path;
}

Check if filename exists and

I wondered if there were a way to check if the filename exists and then to add a number after it, I know this - in a basic for is possible so if someone does it once it'll add 1 after it.
But how would you get it to check if someone has done it more than once? So the first time it would add a 1 then a 2 then a 3 and so on?
$title = $_POST['title'];
$content = $_POST['content'];
$compile = $title. "\r\n" .$content;
$content = $compile;
$path = "../data/" .md5($title). ".txt";
$fp = fopen($path,"wb");
fwrite($fp,$content);
fclose($fp);
$con=new mysqli("###","###_public","###","###");
if (!($stmt = $con->prepare("INSERT INTO `blog_posts` (`post_title`,`post_content`,`post_date`) VALUES (?,?,?)")) || !is_object($stmt)) {
die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $_POST['title'], $path, $_POST['date']);
if($stmt->execute()) {
echo "Successfully Posted";
} else {
echo "Unsuccessfully Posted";
}
$stmt->close();
Thanks for any help in advance
The general idea would be like this:
$basefilename = "somefile";
$filename = $basefilename;
$i = 0;
while(file_exists("../data/".$filename.".txt") $filename = $basefilename.(++$i);
Adapt as needed.
You can use something like this:
<?php
if(file_exists($filename)) { // check if the file exists in the first place
$i = 1;
while(file_exists($filename.$i)) { // check if the filename with the index exists. If so, increase the $i by 1 and try again
$i++;
}
rename($filename, $filename.$i); // rename the actual file
} else {
// file did not exist in the first place
}
Do not add strings at the end of file name - you would eventually
hit the OS file name length limit pretty soon. You would also fail
to recognize the last added number, when the string gets too big -
you'd have to parse all the numbers from the beginning.
Use glob() to search for a file name.
Parse the file names found for the number at the end and increment
that number.
Use rename() on the file name and check the return status to
avoid racing conditions.
Generally avoid that - use a database or any other system that
supports atomic operations.

error while downloading file in PHP

while downloading file im getting this error. specially pdf files.
and also program like download manger doesn't work on the downloading.
v?—x¢b(‏°®ه– ç‏zٍڈà÷µï½zTَکêùQïىxùSَ–‏jîآ·×Yï¹oف5KK÷¾oصتمح+¾¦œ:و†ƒloوnأ"گ ±Oّ•زـ¦§w8^uLٹé†-ئûpfچâ+أجشƒœر د؛-ںe•ؤ…¬RH¦ hْDyے#½=#'X'§¾ذXœtz”†رص0âLوٍ›“ء²{÷ڈے ½}f؛ِâB¦ک­ژ¯“كگyeطPeüpy,¥¼تِŒً•MR±wگCي¢âٹ‘¬}Fzى3¢e¾NAو^4è¬{j=¤ر³جسâل<¶–5Mz&#+­MYN1ُ¨Cںq)زêذش£M nj‍]T‡à*×h0ï3D¤­6غإQ.µg¬€ء¥w«ي|م+s“çكûmٍاe¯Œغ½وؤ~لà…½ں$/‡ھ(!·#‡]µظtحîز4»CQeں[°ظ5گ+è’ہù4›MQd™#ں|‡فژd؟×ë×F*xز‘ ¹’پ÷i·?ù×ـسخ½Mأ}ق¸َOe$ِ à'ظgءl”ƒ=fRن(rإهـPy¨2ش2ج:طQî49œt رA3kfفذ’){¯'7ذE=»نx¾ةLb|‘شاـ×s ل‡ةأجô‰—ثSùy¦y†uھc>‍ا/’›Zç9Vٍ·بش&¸ةq“s؟Yعlzگïگ_v¼ئ؟!؟د h=لّ’ےJ‏تْ…£ںبb÷U;Lآڑ›eڑƒ¨}كFپ ں›Uنvi>“]¤vçW†•Bڑˆˆ´!ج=¥4†é1حز ہحٹ‚é?“ل¢qع¬ ض4‹فلtڑgؤbوT§ةŒEچ8“س©#ôںآ‹EW9—ھr ‘8ژ§¦z$»±¸SW •¨xضث؛i›©سؤ™:pا¾YهسaکؤvC«صژkœچ “ژr\îW"Tùؤ'œ¥<غàû<§«،«ئ¶ —ًيFل¥رکً³ظ(WVتG{i®> stream xœه]ëڈeإqXXVثs1ث‚¹ ;†¹ôûAâDٹEت7[Hùùd'N"ضر’ے_JUWَُô¹sg¦w±#ygخمVWuWWW?~Oâ(صAàü‏ةف¯çüك»éد‡ےxW‏ë®4ٌ£;Hkز؟ے_ؤƒSر~ü÷»ےQ‍pئ¨C0؛{,=ƒ=َù‰ég”qً?™ïH،l{[:گJ›‏Uي¢؛ٍص,أوm)¤>ٌ6ف‍ے°R:^ùêî[ثٹ3¢¾m…ƒضŒ‡ إVeززF{{0BM‍ˆڑں°îùخVيئ[ّ هYPüG6Eàغn{[£´Rآدù•د¥·ءىفس¾¸÷‍‹~÷=ِ/
here is my php code for downloading
<?php
$company =$_GET['company'];
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = intval($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'sqldata', 'sqldata', 'balhaf');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT mime, name, size, data
FROM $company
WHERE id = $id";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
echo $row['data'];
}
else {
echo 'Error! No image exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
#mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>
use BLOB in MySQL to prevent that the data is changed due to the encoding (there might be encoding issues which produce your errors, saving as BLOB is binary safe)
related to Binary Data in MySQL
it may be better to store a link as file reference in the database instead of saving the actual content of the file and retrieve the files using file_get_contents and other related functions to get the mimetype (or finfo) ...
take a look at Trying to download Blob via PHP / MySQL and http://www.sitepoint.com/forums/showthread.php?693871-Problem-using-PHP-to-pull-binary-files-from-a-BLOB-field-in-MYSQL
Try flushing the output buffer immediately before you start setting headers with ob_end_clean, and then exiting immediately after the echo. Take a look at the section of the PHP book on Output Control.
The other possibility is that you are running out of memory when attempting to echo the data, and the error is getting obfuscated by all the preceding binary. Try splitting the binary in to smaller chunks (substr is binary safe), iterating over them and returning them to the output buffer.

Categories