PHP - Help On Upload And Download And Mysql
Hi guys,
I am trying to create a coding which allows users to upload and download files into mysql server, but I came across some errors. The coding itself works fine on the surface, but when I uploaded the file into mysql and download them, the contents of the downloaded file was different from the original file that was upload. One good example would be when I upload txt file or doc file. I was stuck on this for quite a few days without any leads. Here are the codes: index.html <form action="add_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> add_file.php <?php // 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', 'pwd', 'myTable'); 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 `file` ( `name`, `mime`, `size`, `data`, `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!'; } // Echo a link back to the main page echo '<p>Click <a href="index.html">here</a> to go back</p>'; ?> list_files.php <?php // Connect to the database $dbLink = new mysqli('localhost', 'root', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Query for a list of all existing files $sql = 'SELECT `id`, `name`, `mime`, `size`, `created` FROM `file`'; $result = $dbLink->query($sql); // Check if it was successfull if($result) { // Make sure there are some files in there if($result->num_rows == 0) { echo '<p>There are no files in the database</p>'; } else { // Print the top of a table echo '<table width="100%"> <tr> <td><b>Name</b></td> <td><b>Mime</b></td> <td><b>Size (bytes)</b></td> <td><b>Created</b></td> <td><b> </b></td> </tr>'; // Print each file while($row = $result->fetch_assoc()) { echo " <tr> <td>{$row['name']}</td> <td>{$row['mime']}</td> <td>{$row['size']}</td> <td>{$row['created']}</td> <td><a href='get_file.php?id={$row['id']}'>Download</a></td> </tr>"; } // Close table echo '</table>'; } // Free the result $result->free(); } else { echo 'Error! SQL query failed:'; echo "<pre>{$dbLink->error}</pre>"; } // Close the mysql connection $dbLink->close(); ?> get_file.php <?php // 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', 'root', 'pwd', 'myTable'); if(mysqli_connect_errno()) { die("MySQL connection failed: ". mysqli_connect_error()); } // Fetch the file information $query = " SELECT `mime`, `name`, `size`, `data` FROM `file` 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.'; } ?> I am not too sure where the error could be but I suspect that it could be somewhere at the add_file or get_file. Seriously hope someone could help me with this bug and thanks for the trouble. Regards Jasmine Similar TutorialsHello everyone I was working on a code i found on the internet to remotely download a file on my server but for some reason, nothing is been downloaded. You help is required. index.php <html> <head> <title>Remote Upload Page</title> </head> <body> <form method="post" action="download.php"> <p align="center"><b><font face="Tahoma">Enter Download URL :</font></b></p> <p align="center"> <input type="text" name="Link" size="50" dir="ltr"> <input type="submit" name="submit" value="Upload" dir="ltr"> </p> </body> </html> download.php <?php define('BUFSIZ', 4095); $url = $_post['Link']; $dir = 'files/'; $rfile = fopen($url, 'r'); $lfile = fopen($dir . basename($url), 'w'); fwrite($lfile, fread($rfile, BUFSIZ), BUFSIZ); fclose($rfile); fclose($lfile); echo '<p align="center"><b><font face="Tahoma" size="5" color="#339933">File Remote Download Complete !</font></b></p>'; ?> I hope anyone can fix this. Thanks in advance Hi I have to submit an assignment where a user can upload a file of the type "Application/octet" and the script should be able to split this file into multiples files of smaller sizes and display a page where the user can download the split parts. Also the files are not to stay on the webserver after they are downloaded. Any recommendation or lead or even code pieces would be appreciated. Regards, GuddooSk. create table mimi (mimiId int(11) not null, mimiBody varchar(255) ); <?php //connecting to database include_once ('conn.php'); $sql ="SELECT mimiId, mimiBody FROM mimi"; $result = mysqli_query($conn, $sql ); $mimi = mysqli_fetch_assoc($result); $mimiId ='<span>No: '.$mimi['mimiId'].'</span>'; $mimiBody ='<p class="leading text-justify">'.$mimi['mimiBody'].'</p>'; ?> //what is next? i want to download pdf or text document after clicking button or link how to do that Hiya guys After getting everything else working how I expected, I'm sort of struggling on the last step. Downloading I have an upload.php file that allows me to upload a file to Mysql, the fields available a upid - Primary id - Need to link this to the logged on user id name type size content The upload works perfectly Can anyone help with implmenting it to the profile.php (1st page after login) On profile page I have: Welcome "username" from Session Dynamic Table display his user id, username and password at the moment, this will be changed as not needed tho. I am using the sessions MM_Username to pass from the login The table for Login looks like: id - primary username password I assume that if I can copy the ID from login and put it in ID in Upload and add colums to dynamic table to show the upload file, will this make that file only available to logged in user? Cheers Hi, i have a table which shows some mysql data, every entry has a checkbox to select individual entries, now i want to be able to export those selected entries into a xml or txt file, i tried this: Code: [Select] <?php if($_POST['exporttxt']){ for($i=0;$i<count($_POST['checkbox']);$i++){ $export_id = $checkbox[$i]; $sql = "SELECT * FROM table WHERE id='$export_id'"; $result = mysql_query($sql);} $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n"; if($result->num_rows > 0) { while($myrow = $result->fetch_assoc()) { $output .= "\t<row>\n"; foreach($myrow as $_name => $_value) { $output .= "\t\t<$_name>$_value</$_name>\n"; } $output .= "\t</row>\n"; } } $output .= "</root>"; } header('content-type: text/xml'); header('content-disposition: attachment; filename=data_export.xml'); echo $output; exit; ?> but that doesn't seem to work. Any hints ? Hi Guys, I have been contacted by a client who wants me to develop an application which performs the following functionality: Lets say the domain name is xyz.com . We provide an email of our domain to the person who signup on our website for our services. Lets say the email that is given to the customer is email@xyz.com The client wants to built PHP application in which if an email is sent to email@xyz.com it gets downloaded and is stored in the MySql Database. After the download there is going to be a set of algorithms which will decided whether to forward this email to the client or not on his email address. I have no idea how to accomplish this functionality. Any suggestions would be appreciated. Thanks Sadan Masroor. I have a PHP code to download one mysql table to excel sheet.what i want to do is download 2 tables in to same excel sheet.those tables are should be in different excel worksheet.please help me. this code work fine.it's download one table
<?php ob_start(); session_start(); include('dbconnection.php'); $usr= $_SESSION['fname']; header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename=exported-data.csv'); $select_table=mysql_query("select * from regfarmer WHERE ffname='$usr'"); $rows = mysql_fetch_assoc($select_table); if ($rows) { getcsv(array_keys($rows)); } while($rows) { getcsv($rows); $rows = mysql_fetch_assoc($select_table); } function getcsv($no_of_field_names) { $separate = ''; foreach ($no_of_field_names as $field_name) { if (preg_match('/\\r|\\n|,|"/', $field_name)) { $field_name = '' . str_replace('', $field_name) . ''; } echo $separate . $field_name; $separate = ','; } echo "\r\n"; } ?> I have a webpage where the candidates can attach their resumes and send to the admin.These attachments are saved in the mysql db as blob datatype.In another webpage the admin needs to download all this resumes and see the content. How will i code for that. Hi, this is my first post:) pretty sure i will be posting here in the future. Anyway i am having trouble with a php script which downloads a file from a mysql database. This php script works for text files and should work for most files from what i understand. When downloading a text file, the whole file is downloaded from the server. When downloading an mp3 file, only 16kb are downloaded and the file does not play. When looking at the data in the database, it displays that the full file is there (correct amount of bytes, so there is nothing wrong with my upload php script). Does anyone have any suggestions as to what I can change to make this work? Code: [Select] <?php if(isset($_GET['id'])) { // if id is set then get the file with the id from database $link=mysql_connect('localhost', 'root', ''); @mysql_select_db('filemgr') or die ("<p>Could not connect to mysql!</p>"); $id = $_GET['id']; $query = "SELECT name, type, size, content " . "FROM upload WHERE id = '$id'"; $result = mysql_query($query) or die('Error, query failed'); list($name, $type, $size, $content) = mysql_fetch_array($result); header("Content-length: $size"); header("Content-type:$type"); header("Content-Disposition: attachment; filename=$name"); echo $content; mysql_close($link); exit; } ?> Hi all: I have been going nuts trying to get this to work. I have gone through many attempts based on internet searches and examples that simply do not work. I have files stored in my MySQL db. The files cna be of any type and are being displayed in a listed report. The files are hyperlinked and clickable, but here is the issue: When I click on a file in: http://development.products-and-services.ca/cms/test.php I get: http://development.products-and-services.ca/cms/test2.php?content=DHall_CV_webdev_eng.pdf as a blank page result. The objective is to get a file download alert or to see the file in the browser. Any ideas? Hey guys i have a problem, I have a form to upload 2 image files however sometimes i want to only upload the one file, but if i only upload one image, it tells me that it can't upload because there is no name for the second image. I tried fixing it with if (isset($fieldname2)) however i just realised that $feildname2 is always set so im not quite sure how to fix? Code: [Select] ($action == "add"){ $add = $_POST['add']; $reference = $_POST['reference']; $category = $_POST['category']; $sub_cat = $_POST['sub_cat']; $fieldname = 'file'; $fieldname2 = 'file2'; error_reporting(E_ALL); ini_set('display_errors',1); is_uploaded_file($_FILES[$fieldname]['tmp_name']); getimagesize($_FILES[$fieldname]['tmp_name']); if (isset($fieldname2)) { is_uploaded_file($_FILES[$fieldname2]['tmp_name']); getimagesize($_FILES[$fieldname2]['tmp_name']); } $now = time(); while(file_exists($uploadFilename = $uploadsDirectory.$_FILES[$fieldname]['name'])) { $now++; } if (isset($fieldname2)) { while(file_exists($uploadFilename2 = $uploadsDirectory.$_FILES[$fieldname2]['name'])) { $now++; } } move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename); if (isset($fieldname2)) { move_uploaded_file($_FILES[$fieldname2]['tmp_name'], $uploadFilename2); } $sqlname = $_FILES[$fieldname]['name']; if (isset($fieldname2)) { $sqlname2 = $_FILES[$fieldname2]['name']; } $id = mysql_insert_id(); $query = "INSERT INTO cakes (id, reference, category, sub_cat, image, image2) VALUES ('$id', '$reference', '$category', '$sub_cat','$sqlname','$sqlname2')"; $sql = mysql_query($query) or die (mysql_error()); } echo("<form name='add' method='post' enctype='multipart/form-data' action='?action=add'>"); echo("<input type='hidden' name='MAX_FILE_SIZE' value='3000000"); echo("<input type='hidden' name='?action=add'>"); echo("<table class=main cellspacing=0 cellpadding=2 width=60%>"); echo("<tr><td>Reference: </td><td align='right'><input type='text' size=50 name='reference' value='$reference'></td></tr>"); echo("<tr><td>Category: </td><td align='center'><select name='category'><option>Occasional</option><option>Special</option><option>Figures</option><option>Novelty</option><option>Wedding</option></SELECT></td></tr>"); echo("<tr><td>Sub Category: </td><td align='center'><select name='sub_cat'><option></option><option>Birthday</option><option>Anniversary</option><option>Christmas</option><option>Christening</option><option>Valentine</option><option>Mothers Day</option><option>Fathers Day</option><option>Easter</option></select></td></tr>"); echo("<tr><td>Cake Image: </td><td align='center'><input id='file' type='file' name='file'></td></tr>"); echo("<tr><td>Cake Image 2: </td><td align='center'><input id='file2' type='file' name='file2'></td></tr>"); echo("Before uploading an image please resize the image to 290px x 218px"); echo("<tr><td></td><td><div align='right'><input type='Submit'></div></td></tr>"); echo("</table>"); Hey guys! I'm not that good with PHP, and I really need to finish this script. I'm having a hard time finding the problem..it keeps saying Error, query failed and I've also checked the database info, connectivity info and even tried a connection and database selection verification to see if that was working. Is there any other error you guys can find in the script that may be causing the message? Edit: The files I want to be able to upload should be pdf's, txts, docs, etc. Would that be possible with this script? Thanks!! Code: [Select] <form method="post" enctype="multipart/form-data"> <table width="350" border="0" cellpadding="1" cellspacing="1" class="box"> <tr> <td width="246"> <input type="hidden" name="MAX_FILE_SIZE" value="104857600"></td> <td width="80"> </td> </tr> </table> <p>Archivo: <input name="userfile" type="file" id="userfile" /> </p> <p>Nomb <label for="name"></label> <input type="text" name="nombrelista" id="nombrelista" /> </p> <p>Password (para luego borrar si necesario): <input type="text" name="pass" id="pass" /> </p> <p> <input name="upload" type="submit" class="box" id="upload" value=" Upload " /> </p> <?php if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0) { $fileName = $_FILES['userfile']['name']; $tmpName = $_FILES['userfile']['tmp_name']; $fileSize = $_FILES['userfile']['size']; $fileType = $_FILES['userfile']['type']; $filePass = $_POST['pass']; $nombreLista = $_POST['nombrelista']; $fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp); $host_db = "localhost"; $user_db = "melkien_rudesa"; $pass_db = "jorlan2407"; $base_db = "melkien_rudesa"; $link = mysql_connect($host_db, $user_db, $pass_db); if (!$link) { die('Could not connect: ' . mysql_error()); mysql_close($link); } mysql_select_db($base_db, $link) or die(mysql_error()); if(!get_magic_quotes_gpc()) { $fileName = addslashes($fileName); } $query = "INSERT INTO 'upload'('nombrelista', 'name', 'pass', 'size', 'type', 'content' ) VALUES ('$nombreLista', $fileName', '$filePass', $fileSize', '$fileType', '$content')"; mysql_query($query) or die('Error, query failed'); echo "<br>File $fileName uploaded<br>"; mysql_close($link); } ?> </form> Hi all, creating a MYSQL, PHP & XHTML site designed to support local rugby clubs. Just putting the final touches to the functionality now so thanks for your help so far. I would like to provide site administrators with the ability to assign photos to a members profile when initially registering their account, I have no experience of dealing with what presumably will be a function that will upload a photo to a location and then linking it some how to data in the database. Thanks for your help, Tom Hi, I'm not sure if this is the right forum to post this question, but I'll still post it. I'm a newbie programmer, have 1 year experience of php, mysql and html and know how to make a basic website, but I've never actually uploaded the already written code on the internet.So my question is, if you use vertrigo serv and have folders full of php files, what do you do after getting a domain? I read that dreamweaver does that for you, but i also read that it is a closed source software with limitations if you get the free version.The other choice is using FileZilla(which I don't fully understand yet ) i presume.
Hi Guys, I am trying to use a script that is available on the net to upload an image into a mysql using BLOB. However it wont upload it keep getting Warning: fread() [function.fread]: Length parameter must be greater than 0 in /home/theacidf/public_html/attendance/upload.php on line 17 Here is the code... <?php // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","theacidf_admin","password")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("theacidf_attendanc"); // Insert any new image into database if ($_REQUEST[completed] == 1) { move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($image) < 149000) { mysql_query ("insert into pix (title, imgdata) values (\"". $_REQUEST[whatsit]. "\", \"". $image. "\")"); } else { $errmsg = "Too large!"; } } // Find out about latest image $gotten = @mysql_query("select * from pix order by pid desc limit 1"); if ($row = @mysql_fetch_assoc($gotten)) { $title = htmlspecialchars($row[title]); $bytes = $row[imgdata]; } else { $errmsg = "There is no image in the database yet"; $title = "no database image available"; // Put up a picture of our training centre $instr = fopen("../images/logo_png.png","rb"); $bytes = fread($instr,filesize("../images/logo_png.png")); } // If this is the image request, send out the image if ($_REQUEST[gim] == 1) { header("Content-type: image/jpeg"); print $bytes; exit (); } ?> <html><head> <title>Upload an image to a database</title> <body bgcolor=white><h2>Here's the latest picture</h2> <font color=red><?= $errmsg ?></font> <center><img src=?gim=1><br> <?= $title ?></center> <hr> <h2>Please upload a new picture and title</h2> <form enctype=multipart/form-data method=post> <input type=hidden name=MAX_FILE_SIZE value=150000> <input type=hidden name=completed value=1> Please choose an image to upload: <input type=file name=imagefile><br> Please enter the title of that pictu <input name=whatsit><br> then: <input type=submit></form><br> <hr> </body> </html> Why wont it run properly? Thanks in advance... S Hey everyone ... This should be a pretty easy question for someone who is used to using fgetcsv: I have a script that needs to import a csv file into a mysql table ... I keep getting stuck in a loop that only ends when the script hits the 30 second timeout I have set on the server ... It never actually inserts a record, and it never spits out a message indicating and error ... Can someone help figure out why I get caught in this loop? Here's the code: Code: [Select] function import_csv() { if(isset($_POST['submit_csv'])) { $filename=$_POST['filename']; $handle = fopen("$filename", "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT INTO `{mydatabase}`.`{my table}` (`name`, `qrl`, `begin`) VALUES ('$data[0]','$data[1]','$data[2]')"; mysql_query($import) or die(mysql_error()); } fclose($handle); print "Import done"; } else { print "<form action='results.php' method='post'><input type='file' name='filename'><br /><input type='submit' value='submit' name='submit_csv' /></form>"; } } Hi All I am trying to upload a csv file to a database using php html form however, the results shows none of the data passsing through to the database and it produces 1000's of empty fields here is the form Code: [Select] form action="lib/import.php" method="post" enctype="multipart/form-data"> Type file name to import: <input type="file" name="filename" size="20"><br /> <input type="submit" name="submit" value="submit"></form> and here is the passing info Code: [Select] $file = $_FILES['filename']; $sqlstatement="LOAD DATA INFILE '$file' into TABLE shop FIELDS TERMINATED BY ',' (id, merchant_name, product_name, description, category_name, Affiliate_deep_link, Affiliate_image_url, price)" ; mysql_query($sqlstatement); echo "it is done!"; can anyone help please?
Basically I would like to place a link on my website and have the user download a file, but rather than just right clicking and choosing save target as, the link must be clicked, on the next page the file is fetched and then the client can download the file. How would I go about setting this up please? Hello freaks! Im new to this forum, but im not all that new to PHP and MySQL. Although there's been some years since the last time I used it, so don't go all freaky on me if I dont do this right Let's go on-topic: Im in progress of making an internal web-page for me and my colleagues to make things a bit easier for us. I am making an database of our different projects, and I need some help with the input form - as I need to upload an image to the server, and store the path in the MySQL database. In my input form, I need to store information from text fields, and I need to upload an image to the server and store the path in the database. Before I can even start to code this (although I have coded the input forum without the upload), I need to know what would be the best way to do this. I guess there are several ways.. What would the expert do (That's you right?)? Should I have the information input, and image upload in the same form, or should I make a second form (maybe on a different page) for the upload? Is it necessary with two tables, one for the info and one for the image path, and then tie them together with the imageID, or is it fine to use just one table? Any thoughts would be appreciated! <!-- TechThat --> |