Basically I have written a script to allow the user in the back end to upload pictures for the gallery. The script is supposed to upload the file to the server and then post the file name and info into the database.
It always uploads the file to the server without fail, however for some reason it only posts it to the database occasionally. Sometimes it works fine but 8 times out of 10 it uploads the file and thats it, the script is as follows.
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$caption=$_POST['caption'];
$pic=($_FILES['photo']['name']);
$live=$_POST['live'];
//Connecting to the database
require_once('../Connections/tim.php');
//Writes the information to the database
mysql_query("INSERT INTO `gallery` VALUES ('$name', '$caption', '$pic', '$live')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded successfully, press back to upload more";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
That's probably because of the sql injection hole you have: If a caption (or any other posted field) contains for example a ', it will break your query.
You should dump the mysql_* functions and switch to prepared statements with PDO or mysqli. And always add error handling.
You really should read something on SQL Injection and you should use PDO or mysqli (as jeroen) suggested.
But debugging at your situation could be done by this:
mysql_query("INSERT INTO `gallery` VALUES ('$name', '$caption', '$pic', '$live')") ;
if( mysql_errno() != 0){
// mysql error
// note: message like this should never appear to user, should be only stored in log
echo "Mysql error: " . htmlspecialchars( mysql_error());
die();
}
And you have to escape your database inputs at least by mysql_real_escape_string().
Related
I have a code that lets a person upload multiple images through a form.
Problem is, the images upload fine on to the server but not sure how to get the images to be sent into the database.
PHP:
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $targetscreenshots.$name))
$count++; // Number of successfully uploaded file
}
Where do I put the following code?
{
mysql_query("INSERT into Colleges (`files`) VALUES ('$files')"); // inserting data if file is moved
echo "Your screenshots have been uploaded successfully!"
}
This is my own code which i am using in my script.
<?php
$upath="../images/";
//uploads is the name of file array that is being uploaded.
foreach ($_FILES['uploads']['name'] as $key=>$file) {
$target = $upath.$file;
$path=substr($target,3);
// echo $path; THIS CAN BE STORED DIRECTLY TO THE DATABASE
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die();
mysql_query(**YOUR INSERT QUERY HERE. IT WONT BE EXECUTED IF IMAGE IS NOT UPLOADED PROPERLY.**)or die(mysql_error());
}
?>
I read your comment and so i gave this answer... Kindly correct me if i have misinterpreted your question.
You are missing code that is responsible for database modification, I suggest you read some tutorials like this one.
I haven't tested it, but at least it looks like it involves all the steps required.
$files = $_FILES["files"]["tmp_name"][$f]
Just Insert the file path or name in the DB
it gives me an error whenever i try to store the video into the database..i have here a code that can store video into a folder and only save id_no and video_name from database,i want all 5 fields to be stored into my database...can anyone help me with my codes please
<?php session_start();?>
<?php
include("session/DBConnection.php");
include("session/session.php");
$error = "";
?>
<?php
$user = $_SESSION['log']['username'];
$query = mysql_query("SELECT * FROM members WHERE username = '$user'") or die (mysql_error());
$display = mysql_fetch_array($query);
if(isset($_POST['upload'])){
$mem_id = $display['member_id'];
$stat = "just uploaded a video.";
$date = date("m/d/Y");
$qry = "INSERT INTO updates SET member_id='$mem_id', status='$stat', date='$date'";
$result = mysql_query($qry);
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=video.php\">";
}
}
?>
<?php
if(isset($_POST['video']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
else{
move_uploaded_file($_FILES["userfile"]["tmp_name"],"video_uplaod/" . $_FILES["userfile"]["name"]);
$user = $_SESSION['log']['username'];
$today = strtotime(date("Y-m-d H:i:s"));
$location="video_upload/" . $_FILES["userfile"]["name"];
$video_name=$_POST['video_name'];
$sql = "INSERT INTO tbl_video SET username='$user', video='$location', video_name='$image_name', date_created='$today'";
echo "File $fileName uploaded";
}
header("video.php");
?>
Your INSERT statement is wrong,
INSERT INTO updates (member_id, status, date) VALUES('$mem_id','$stat','$date')
should be the right statement, as commented by Mike.
However, you have 3 big problems in your code:
1) You're using deprecated functions.
Seriously, stop using mysql_ functions, they're deprecated, they are no longer supported any more by PHP, and they may go away anytime, and when that happens your code will break, and you'll be in a hell of trouble. Use mysqli or PDO instead.
2) Your code is vulnerable to SQL Injection.
You're not sanitizing user input, addslashes is not good enough to prevent SQL injection into your query, if you use mysqli or PDO you'll be able to use prepared statements, so that your code will no longer vulnerable to SQL Injection (it doesn't mean that you shouldn't sanitize user input anyway).
3) Your code may be vulnerable to a file upload attack.
You really trust your users, do you?
What If I'm supposed to upload a video file, but instead of that I
upload a php file that copies your whole web directory, zips it, and
send it to my email so that I can see your source code, view your
database credentials, and open a backdoor to your server and do
whatever I wish with it?
When uploading files you shouldn't preserve the original filename,
you shouldn't save the file "as is", you must process that file and
make sure that you're handling a video file... DO NOT rely on file
extension, because I can upload "myfunnyvideo.avi.php" and your file
extension will pass, because it contains ".avi", and apache will run
that file because it contains php.
You shouldn't save the files in a folder that can be guessed by an
attacker, try to make that as obscure as possible... it's quite
obvious to see if my file was uploaded to uploads/ video_uploads/
folder.
Whatever folder you chose to upload the files to, make sure that
apache cannot run any script inside of that folder... otherwise, if a
malicious user guesses the upload directory, he could potentially run
any php script he wants.
EDIT
INSERT INTO updates SET member_id = ".$mem_id
is correct syntax, here's proof for those who doesn't believe it:
http://sqlfiddle.com/#!2/df90b8/2/0
How do I get files to upload online? This works well locally, but I cannot get the file to upload online to my cpanel server. I cannot see the path in my database, and the file is not uploaded into the researches file.
Here is my code:
if($name=="") echo "Enter the Research Title.<br/>";
else{
$uploadfile = basename($_FILES['imageupload']['name']);
$fileTmpLoc = $_FILES["imageupload"]["tmp_name"];
$moveResult = move_uploaded_file($fileTmpLoc, "researches/".$uploadfile);
$path = $uploadfile.".pdf";
$sql = mysql_query("INSERT INTO researches (name, link, date) VALUES ('$name', '$path', '$date')");
echo "Research Uploaded successfully.<br/>";
echo "<meta http-equiv='refresh' content='2, url=researches.php' >";
}
}
?>
I hope "researches" is a DB in which you want to INSERT files every time you needed. If that is not allowing to upload (INSERT) files to the DB, Make sure that the DB user is having necessary privileges to perform the action.
Anyway I don't see anything regarding DB user. You simply give all privileges to the corresponding DB user for the DB researches.
I am working with adding a file upload system to my website and I cannot seem to get the file links to match up with the file name that is generated. I am adding a time function onto the front of the file name to make it unique (it generates a number based on the time). It does do this, but for some reason, that unique name is not saved in the database. Could someone help me figure this out?
//This is the directory where images will be saved
$target = "files/";
$target = $target. time(). basename( $_FILES['photo']['name']);
echo $target;
//postThis gets all the other information from the form
$tfid=$_POST['tfid'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$hca=$_POST['hca'];
$file=($_FILES['photo']['name']);
//Writes the information to the pic table
mysql_query("INSERT INTO pic
(tfid, file)
VALUES ('$tfid', '$file')")
or die(mysql_error());
ECHO "<strong>pic table has been saved.<br></strong>";
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "<strong>The file has been uploaded</strong>";
}
else {
//Gives an error if its not
echo "<strong>Sorry, there was a problem uploading your file.</strong>";
}
echo '<br>';
require 'insertbuttons.php';
I see what was going on now. Sorry about the comments. You'll want to save the $target variable in your database. The posted variables won't match the target. So, where you have $file in your SQL statement, you'll probably want $target instead. That should give you the name of the file, but without the extension it looks like.
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('Could Not Connect:'.mysql_error());
}
mysql_select_db("tcs",$con);
$upload_to = "./uploadedfiles/";
move_uploaded_file(
$_FILES["filename"]["tmp_name"],
$upload_to . "/" . $_FILES["file"]["name"]
);
$sql="insert into employee values ('$_POST[username]','$_FILES[filename][name]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Employee Uploaded File"."$_FILES[file][name]"; //showing uploaded file name
?>
But there are three problems:
$sql="insert into employee values('$_POST[username]','$_FILES[filename][name]')";
By '$_FILES[filename][name]' this command file name is not saving in database.
And if I try $sql="insert into employee values ('username....','$_FILES["filename"]["name"]')" then a syntax error is displayed.
How do I send file name also in database? Please write or edit above code.
How do I add username id with this file so that it can be downloaded in the future?
If I try the same file name from another location to store in the database (uploaded folder), then the file is still the same (only one copy after 2 times of uploading the same file name but from different locations).
How to download file if user wants to download it? How server will know that this file name belongs to this user? Please tell me the code for this purpose.
Basically you store images in a folder but in the database, you store only the file names of uploaded pics. Here is how to upload the files.
To store images in our DB, you've got to make the field BLOB instead of VARCHAR.