Want to store and retrive data in MySQL on different pages - php

I'm handling a project and from long time that project is in the middle. The problem is : to store and retrive contents from MySQL database (locally in WAMP Server).
The brief overview about the project which inculdes the folowing steps:
1) Users can create account,
2) Upload files (whcih can be text(.rtf & .txt), images (.jpg & .png ), docs (.doc, .xls, .pptx, .pdf ) & videos (.avi & .mp4 ))
3) View those files and
4) Modify them.
So the concept is :
1) User logs-in or do sign-up,
2) He gets options the following options : Text, Images, Docs & Videos.
3) The user choose any option : which opens a new page where user can view his/her existing content in Thumbnail view with its name and
4) There's an option on top of everything to "Add new". Here we've two conditions:
If user clicks on existing, user can view it and delete the existing files. For example, if it's a video, user can play it by clicking on thumbnail.
If user clicks on "Add new", it takes user to another page where user can upload the respective content.
So, the problem is that no one in my team (we're in college, not in a company) knows the queries to store the file into database & after uploading it, retrieve the file's name and thumbnail (only in case of image & video otherwise, a default thumbnail) on previous page.
One of my team member tried to do it, but the uploaded file is shown in every user's account.
So I want to know how we can do it. I mean to say, specific programming code for both problems.
P.S.: If possible please let me know how to set restrictions(validations) of file choosing (like during uploading FB cover, it shows only IMAGES not ALL FILES).

This should help you. But be sure to clean this code from sql injections.
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("yourdbname") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO tbl_files (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}

// Connect to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("dbname") or die(mysql_error()) ;
// directory where images will be moved
$file=mktime()."_".$_FILES['files']['name'];
$target = "images/" . $file;
//This gets all the other information from the form
$description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['files']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file has been uploaded, and your information has been added to the directory";
//Writes the information to the database
mysql_query("INSERT INTO tbl_files (Filename,Description)
VALUES ('$file', '$description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading the file.";
}

Your question is much too broad. Here are some tips. Come back with more specific questions after you have tried things.
"User" management is a non-trivial task. You need admin page(s) to create new users, delete users, etc. A "end-user" should not be a MySQL "user"; there should be only one or two MySQL users ("app-user"). The PHP code will validate an "end-user", using your own tables for storing their names, passwords, etc. The PHP code will connect to mysql as the app-user.
Media files should be stored on disk as files. This allows the easy use of HTML code to display images (<img...>) or play videos.
Thumbnails -- The simple answer is to treat them like other media. (In one project, I stored them in the db and clumsily converted them to base64 for inclusion in <img...>.)
Thumbnails -- There may be a thumbnail in the "exif data". But I would not trust it to exist. Instead, I would use image* routines in PHP to create a thumbnail from an image. (I do not know how to deal with thumbnails of videos.)
PHP has functions for uploading media. It is a bit clumsy and contorted; study the manual.
PHP is picky (for good security reasons) about access to the filesystem. You will need to poke holes (see open_basedir) to allow access.
You will need to pass information from one page to another. Keep in mind that HTML pages are "stateless", so nothing from one page is implicitly available to the next. You may be able to put everything in the url (...?user=123&img=abc...). But there could be security considerations. Or you may need to get "cookies" involved.
"The user clicks..." -- You may need JavaScript starting with OnClick=DoSomeFunction(...). You may need AJAX, but it does not sound like it.
Otherwise, HTML, PHP, and MySQL can handle everything you need.
Those notes probably encompass several thousand lines of PHP, including a several dozen SQL queries. Divvy up the project among your team so that not everyone has to be come versed in every aspect. Suggested breakdown: User management; Media processing; Flow of pages (clicks, passing args, security, etc); Database abstraction layer.

Related

Is my PHP profile image code safe?

I am working for a paranoid client. The image uploader I've written must be able to 'survive' multiple penetration tests from some hired guys. Just for some background information: The images are for profile pictures only.
So, what I've got. I've got a HTML form to upload files, and the form can only be accessed by logged in users. The login system is safe, there's no worrying in that. Every user gets an unique user id, which is what I use to identify different users.
Whenever a file gets uploaded, I do the following checks on it:
The file must be larger than 128 bytes (stop ddossing)
The file must be smaller than 100 kb (the pictures will be displayed as 64x64 anyway)
Both of those checks are done with $_FILES["fileToUpload"]["size"]
The file's extension has to be '.png' (done with $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);)
The mime content must be "image/png" (done with mime_content_type($_FILES["fileToUpload"]["tmp_name"]))
The file will be renamed to $current_user->ID.".png"
All profile images are stored in /resources/img/profilepic/[userid].png
The file is moved with move_uploaded_file
Loading of the images is done within <img> tags. The code that gets the complete sentence (including the tags) is require'd in another .php file later.
So in short: The files are not named after the original but after [id].png. I haven't been able to find questions which address this too.
Is this bullet proof? Or is my current system just a nice challenge for someone willing to upload a web-shell? If there's a major vulnerability, how can I protect myself against it?

MLS RETS Server

I am downloading property images from MLS RETS server. When I am using GetObject method to download property images, sometimes Getobject method does not return success parameter then image does not download on local server. Is any solution on it?
Here is my code :
$photos = $rets->GetObject("Property", "Photo", $idata['propertymlsid'], "*", 0);
foreach ($photos as $photo)
{
$imgval="";
$imgval="{$photo['Content-ID']}-{$photo['Object-ID']}.jpg";
if ($photo['Success'] == true)
{
#file_put_contents("photos/{$photo['Content-ID']}-{$photo['Object-ID']}.jpg", $photo['Data']);
#mysql_query("insert into tableName (pro_mlsid,photos_name,image_date)values('".$idata['propertymlsid']."','".$imgval."','".date('Y-m-d h:i:s')."')");
}else
{
// in this section i want to download image. please suggest what to do here? . i have record for this image in database for but could not download it.
}
}
please go through the code. i want to download image in else section of above code.
Unfortunately the RETS protocol is not made for handling images and there are quite a few pitfalls with the whole process.
When an item in the database is deleted the RETS protocol is not able to reflect that change. For listings this is a very rare event but not for images. In either way there is just an error that the requested object has not been found or does not exist. In other words you have to assume that the object was deleted and you have to update your own records.
Images are updated frequently by agents and may have been deleted or changed order.
The image download process is twofold. a) you have to fetch the metadata record first and then b) the image itself with GetObject. However, in the meantime the agent may have deleted the image.
Depending on where you get the data from there may be a lot of latency between the two events. For instance, IDX is usually a secondary database versus access to a RETS feed from the MLS itself.
So bottom line your code is probably okay but the requested image has in fact been deleted since you requested the metadata for that image.
If your process overall works and there's an image missing it may well be gone for good. In theory you should run a second process and try to fetch the actual metadata. If there's no return as well you can safely assume that the record for this image is gone.
Some real estate boards allow agents to upload corrupt photos, or even invalid files (like PDFs). These mistakes made by realtors incorrectly update the RETS feed to indicate a valid photo exists, but when you attempt to download it, it fails.
Simply remove your else statement.

Access folder and select filename using PHP

I have written a code, where the user selects a profile picture and then the picture is stored in localhost/user/$username/photos/photo1.gif.
After that, I assigned the filename (photo1.gif) into a session variable so I can display it from all my php scripts. This is working just fine. I can display the picture in every php script by accessing this session variable.
The only problem I have is when I am trying to login from the login page: In the login page I connect to the database, retrieve email and password, check them and if they are OK I redirect the user to home.php. The problem is that the user's photo is not linked to the email so i cannot know the filename of the photo. The only thing I know for sure is the directory (because I can retrieve username from database as well).
Lets say that a user has uploaded 4 photos (photo1, photo2, photo3, photo4 - photo4 was uploaded last). It makes sense that he is currently using photo4 as my profile picture.
Is there a way for me to access that folder and retrieve the filename of the picture uploaded last?
Also, as a general question, what is better, store the photos(or files) in a database or server?
A few options:
It would be 'better' to create a photo table and store the user_id and the photo location in that table. Storing the actual photo in the table as a blob is not generally recommended.
Alternatively, to avoid more tables, you could rename the photos as
username_photo1.jpg
username_photo2.jpg
username_photo3.jpg
And then you can retrieve the largest of them.
Finally, another option is to get the file creation date of the photos in the directory and take the most recent photo.
see Getting the filenames of all files in a folder

show the contents of a folder in a web page

I'm trying to build an online storage site similar to Google drive. My code can upload files and save it in a specific given path. It also has code for creating files. the only thing is missing is showing the user "how many" or "which" files he/she uploaded in the specific path.
As shown in the Google drive image (in the link below), I want my code to look like similar to this, I want my user to see he/she's uploaded files in a serial on the web page. I'm not sure how to do it or whether it is possible in php or not, or if it is possible in php then which function is needed. I'm also not sure "what to type" in the Google search to find some examples of this type of coding. please tell me anything that will help me to start this part of my project.
http://www.google.com.bd/imgres?sa=X&biw=1024&bih=605&tbm=isch&tbnid=kSX8G1DGHuYiHM:&imgrefurl=http://www.zdnet.com/blog/networking/free-storage-for-you-google-drive-to-arrive-today/2293&docid=VGLnSQuNf4vGLM&imgurl=http://www.zdnet.com/i/story/62/58/002293/google-drive.png&w=1012&h=725&ei=JPCNUtj_FoKtrAfYkoHwCA&zoom=1&ved=1t:3588,r:12,s:0,i:122&iact=rc&page=2&tbnh=173&tbnw=241&start=8&ndsp=14&tx=182&ty=107
(I'm still working offline. I haven't yet launched it online.)
if you need any code from my existing work please tell me. I would love to upload my code.
---thanks.
So, you can just insert records in the Database while uploading (saving/moving files).
And example pseudocode, as you didn't provide any, would be:
if (checkForErrors()) {
// your error page for file exists, improper extension, and other violated constraints
} else {
move_uploaded_file($_FILES['file']['tmp_name'], 'your/path/here/' . $_FILES['file']['name']);
$db->query("INSERT INTO uploads (uploader, filename, uploaded_on) VALUES ('{$_SESSION['username']}', '{$_FILES['file']['name']}', NOW());");
}
// later you can just fetch the results for the current uploaded
$db->query("SELECT filename, uploaded_on FROM uploads WHERE uploader = '{$_SESSION['username']}';");
// under the row of filename will be stored the files that the current user has uploaded

Avatars : default image

i would like to make a simple avatar system for my users.
Usage is simple, every uploaded avatar image is named by user, for example:
<a>...$username.'.jpg';..</a>
so there is really no need for database.
When user is logged in, I just append the filetype to the already (from database) required username.
What concerns me here is the default image, which is used before user sets his own image. What is the best way to handle this? Is there a possiblity to create / copy default image to users avatar folder when user account is created?
I know that I can achieve this using database (default value) or checking if user image is set etc. but i want to keep it as simple as possible.
Thanks in advance :)
Very simple example of what the file would do. I'd suggest making it more secure of course.
$filename = $_GET["avatar"];
$path = 'path/to/your/files';
if (!file_exists($path.$filename.'.jpg'))
{
$filename = "default";
}
Header('Content-type: image/jpg');
readfile($path.$filename.'.jpg');
Check if the user's profile picture exists on the file system:
If it exists: display it.
If it doesn't: display the default image that is stored in one single place. No need to copy it.
I recommend saving the image name in the database, with its extension. People may want to upload a PNG or GIF image, rather than the classical JPG.
A simple example of what you are trying to do could be...
When a user registers in your site, he or she can upload or not an image.
Make a validation in the process to know if there is an image to be uploaded or not. Also, if there is a file in the process, validate it's extension (declare and array with the extensions you want to allow and compare with the incomming file).
If the user that is registering doesn't upload an image, in your server, create a default image for example: "users/default.jpg". So in the insert to you db, you must put in your imaginary "image_name" column: default and in your "image_ext" column: .jpg
If the user that is registering uploads an image in the process, in your server (when you validated the extension and size) create for example: "users/1.jpg" which "1" is the userid, and also in your insert to the db put in your imaginary "image_name" column: 1 and in your "image_ext" column: .jpg
To retrieve the image, just do a kind of select * from of the userid you want and just put in your html: echo "<img src='users/".$row['image_name'].$row['image_ext']."'/>"; and that's all, you are done.

Categories