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.
Related
I have a hosted website and i want to upload my images to image directory and link the image to mysql database .
What i did:
Creating form as :
<form method=POST align=center enctype="multipart/form-data">
<input type=file name=image>
Php code :
$uploaddir = 'images/';
// echo $uploaddir;
$target = "$uploaddir".basename($_FILES['image']['name']);
echo $target;
$image = $_FILES['image']['name'];
$sql="insert into News2(image_News2)
values($image)";
$res=mysqli_query($con,$sql);
copy($_FILES['tmp_name']['name'],$target,true);
What this code actually do is only inserting the image into the database not copying the image into the images folder.
What i searched for and found :
You shouldn't specify a http:// URL as $uploaddir but a path relative to the path where the php script is running from.
So i what i really wanted to do is :
1- Copying the image into image folder directory on website.
2- Linking the copied image to the database.
you're missing the name ïmage"
not:
copy($_FILES['tmp_name']['name'],$target,true);
but:
move_uploaded_file($_FILES['image']['tmp_name'], $target);
And maybe you should try the move first, before inserting it in the database, should that action fail (or filesize = 0) etc.
do check on both the file actions and the db actions, should they fail: rollback
extra:
is only 1 column present in your database table?
is it wise to use the uploaded file's name? Duplicates can happen.
I would after checking the file insert the original name into the database. Get the autoincrement id of that record. rename the file to ./1234.jpg
through the database you can then later use the original name. But this numbering might go too var for a simple application
PHP Code :
if (isset($_FILES['image']['name']) && $_FILES['image']['error']
== 0) {
$uploads_dir = '/uploads';
$temp_file = $_FILES['image']['tmp_name'];
$name = basename($_FILES["image"]["name"]);
if(move_uploaded_file($temp_file, "$uploads_dir/$name")){
//Fire Insert Query For Insert image name in your database
}
else
{
echo "Error !! , Your image not uploaded.";
}
}
?>
as per your given data you must close Form tag then give form action ="" attribute to specify url . and if your oprating system is linux then check folder permission in set or not , also check your database table if field name is set unique or not ?
then write below code in given url file
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
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().
I'm sure I'm doing something silly but I've checked and re-checked this. This is my photo uploader, meant to save the photo file itself to a folder (named "reccs"), and then save the name of the photo to a row in my DB. The DB part works perfectly, but my photo isn't showing up in the folder.
It displays no errors and appears to be working (I get the "success" message). Ack!
Code is below. Thanks for ANY insight.
$link = mysql_pconnect($host, $username, $password);
$db = mysql_select_db ($dbname);
$target = "reccs/";
$target = $target . basename($_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
mysql_query("UPDATE login SET recc = '$pic' WHERE username = '".$_SESSION['user']['username']."'");
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "The file has been uploaded, and your information has been added to the directory";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
try;
if(move_uploaded_file($pic, $target))
Depending on your server setup you may have to set $target to be an absolute path and not relative. At least it should be absolute to your home dir, so if reccs is a dir in your root site directory then set $target to /reccs/file.name.
The reason for this is that files are uploaded by defualt to /tmp, which is at the root (OS) level, not the hosted level, so paths relative to /tmp are generally meaningless.
saving photo with same name is very bad practice. I will suggest you to do below before uploading the foto.
extract name and extension.
now check that extension is valid or not. if valid then go further
first trim and then clear all multiple spaces with single spaces.
now lowercase filename and change all space with _ and append timestamp with filename.
remove all special characters ( ', " , \ etc )
now add filename with that extension .
then store into database
Should reccs have a forward slash in front of it? It would seem the mysql update query would be better inside the if statement , after you know the move_upload_file was successfull.
I have a file with 2 input fields one for file name (user will type) and the second one for choosing file what I want to upload the file to a directory with the name user typed.
down is the code I'm using guys please help me how to change the file name into what user typed.
<?php
$filename = $_POST["file"]
$upload = $_FILES['userfile'];
$target_path = "upload/";
$target_path .= $upload["name"];
$newname = "anything";
if(move_uploaded_file($upload["tmp_name"], $target_path))
{
echo "uploaded successfully";
}
?>
Change $target_path .= $upload["name"]; to something like $target_path .= $filename;.
edit: For the record, I have to say that letting people upload files (and choose the extension) to your web server raises some serious security concerns. I would suggest at least disabling the ability to execute scripts in your target folder.