How to populate a database as soon as user uploads a file - html

So Ive a code where in user uploads a video file from a certain directory.
-Now as soon as the user uploads the file, I want a table to be created with the name of the file as the name of table and exactly three columns named
ID(primary),type(varchar20), timestamp(float)
-Secondly, the page should show the table name created and there should be an option to delete the table if the user wants to.
My video upload and play code goes as below
<h1>HTML5 local video file player example</h1>
<div id="message_"></div>
<input type="file" accept="video/*"/>
<video controls autoplay></video>
<script>
(function localFileVideoPlayer() {
'use strict'
var URL = window.URL || window.webkitURL
var displayMessage = function (message, isError) {
var element = document.querySelector('#message_')
element.innerHTML = message
element.className = isError ? 'error' : 'info'
}
var playSelectedFile = function (event) {
var file = this.files[0]
var type = file.type
var videoNode = document.querySelector('video')
var canPlay = videoNode.canPlayType(type)
if (canPlay === '') canPlay = 'no'
var message = 'Can play type "' + type + '": ' + canPlay
var isError = canPlay === 'no'
displayMessage(message, isError)
if (isError) {
return
}
var fileURL = URL.createObjectURL(file)
videoNode.src = fileURL
}
var inputNode = document.querySelector('input')
inputNode.addEventListener('change', playSelectedFile, false)
})()
</script>

(Mercilessly stolen from php.net https://php.net/manual/en/features.file-upload.post-method.php)
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile) && $_FILES['userfile']['type'] === 'image/jpeg') {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
/*for creating table, which I don't recommend*/
$sql_query = "CREATE TABLE ".$_FILES['userfile']['name']." INT(6) AUTO_INCREMENT PRIMARY KEY,
type VARCHAR(20) NOT NULL,
timestamp FLOAT
)";
$mysqli->query($sql_query);
?>
/First half of the code, but something came up, I will be back in an hour.../
<?php
print '<form action="delete.php" method="post">
'.$_FILES['userfile']['name'].' <input type="submit" value="'.$_FILES['userfile']['name'].'" name="delete" />
</form>';
?>
<?php
$sql_query = "DROP TABLE ".$_POST['delete'];
$mysqli->query($sql_query);
?>
Instead of creating new tables for each file, I would recommend creating the table once, and insert the files like this:
<?php
$stmt = $mysqli->prepare("INSERT INTO table (name, type, timestamp) VALUES (?,?,?)");
$stmt->bind_param("ssf", $_FILES['userfile']['name'], $_FILES['userfile']['name'], strtotime(date("Y-m-d H:i:s")));
$stmt->execute();
?>
Similarly, if you want to delete:
<?php
$stmt = $mysqli->prepare("DELETE FROM table WHERE name = ?");
$stmt->bind_param("s",$_POST['delete']);
$stmt->execute();
?>
Or if you know the id, you can delete it by it instead (is safer, because multiple files can own the same name, but id must be unique).

Here is the big-picture overview of what you might wish to do.
1. Identifying who uploaded what
You may want each uploader to be able to request a list of his uploaded files and, optionally, to remove one or more. Or, you might want to be able to list all uploaded videos, grouping them by the uploader.
For this, you want a login system. Here is a post that links to a couple of videos that take you through that process.
2. Providing an upload system (client side)
You can write this from scratch, as you are doing, or you can use an already-invented wheel (rather than re-inventing it yourself). This jQuery plugin is awesome - looks world-class and works perfectly. I have used it on dozens of projects. Plus, it comes with example code for both server-side and client-side. Take a look.
3. Managing the uploaded files (server side)
On the server side, you might want to organize the uploaded files to some degree. There is no need to create much of a folder structure on the server since you have a database table to keep track of things, but at the least you might want to put them into a folder called "uploads" or "videos" or etc - just so that they are not stored in with the HTML files.
4. Adding each uploaded video to a MySQL (now called MariaDB) table
If you use the jQuery File Upload plugin, you will already have a file that handles that back-end receipt of the uploaded file. It is in this file that you write the code to also post the data into the database.
Look at this spot the docs for the jQuery file upload plugin. The plugin allows you to go fetch some additional data from the page (for example, you might have fields that ask the user for a tag, or a drop-down that lets users select a category) and you want to also insert those selections into the database when you upload the file. This is how you do that.
5. Getting the list of videos from the MySQL table and listing them on a webpage
This is a simple matter of querying the database, creating some HTML code in a PHP variable, and then later outputting the PHP variable containing that HTML at the appropriate place in the web page. Personally, I prefer to keep as much of my PHP as possible at the top of the page - create the strings containing any PHP output - and then echo the HTML code at the appropriate place. Keeps the file tidy and easy to read.
This youtube video will help you to grasp how to do that. Also see this post and this one.
Some notes to keep in mind:
a. You must name all of your web page files to end in .php instead of .html. There is almost no difference in how the pages will work - the sole difference is that any pages ending in .php can now process PHP code. Otherwise, they are identical. In fact, you can rename them now - try it - and they will work the same.
b. PHP code can be inserted anywhere in your web page -- you just place the PHP code between PHP_Start and PHP_END tags - it looks like this:
<?php
$myvar = 'Bob';
?>
c. PHP is very unforgiving about missing end-of-statement semi-colons. If you forget one, the PHP script will abort at that spot with no notification This makes it a bit tricky to work with PHP. See this answer for a couple of suggestions.
d. All PHP variables begin with a dollar sign. Weird, but true. Use the echo command to output PHP strings to the screen (for example, a PHP string containing HTML will display that HTML on the screen).
e. The PHP $_SESSION is super-useful. It is not difficult - it is just a way to store variables on the server. Very useful for things like remembering if someone has logged in, remembering data about that user that is stored in a MySQL table, etc.
Good luck with your project.

Related

Testing file extension for image linking

I am looking for a way to link an tag to a profile picture with the user's id as the file name. However, the extension of the image is dependent on the file extension when it was uploaded by the user.
My question is: how would one go about testing to see if a given image file name exists and cycle through the various file extensions for images.
For example:
Let's say and image is named: 1.jpg, but another is named 2.png.
I would like to implement the following in html:
<img src = "' + userId + '.jpg">
This will work for the furst user, but not the second. How would I go about testing the various image file extensions for the src?
Thanks
"File extensions" (indeed, anything regarding the name of the "file") are meaningless. Especially when it comes to HTTP requests. This URL could just as easily produce an image file:
http://www.example.com/foo.txt
Understand that there is no such thing as "files" in HTTP. There are requests and responses, each of which contain headers and content. A "file" is just a response with a content-disposition header. An "image" is a response with other headers which specify that it contains image data.
If you don't know the URL of the image, it could literally be anything.
the extension of the image is dependent on the file extension when it was uploaded by the user
In that case you should really be storing that information in your database. Whatever record holds the information for the user's profile would include the URL for the user's profile image. Use that data to build the img element.
Either store the data or enforce a convention. If you don't do either then you simply don't have that data.
Assuming you are using PHP & MySql store uploaded images like this
user_data/user_id/image.png
You can use php mkdir() function to create directory with user id
for example
mkdir("user_data/".$user_id,0777);
So your upload script be something like this
<?php
$fileName = $_FILES['uploadedFile']['name'];
if(!file_exists("user_data/".$user_id."/")){
mkdir("user_data/".$user_id,0777);
}
move_uploaded_file($_FILES['uploadedFile']['tmp_name'],user_data/".$user_id."/");
$conn = mysqli_connect($host,$user,$pass,$db_name);//Database connection
$sql = "INSERT INTO uploads(user_id,fileName) VALUES('$user_id','$_FILES['uploadedFile']['name']'";
$query = mysqli_query($conn,$sql) or die("Unable to update to database");
?>
Script for Retrieving Results
<?php
$conn = mysqli_connect($host,$user,$pass,$db_name);//Database connection
$sql = "SELECT * FROM uploads";
$query = mysqli_query($conn,$sql);
$data= mysqli_fetch_array($query);
?>
<img src"user_data/<?php echo "/".$user_id."/". $data['fileName']; ?>
There are some varialbes above like $user_id which you set & get from session variables

Bolt: saveContent updates values but doesn't actually save the record

I'm trying to create new content with:
// Get suggestions template and update with values
$content = $this->app['storage']->getEmptyContent('suggestions');
$content->values['title'] = $title;
$content->values['description'] = $description;
// Save to db
$save = $this->app['storage']->saveContent($content);
status is set as publish in data returned from getEmptyContent.
When I visit the backend, I can see that the save status is None. How can I actually create it so that it is published?.
This sounds like it could be a bug since as far as I can remember some value should make it through to status by default. One thing to check, in your contenttypes.yml file for suggestions you can also add a default_status eg:
default_status: publish
If you still have no luck then raise an issue on Github.

Is HTML5 localstorage appropriate to store input field values?

I have a question, on how to best store local values of some form fields.
In my website, users use the keypad to keep a tally count of items. They can enter a label for the items they count. The problem is that each user apply different labels for their needs - and, each time they visit the labels are blank.
My sites are running through site44.com, which does not allow the use of server side php. So, in my research, I think using HTML5 localstorage may allow a user to keep the label after the exit the site?
Is this a correct interpretation?
Can someone give me a guide if I have, say 3 inputs - with different ids - how to set up the script?
you can use the local storage like this :
var fn = document.getElementById("firstname").value;
localStorage.setItem("firstname", fn);
var ln = document.getElementById("lastname").value;
localStorage.setItem("lastname", ln);
var em = document.getElementById("email").value;
localStorage.setItem("email", em);
thus the clients browser will have these items set in their local storage.
Now if a user visits the website afterwards. you can check for the value of localStorage and find the items of your need.
Suppose on users' next visit you want to send him a greet message ( he has not logged in ofcourse ) you can use a script like this below:
var name = localStorage.getItem("firstname");
alert("Hello"+name);

Display image with wildcard in src

I have a series of photos on a server with a strict naming convention: "uniqueId-readableName.jpg". I do this because my website database currently only logs the uniqueID (and some unrelated info), but people occasionally need to look at the file server directly to browse the photos (via FTP) so a readable name is useful. For example
001456-War Horse.jpg
003295-Sunshine Daiseys.jpg
129084-Laboring at the farm 2013-08-11.jpg
Now, I'm fairly sure the best option would be to set up the database with a record of the full file names, but I just wanted to see if anyone had any ideas I may have missed. This question on SO is similar, but here I have strict naming conventions - not sure if that opens up any possibilities or not.
I'm applying this to img, but the same idea could be appled to any file extension (eg, download "789-My Homework.zip" or "123-Family vacation.zip").
As an example of what I'm looking for, in Windows Explorer you can do a file search for
0*.jpg
and all of the following files can be returned
001456-War Horse.jpg
003295-Sunshine Daiseys.jpg
029084-Laboring at the farm 2013-08-11.jpg
In my case the beginning part is always unique, so I'd like to use something like 001456-*.jpg and have it return 001456-War Horse.jpg.
Is there any way do this on a website?
<img src="001456-*.jpg" />
Although no such method exists, you can still do a server side scripting to acheive the functionality you require.
For example in PHP you could use in-built commands to browse a folder, select all files matching the criteria name as '001456-*.jpg' and then depending upon the number of records returned select the first filename and insert it into an IMG tag.
Here is a sample implementation in PHP:
$files = array();
$id = "001456";
$files = glob("id-*.jpg");
echo "<img src='$files[0]' />"; //Assuming one file is found for every unique ID.

How to store images/files in a folder input through forms and save address to sql DB?

I am designing a web site for a client and have a gallery page. I need to make an upload image option through the admin panel. I heard that storing the image directly in the sql DB is not efficient.
So what I want to know is that, how can I store the image I obtained from the user through the INPUT tag of HTML and store it in a folder say, UploadedImages and at the same time store the address of the upload image (URL) in my SQL DB?
Any answer with sample code will be of much use. Please advice me if there is much more efficient way. And sorry if this description seems to be lengthy. :)
And please guide me if the question is already answered. I dont find any post having a complete explanation about the process with the code..
thanks!
$target_path = "./upload/";
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) //Upload file to target path
{
$fileName = $_FILES['myfile']['name']; // Get Filename
$fileSize = $_FILES['myfile']['size']; // Get filesize
$fileType = $_FILES['myfile']['type']; // Get filetype
echo "The picture ". basename( $_FILES['myfile']['name']) . " was uploaded successfully.";} else{
echo "There was an error uploading the file, please try again!";
}
Something like this.
mysql_query("INSERT INTO `files`(`title`, `filename`, `size`, `type`, `categorie`) VALUES ('$_POST[title]', '$fileName', '$fileSize', '$fileType', '$_POST[type]');");
This would be excatly what you need. An upload for a file - And additional an insert for your database (filename, size and so on...).
edit: added else : Error message and comments
edit 2: donĀ“t forget:
<form action="" enctype="multipart/form-data" method="post">
And:
<input type="file" name="myfile">