Upload images to temporary image folder - php

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

Related

How to rename the uploaded files in PHP

extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
move_uploaded_file($file_tmp,"".$_POST['property_builder']."/".$_POST['property_city'].""."/".$_POST['property_location'].""."/".$_POST['property_type']."/".'Images-'.$_POST['property_name']."/".$file_name);
$content_to_write .= '<img src="Images-'.$_POST['property_name'].'/'.$file_name.'" alt="'.$file_name.'" title="'.$file_name.'" height="400" width="600">';
}
In the above code, I am unable to rename the uploaded files.. Please help me out as how to rename all the uploaded files by user...
User, just uploads 5 files, I want 5 text boxes asking for 5 filenames.. and save them accordingly.
You supposed to change following code
move_uploaded_file($file_tmp,"".$_POST['property_builder']."/".$_POST['property_city'].""."/".$_POST['property_location'].""."/".$_POST['property_type']."/".'Images-'.$_POST['property_name']."/".$file_name);
with
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = $_POST['filename']."."end($temp); // this filename is the name of field you have given in your text fields. If you have not given extension name you have to include that too.
// Make sure your path is currect where you're saving your file
move_uploaded_file($file_tmp,"./pathtomainimagefolder".$_POST['property_builder']."/".$_POST['property_city']."/".$_POST['property_location']."/".$_POST['property_type']."/".'Images-'.$_POST['property_name']."/".$newfilename);
Just make sure the file path. I just wrote smaple based on your path.

PHP letting the code add the uploader's last name to the image file he is uploading from a form

Got the server, got the domain, got the code, getting the images successfully, making the products for the customers from the image files they upload. Yay!
Problem: all my image names are image_0001 etc.
Customers can't rename image files from iPhones and do not care to from PCs.
So I was thinking about putting a short form on the upload page asking for customer's last name and having the PHP code attach that name to the image file(s) being uploaded.
If it's not possible, I'm sorry for the inconvenience.
You can rename files after they have been saved to your server, check out the PHP manual for the rename function - http://www.php.net/manual/en/function.rename.php, or just while you are moving them from the tmp directory, you can specify a different name for the uploaded file. See http://www.php.net/manual/en/function.move-uploaded-file.php
Be careful to include something in your code for dealing with naming conflicts.
This one might help :
$imagename = basename($_FILES['file']['name']);
$ext = pathinfo($imagename , PATHINFO_EXTENSION); //we want to change the file name but not the extension
$newImagename= $imageName.$username.'.'.$ext; //assuming you hold the username in $username
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$newImagename}"))
{
....
}

adding time to an uploaded file and database

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 photo uploader to MySQL and separate folder

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.

Saving a PDF file using PHP

I have a problem with saving PDF files to folders on my server. The code worked at one time and now it doesn't. What I want it to do is to check if someone is trying to upload a PDF when a form is submitted, and if there is a PDF in the file field it uploads it and then saves the path to the mysql database. Code is below:
if (!empty($_FILES['pdf'])){
$idir = "../files/PDF/"; //my directory file is supposed to be saved in
$randomd=rand(0000000,9999999); //creates a random number as filename
$domain = "http://".$_SERVER['HTTP_HOST'];
$file_ext = strrchr($_FILES['pdf']['name'], '.'); grabs file extension. my code checked if the file was a pdf a different way and neither seems to work.
$destination=$randomd.$file_ext; //new filename
if ($file_ext=='pdf') {
move_uploaded_file($_FILES['pdf']['tmp_name'], "$idir" . $destination);
$pdf= $domain."/files/PDF/".$destination; } else { echo("File type not supported.");
mysql_query("UPDATE tbl_listings SET pdf='$pdf' WHERE listing_id='$lid'");
}
The if not empty does not work and it always tries to upload a file, but when I check the folder nothing is in there and it doesnt update the mysql.
$_FILES['pdf'] will never be empty(when the form has been submitted), no matter if a file has been selected or not, it will always return an array.
Check $_FILES['pdf']['error'] , it will be 4 when no file has been uploaded.

Categories