Audio files to be stored into database - php

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

Related

How can I validate multiple files first and add the rest of the form data to the database only if they're valid?

I'm not very experienced in coding PHP and MySQL, and am therefore looking for help. I'd like to do the following:
I have a form where users enter their contact details and at the end of the form there is a multiple file upload button.
Now if they submit the form, the following should happen:
First, I wanna check if all of the uploaded files are valid (file types are ok), if this is true, then the contact details should be entered to table_X of db_Z.
Then, all files should be moved/uploaded to the server and in table_Y of db_Z the file name, the (let's call it) eventID and date and time of the upload should be inserted, whereas the eventID is a foreignkey of the ID of the entry of the contact details.
The code I have until now is close, but the final step is missing. It adds the contact details to the database regardless of the result of the validation of the files.
How can I change it, so that it only adds something to the database if all files are valid? And also that it adds the contact details only once to database regardless of how many files are being uploaded?
Thanks in advance
Here's my code:
<?php
if(isset($_POST['submit'])){
$obs_fname = filter_input(INPUT_POST, 'firstname');
$obs_lname = filter_input(INPUT_POST, 'lastname');
$obs_address = filter_input(INPUT_POST, 'adresse');
// Include the database configuration file
include_once 'dbConfig.php';
$query = "INSERT INTO bear (obs_fname, obs_lname, obs_address)
values ('$obs_fname','$obs_lname','$obs_address')";
$result=$db->query($query);
// verify results
if(!$result) {
$message = "ERROR SAVING POST : ".$db->error . "\n";
$db->close();
echo ($message);
return false;
}
/**
* get the last inster id of the Post
**/
$post_id = $db->insert_id;
echo "Post id=".$post_id ."<br>\n";
// File upload configuration
$targetDir = "uploads/";
$allowTypes = array('jpg','png','jpeg','gif');
if(isset($_FILES['files'])) {
foreach($_FILES['files']['name'] as $key => $name) {
$image_tmp = $_FILES['files']['tmp_name'][$key];
move_uploaded_file($image_tmp, './uploads/' . $name);
/**
* now insert the image with the post_id
**/
$query = "INSERT INTO images (eventID, file_name, uploaded_on)
VALUES ('$post_id', '$name', NOW())";
$result=$db->query($query);
// verify results
if(!$result) {
$message = "ERROR INSERT IMAGE : ".$db->error . "\n";
$db->close();
echo ($message);
return false;
}
}
}
header("Location: upload-complete.php");
}
You need to validate the MIME type on the server-side using mime_content_type() or using an image function that will return FALSE if it is not an image such getimagesize()
you gonna need a function like this + you need to validate the size $_FILES['files]['size] and the file extension $file_ext = strtolower(pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION))
function validate_images($image_tmp){
foreach($_FILES['files']['tmp_name'] as $key => $name) { // you need the tmp_name here and not "name" name is the one was when the file was in the client computer, After the form sent, the file will be in `/tmp` on the server and that is where php is accessing it.
$image_tmp = $_FILES['files']['tmp_name'][$key];
if(strpos(mime_content_type($image_tmp),"image")){
return true;
}else{
return false;
}
}
if(validate_images($image_tmp)){
// do the rest
}else{
die("no no no");
}
Also look here w3school image upload

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

add multiple pdf files to blobs usng 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!'; }

Insert and select from database

i've a problem with my query. The problem is that: the file is correctly loaded in the uploads folder. But not in the database with the content of the textarea.
i ve created this table into my database with:
CREATE TABLE dati(article VARCHAR(30), photo VARCHAR(30))
this is my code (pick from internet)
<?php
//This is the directory where images will be saved
$target = "../image/";
if(isset($_FILES['photo']['name'])) {
$target = $target . basename($_FILES['photo']['name']);
//This gets all the other information from the form
}
$article = (isset($_POST['article']));
$pic = (isset($_FILES['photo']['name']));
// Connects to your Database
//Writes the information to the database
if (isset($_FILES['photo']['name'])) if (isset($_POST['article'])) {
mysql_query("INSERT INTO nome_tabella (photo, article) VALUES ('{$_FILES['photo']['name']}', '{$_POST['article']}'");
}
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name']))
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename(isset($_FILES['uploadedfile']['name'])). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I tried several times, but does not insert data into the database. What's wrong?
This is the code for read the results
<?php
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM 'dati' (photo, article)") or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
echo "<div id='cover'>";
echo "<img src='http://localhost/chiedifilm/image/".$info['photo']. "'>";
echo "</div>";
echo "" .$info['article']. "";
echo "<hr>"; } ?>
It does not load the image name and the textarea tinymce.
Im sorry for my bad english, i don't speak it very well.
Check your code:
//Writes the information to the database
if (isset($_FILES['photo']['name'])) if (isset($_POST['article'])) {
mysql_query("**NSERT** INTO nome_tabella (photo, article) VALUES ('{$_FILES['photo']['name']}', '{$_POST['article']}'");
}
where's "I" on INSERT statement
regards

Restricting uploads to PDFs and MS Word files

I'm making a file uploader using PHP and want to restrict it to PDFs and Microsoft Word files. However, it's currently allowing uploads from all file types to the database. How can I restrict it to only allowing PDFs and Microsoft Word files?
Here is my code:
<?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 = mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("webproject", $dbLink) or die(mysql_error());
/* if(mysql_connect()) {
die("MySQL connection failed: ". mysql_error());
} */
# Gather all required data
$filename = mysql_real_escape_string($_FILES['uploaded_file']['name']);
$filemime = mysql_real_escape_string($_FILES['uploaded_file']['type'] == "application/pdf" || $_FILES["uploaded_file"]["type"] == "application/msword");
$size = $_FILES['uploaded_file']['size'];
$data = mysql_real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$subjects = $_POST['subjects'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
# Create the SQL query
$query = "
INSERT INTO file(
Filename, Filemime, Filesize, Filedata, subjects, name, email, phone, Created
)
VALUES (
'{$filename}', '{$filemime}', {$size}, '{$data}', '{$subjects}','{$name}','{$email}','{$phone}', NOW()
)";
# Execute the query
$result = mysql_query($query, $dbLink);
# Check if it was successfull
if ($result) {
echo "Success! Your file was successfully added!";
} else {
echo "Error! Failed to insert the file";
echo "<pre>" . mysql_error($dbLink) . "</pre>";
}
} else {
echo "Error!
An error accured while the file was being uploaded.
Error code: " . $_FILES['uploaded_file']['error'];
}
# Close the mysql connection
mysql_close($dbLink);
# Echo a link back to the mail page
echo "<p><a href='index.html'>Click here to go back home page!.</a></p>";
?>
I am not sure how your code actually works, but if you replace your second if at the top by this, the program will run only if the type is pdf or word, other files will cause this error: "Error! An error accured while the file was being uploaded. Error code: ". $_FILES['uploaded_file']['error'];" to occur
if($_FILES['uploaded_file']['error'] == 0 && ($_FILES['uploaded_file']['type']=='application/pdf' || $_FILES['uploaded_file']['type']=='application/msword' || $_FILES["uploaded_file"]["type"] == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'))
Your first if: if (isset($_FILES['uploaded_file'])) has no braces... that's not a very good practice.
Here is a extract from a function I sometimes use:
function CheckFile ($file){
$mimeTypes = array(
"application/pdf",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/excel",
"application/vnd.ms-excel",
"application/x-excel",
"application/x-msexcel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
$fileExtensions = array("pdf", "doc", "docx", "xls", "xlsx");
if (in_array($file['type'], $mimeTypes) &&
in_array(end(explode(".", $file["name"])), $fileExtensions)) {
return true;
}
}
Call it with CheckFile($_FILES['uploaded_file']) It will return true if the doc is a pdf word or excel file
Edit:
One way to use it would be like so:
if (!CheckFile($_FILES['uploaded_file'])){
?>
<p>Sorry, your file was not of the correct type</p>
<?php
exit();
}

Categories