I am trying to upload an image to the server (with a path in mysql table) twice through php with different names. One version of the image as "xxxx.png" and the other version of the image as "xxxxt.png".
My php is:
<?php
if ($_FILES['photo']) {
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
} else {
echo "Error uploading new image - please check the format and size";
}
}
?>
The above code inserts the image into the mysql database and uploads the file to the server correctly.
I am however trying to upload the same image twice with a different naming convention on a "thumbnail" version. The slideshow script in my html only recognises the thumbnails if there are named with a "t" at the end of the filenames hence my problem.
I have been advised to look at the php copy() function to achieve this but am incredibly unclear as to how to incorporate such a function into my existing code.
Happy to provide the html or any other info if required.
Any help much appreciated. I did have another thread attempting to find out the same thing but I wasn't very clear!
Thanks
JD
If I correctly understand you, you do not need to upload this file twice. You already have this file on your server. So you should copy it (optionally do some transitions to make it more like a thumbnail) on your server's hard drive and update database.
Your code should like similar to this:
<?php
if($_FILES['photo'])
{
$target_dir = "images/properties/";
$upload_file_name = basename( $_FILES['photo']['name']);
$upload_file_ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . $upload_file_name . '.' . $upload_file_ext;
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.' . $upload_file_ext);
$target_thumb = $target_dir . $upload_file_name . 't.' . $upload_file_ext;
$target_thumb_sql = $target_dir . mysql_real_escape_string($upload_file_name . 't.' . $upload_file_ext);
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_file_sql' )");
echo "The new image has been added successfully";
if (copy($target_file, $target_thumb))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_thumb_sql' )");
echo "The new thumb image has been added successfully";
} else
{
echo "Error copying thumb file";
}
} else
{
echo "Error uploading new image - please check the format and size";
}
}
Again, the idea is that you do not need to upload file twice in a row. All you need to do is just copy it on server.
As you've been advised you should use copy(). I didn't fully test this but give it a try:
<?php
if ($_FILES['photo'])
{
$target = "images/properties/";
$ext = array_pop(explode('.', $_FILES['photo']['name']));
$copy = $target . basename($_FILES['photo']['name'], '.' . $ext) . 't.' . $ext;
$target = $target . basename($_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
copy($target, $copy);
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
}
else
{
echo "Error uploading new image - please check the format and size";
}
}
?>
Related
I'm trying to upload a file but I always get an error:
Notice: Undefined index: file_pdf in C:\xampp\htdocs\FYP2\site_admin\pentadbiran\upload.php on line 10
The example of my code get data from a form and upload to my database for the information given, such as file_reference, file_name, file_location and file_pdf.
But the problem is, the code runs well but does not update on file_pdf column in table. But the file upload into target folder is working.
if (isset($_POST['submit'])) {
$file_reference = $_POST['file_reference'];
$file_name = $_POST['file_name'];
$file_location = $_POST['file_location'];
$file_pdf = $_POST['file_pdf'];
if ($_FILES['file_pdf']['error'] == UPLOAD_ERR_OK)
{
$ext = strtolower(pathinfo($_FILES['file_pdf']['name'],PATHINFO_EXTENSION));
switch ($ext)
{
case'pdf':
break;
default:
throw new InvalidFileTypeException($ext);
}
$targetfolder = "pdf/";
$targetfolder = $targetfolder . basename($_FILES['file_pdf']['name']);
if (move_uploaded_file($_FILES['file_pdf']['tmp_name'], $targetfolder)) {
echo "The file " . basename($_FILES['file_pdf']['name']) . " is uploaded";
} else {
echo "Problem uploading file";
}
$sql = "INSERT INTO file (file_reference,file_name,file_location,file_pdf)
VALUES ('$file_reference','$file_name','$file_location','$file_pdf')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
The code is run but on my database the file_pdf does not update.Why is this?
The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.
$_FILES['userfile']['name'] The original name of the file on the client machine.
$_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] The error code associated with this file upload.
Change this...
$file_pdf = $_POST['file_pdf'];
to
$file_pdf = $_FILES['file_pdf']['name'];
I have a simple piece of code for uploading the files in php/mysql and it works well.
$target = "uploads/clients/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
$insertSQL = sprintf("INSERT INTO clients (img, `cname`) VALUES (%s, %s)",
GetSQLValueString($pic, "text"),
GetSQLValueString($_POST['cname'], "text"));
mysql_select_db($database_thebest, $thebest);
$Result1 = mysql_query($insertSQL, $thebest) or die(mysql_error());
Now what I want is to rename the filename if that filename already exists and then insert the renamed filename to the database
Thanks for your reply
Try this...
$upload_dir = "uploads/clients/";
$target = $upload_dir . basename( $_FILES['photo']['name']);
while(file_exists($target)){
$new = time().rand();
$target = $upload_dir . '_' . $new . '_' . basename( $_FILES['photo']['name']);
}
// rest of the code now...
$pic= $new . ($_FILES['photo']['name']);
You can do it by many ways.
Method 1
Check file_exists() before save to the server :
if (file_exists("../img/imageDirectory/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
// Others insert statements here...
}
Method 2
Use microtime() to generate unique name for each file :
$temp = explode(".",$_FILES["file"]["name"]);
$newfilename = substr(microtime(), 2, 7) . '.' .end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename;
mysql_* functions are deprecated. Do not use them any more.
Try to use PDO or mysqli.
Run a SELECT query checking to see if the name exists. If it does not, INSERT it. So, select all from your table where the name = your file name. If numrows > 0 you change the name.
Actually why don't you just use the auto increment value as the name and store whatever you want to call it in a separate column. Then you'll know each name will be different and you won't have crazy long urls or file names.
First you must check table, that filename already exists or not.
select * from client where cname="filename";
if filename exist, you can must change filename .
I have a code. But move_uploaded_file is not working.
This is my code below:
is there any way to upload all types of with one field like Image/Video?
<?php
if(isset($_POST['save_news']))
{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$location="news/" . $_FILES["image"]["name"];
$vfile=$_FILES['video']['tmp_name'];
$vid= addslashes(file_get_contents($_FILES['video']['tmp_name']));
$video_name= addslashes($_FILES['video']['name']);
$video ="news/" . $_FILES['video']['name'];
$q = mysql_query("INSERT INTO news(video,image) VALUES('$video',
'$location')");
if(!$q)
{
echo mysql_error();
}
else
{
move_uploaded_file($_FILES["video"]["tmp_name"],"../news/" . $_FILES["video"]["name"]);
move_uploaded_file($_FILES["image"]["tmp_name"],"../news/" . $_FILES["image"]["name"]);
$_SESSION['mass_added']= 'echo"you are logged in"';
echo "<script>window.location = 'manage_news.php?user_type=admin'</script>";
}
}
?>
You need to check the errors to find out why. Do this by looking at $_FILES['video']['error'].
My guess would be that if you're uploading videos, their filesize is too large. You can change the maximum upload file size in php.ini with `upload_max_filesize=..." (see here).
I am trying to build a script to upload and rename an image to a folder and store the path in my sql db.
Here is where I am at: The file get uploaded both to the folder and the pathname to the db but I cannot figure out how to rename the filename. Ideally I would like to make the filename unique so I don't duplicates.
<?php
//preparing the patch to copy the uploaded file
$target_path = "upload/";
//adding the name of the file, finishing the path
$target_path = $target_path . basename( $_FILES['picture']['name']);
//moving the file to the folder
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
//getting input from the form
$name = $_POST['name'];
$description = $_POST['description'];
//preparing the query to insert the values
$query = "INSERT INTO complete_table (name, description, picture) VALUES ('$name', '$description', '". $target_path ."')";
//opening connection to db
$link = mysql_connect('localhost', 'root', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//selecting a db
mysql_select_db("wcs_venues", $link) or die(mysql_error());
//running the query
$result = mysql_query($query) or die (mysql_error());
//closing the connection
mysql_close($link);
?>
I am new with all this and I am really trying but after looking at many tutorial and answered questions on Stack-overflow, I realized I needed help. Thank you in advance for helping this newbie.
Well, this is where you set the name of the file being saved:
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
In this case, you're building the file name in the variable $target_path. Just change that to something else. What you change it to is up to you. For example, if you don't care about the name of the file and just want it to always be unique, you could create a GUID or a Unique ID and use that as the file name. Something like:
$target_path = "upload/";
$target_path = $target_path . uniqid();
Note that this would essentially throw away the existing name of the file and replace it entirely. If you want to keep the original name, such as for display purposes on the web page, you can store that in the database as well.
First get the file extension:
$file_extension = strrchr($uploaded_file_name, ".");
Then rename the uploaded file with a unique id + file extension
$uploaded_file_name = uniqid() . $file_extension;
Example:
TIP: Save the original file name and other information in a database.
First get the extension with pathinfo()
Then create your unique name:
$name = 'myname'.uniqid();
Then rename your file.
$target_path = $target_path . $name.$ext);
move_upload_file takes the second parameters $destination, its where you are inserting the target_path ( where your file is going to be saved with that given name ).
I tried uploading a picture to a directory in my server with the code below. However, when i run it, I get this error:
Warning: move_uploaded_file(images/) [function.move-uploaded-file]: failed to open stream: Is a directory in /home/a2943534/public_html/add.php on line 24
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/php7yEkDe' to 'images/' in /home/a2943534/public_html/add.php on line 24
What am I missing here, please?
<?php
include_once("connect.php");
?>
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['title']);
//This gets all the other information from the form
$title=$_POST['title'];
$name=$_POST['name'];
$describe=$_POST['describe'];
$pic=($_FILES['photo']['title']);
$url=$_POST['url'];
$country=$_POST['country'];
$endDate=$_POST['endDate'];
//Writes the information to the database
mysql_query("INSERT INTO `authors` VALUES ('$title', '$name', '$describe', '$pic', '$url', '$country', '$endDate')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
$result = "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
$result = "Sorry, there was a problem uploading your file.";
}
?>
<?php
// if the form has been submitted, display result
if (isset($result)) {
echo "<p><strong>$result</strong></p>";
}
?>
rather than writing
$target = $target . basename( $_FILES['photo']['title']);
you should write
$target = $target . basename( $_FILES['photo']['name']);
i think there is nothing like $_FILES['photo']['title']..
I think you make a mistake with
$target = $target . basename( $_FILES['photo']['title']);
Which should be
$target = $target . basename( $_FILES['photo']['name']);
This because title does not exists within the $_FILES['photo']
Also this error states it:
Unable to move '/tmp/php7yEkDe' to 'images/' in /home/a2943534/public_html/add.php on line 24
The to images/ does not contain your filename.
the error is obvious and self-explanatory.
the second parameter have to be a filename, not directory.
Apart from the SQL injection issue which seems to be present in every single PHP question that features MySQL here on SO, you should start debugging.
You're getting a pretty clear error on which line and what function call causes the error. Look the error up on Google, read the manual for the functions you're using.
Long story short: you should create two variables, print them before your function call, and figure out what's wrong.
<?php
$source = $_FILES['photo']['tmp_name'];
$target = "images/" . basename( $_FILES['photo']['title']);
echo "Moving '$source' to '$target'";
move_uploaded_file($source, $target);
You'll immediately see where the error occurs.