I need to get this done very quickly. What's an easy way to do image uploading in php...I have a script atm but if an image with the same name comes it'll overwrite it.
Basically I just want to be able to use the form field file to select an image and upload and maybe rename it somehow. Then put the location into a database to retrieve when needed.
Any tips or ideas on how to do this? Don't have a lot of time to get this done.
http://www.google.co.za/search?sourceid=chrome&ie=UTF-8&q=php+image+upload
http://www.plupload.com/ - is also a good way to do this. Doing something
very quickly ... the easy way
Sounds to me like you are looking for the easy way out. Please remember that we are not here to give you your code solution, but merely as an advisory panel to help you get over some obstacles in your current (already tried to make it work) code. If you read up a bit its real easy, thats the reason for documentation on everything, especially PHP and file uploading.
:)
Seems to me right now, your script has a security issue as well.
Append a unique hash to the end of the filename before you save it. That way no one can overwrite your files.
Can you just append uniqid() to the filename..?
$target = "files/";
// Upload the file to directory
$url = basename($_FILES['uploadedfile']['name']);
$name = str_replace(' ', '_', $url);
$target .= strtolower($name . uniqid());
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target))
{
echo 'File has been uploaded<br />
http://yoursite.com/directory/' . $target . '';
}
Obviously still needs to be made more secure.
Related
I know there are already many similar questions like this and I apologize in advance for adding to the file, but I am a little short on time to do research and I need quick help. I am trying to finish an overdue assignment and my image upload function is working perfectly when I add a product, but not when I update it. I have no idea why. My code to update the image is here:
require_once 'file-util.php'
// Check if the file exists before setting it
if (isset($_FILES['imageFile1'])) {
// Retrieve the name of the file based on what it was called on the client computer
$filename = $codeInput . '.png';
// Make sure the filename exists
if (!empty($filename)) {
// Store the temporary location of where the file was stored on the server
$sourceLocation = $_FILES['imageFile1']['tmp_name'];
// Build the path to the images folder and use the same filename as before
$targetPath = $image_dir_path . DIRECTORY_SEPARATOR . $filename;
// Move file from temp directory to images folder
move_uploaded_file($sourceLocation, $targetPath);
}
}
This is the exact same code that I have in my insert_product file.
And my file_util is here:
$image_dir = 'images';
$image_dir_path = getcwd() . DIRECTORY_SEPARATOR . $image_dir;
Everything else works perfectly, but it is just this little thing that isn't seeming to do anything, so it seems to me like there's a little detail I'm missing for this to work in update_product. Is there something else I need to do to get this to work, or is it something else I'm unaware of?
Edit: Turns out that I just forgot to set the encryption type in my add_product_form. If anyone else has this silly issue, double check your forms for this near the top of the body:
<form action="insert_product.php" method="post"
id="add_product_form"
enctype="multipart/form-data">
You need to check if your updating form tag has the proper enctype attribute value...
and please be aware to use more validation on the uploaded file, your checking for file name exists or not will always be true as you are setting a value for it in the previous line.
Apparently, my code was right but I just forgot to go "enctype="multipart/form-data" in update_product_form.php.
I have a file hosting website and everything works except one thing. I cannot upload two files with the same name. I want to be able to overright the name of a new file with a format like file_2.ext i believe this can be done with the file_exists() function but I am having trouble getting it to work. I will post the system I use to get files to upload below.
System:
if (move_uploaded_file($tmp_location, $location . $name)) {
echo'<br>Upload was successful';
}
I tried doing:
if (isset($_POST['submit_file']) &&!file_exists($name)) {
move_uploaded_file($tmp_location, $location . $name)
echo'<br>Upload was successful';
} else if (isset($_POST['submit_file']) &&file_exists($name)) {
!move_uploaded_file($tmp_location, $location . $name);
echo 'File exists';
}
The method above did not post the error message.
Try something like this. You will need to find a unique filename. You don't want to let it go indefinitely though, so add a limit to it.
function get_unique_filename($filename) {
if (!file_exists($filename)) return $filename;
$limit = 200;
$path = dirname($filename).DIRECTORY_SEPARATOR;
$basename = basename($filename);
$parts = explode('.', $basename);
$ext = array_pop($parts);
$base = implode('.', $parts);
for ($i=2; $i<$limit+2; $i++)
if (!file_exists($path.$base.'_'.$i.'.'.$ext))
return $path.$base.'_'.$i.'.'.$ext;
return false;
}
if (isset($_POST['submit_file'])) {
$new_path = get_unique_filename($location.$name);
if ($new_path && !move_uploaded_file($tmp_location, $new_path))
echo 'Could not upload file.'
else
echo '<br/>Upload was successful';
}
The way you're tackling it is wrong in my opinion , even if you need the user to have the "original" filename, you can't show them "file2.ext" if they uploaded "file.ext", that's just confusing and feels so wrong, take this example
Your server has files named file.ext, file2.ext and file4.ext and
your user uploads a file named file.ext, how would you handle that ? will you iterate over the pattern file*.ext and then add one to the biggest number ? or look for holes
and name it file3.ext ?, or will you append a random number to the file ? how will you handle collisions ? keep looping till it works ? it's just too much pain and might end up making your server really busy if you handle lots of uploads !
What I would do, is use uniqid for filenames on your filesystem, then have a DB that links original filenames to the UUIDs.
This way, all your users are able to upload an file named "file.ext", also it's cleaner to handle files since everything will be unique and their names will have the same length, and no need to worry about filenames in who knows what encoding, etc..
It'll also give you a bonus of being able to change UUIDs and show the same filenames to the user without worrying what they see, this way you're having a layer between the actual files on your FS and what the user perceives files.
I'm working on a small, user-maintained online store, and am trying to allow my end user (the store administrator) to upload graphics for products. When I run this script, however, it doesn't actually store the image. I built this script from various tips here and a tutorial, and have gotten everything but the image upload portion to work.
// Set the image target directory here
$target = "itemImages/";
$target = $target . basename($_FILES["image"]["name"]);
// Variables get POSTed here - just tack new ones on at the end.
// Various POSTs omitted for brevity
$pic=($_FILES["image"]["name"]);
// Places the picture in the folder
if(move_uploaded_file($_FILES["image"]['tmp_name'], "itemImages/"))
{
echo "The file " . basename($_FILES['uploadedfile']["name"]) . " has been uploaded.<br />";
}else {
echo "There was an issue adding this item. Please try again.<br />";
}
// Writes variables to the database
mysql_query("INSERT INTO tbl_item (itemNAME,itemDESC,itemCOST,itemHCOL,itemHSIZ,itemIMG)
VALUES ('$itemName','$itemDesc','$itemCost','$hasColor','$hasSize','$pic')");
mysql_close($con);
?>
Any help, tips, advice, insight, etc. would be very much appreciated.
move_uploaded_files requires a filename as its target. It does not blindly move to a directory, so
move_uploaded_files($_FILES..., 'somedir/somefile.txt');
works, but
move_uploaded_file($_FILES..., 'somedir/');
will not.
Plus, note that your database operation is vulnerable to SQL injection attacks. You're blindly inserting the uploaded file's remote name (['name'] via $pic), and that name is fully under the remote user's control.
Make sure the itemImages folder has write permission by the user your web server (e.g. Apache) is running as (e.g. www-data)
make sure the .php file and the folder you are writing to have the same "owner". Or try setting permissions on the itemImages folder to 777 (This is not recommended, just a debug tactic)
how can I copy two times the same file? I'm trying to do something like this:
copy($file['tmp_name'], $folder."1.jpg");
copy($file['tmp_name'], $folder."2.jpg");
copy($file['tmp_name'], $folder."3.jpg");
And how many time does temp files has before it's destroyed by the server?
I try using move_uploaded_file also, but I can't make it work. I want to generate 2 thumbs from an uploaded file.
Some help?
Thanks,
move_uploaded_file will move the file, and not copy it -- which means it'll work only once.
If you are using copy, there shouldn't be any limit at all on the number of times you can copy : the temporay file created by the upload will only be destroyed at the end of the execution of your script (unless you move/delete it before, of course)
Still, maybe a solution would be to use move_uploaded_file first, and, then, copy ?
A bit like that, I suppose :
if (move_uploaded_file($file['tmp_name'], $folder . '1.jpg')) {
copy($folder . '1.jpg', $folder . '2.jpg');
copy($folder . '1.jpg', $folder . '3.jpg');
}
This would allow you to get the checks provided by move_uploaded_file...
If this doesn't work, then, make sure that :
$folder contains what you want -- including the final /
That $file['tmp_name'] also contains what you want (I'm guessing this is some kind of copy of $_FILES -- make sure the copy of $_FILES to $file is done properly)
Why doesn't move_uploaded_file() work? Are you trying to use it twice? You can't do that, it moves it, so the second time will fail.
I would just use move_uploaded_file() once, and then make the second copy from the location you just moved it to:
move_uploaded_file($uploaded, $destination);
copy($destination, $destination2);
I don't have a reply to your question directly but how about this workaround ?
copy($file['tmp_name'], $folder."1.jpg");
copy($folder."1.jpg" , $folder."2.jpg");
copy($folder."1.jpg" , $folder."3.jpg");
Thanks man, you give me the light.
I made something like this:
$objUpload = new Upload();
$filename = $objUpload->uploadFile($newFile,$folder);
// returns a string
$objUpload->makeThumb($filename,$folder,"thumbs",139);
// makes a 139px thumbnail from the original file uploaded on the first step
$objUpload->makeThumb($filename,$folder,"mini",75);
// makes another thumb from the same file
Using move_ulploaded_file and copy we can make only one thumb. :)
I have the php code below which help me get a photo's thumbnail image path in a script
It will take a supplied value like this from a mysql DB '2/34/12/thepicture.jpg'
It will then turn it into this '2/34/12/thepicture_thumb1.jpg'
I am sure there is a better performance way of doing this and I am open to any help please
Also on a page with 50 user's this would run 50 times to get 50 different photos
// the photo has it is pulled from the DB, it has the folders and filename as 1
$photo_url = '2/34/12/thepicture_thumb1.jpg';
//build the full photo filepath
$file = $site_path. 'images/userphoto/' . $photo_url;
// make sure file name is not empty and the file exist
if ($photo_url != '' && file_exists($file)) {
//get file info
$fil_ext1 = pathinfo($file);
$fil_ext = $fil_ext1['extension'];
$fil_explode = '.' . $fil_ext;
$arr = explode($fil_explode, $photo_url);
// add "_thumb" or else "_thumb1" inbetween
// the file name and the file extension 2/45/12/photo.jpg becomes 2/45/12/photo_thumb1.jpg
$pic1 = $arr[0] . "_thumb" . $fil_explode;
//make sure the thumbnail image exist
if (file_exists("images/userphoto/" . $pic1)) {
//retunr the thumbnail image url
$img_name = $pic1;
}
}
1 thing I am curious about is how it uses pathinfo() to get the files extension, since the extension will always be 3 digits, would other methods of getting this value better performance?
Is there a performance problem with this code, or are you just optimizing prematurely? Unless the performance is bad enough to be a usability issue and the profiler tells you that this code is to blame, there are much more pressing issues with this code.
To answer the question: "How can I improve this PHP code?" Add whitespace.
Performance-wise, if you're calling built-in PHP functions the performance is excellent because you're running compiled code behind the scenes.
Of course, calling all these functions when you don't need to isn't a good idea. In your case, the pathinfo function returns the various paths you need. You call the explode function on the original name when you can build the file name like this (note, the 'filename' is only available since PHP 5.2):
$fInfo = pathinfo($file);
$thumb_name = $fInfo['dirname'] . '/' . $fInfo['filename'] . '_thumb' . $fInfo['extension'];
If you don't have PHP 5.2, then the simplest way is to ignore that function and use strrpos and substr:
// gets the position of the last dot
$lastDot = strrpos($file, '.');
// first bit gets everything before the dot,
// second gets everything from the dot onwards
$thumbName = substr($file, 0, $lastDot) . '_thumb1' . substr($file, $lastDot);
The best optimization for this code is to increase it's readability:
// make sure file name is not empty and the file exist
if ( $photo_url != '' && file_exists($file) ) {
// Get information about the file path
$path_info = pathinfo($file);
// determine the thumbnail name
// add "_thumb" or else "_thumb1" inbetween
// the file name and the file extension 2/45/12/photo.jpg
// becomes 2/45/12/photo_thumb.jpg
$pic1 = "{$path_info['dirname']}/{$path_info['basename']}_thumb.{$fil_ext}";
// if this calculated thumbnail file exists, use it in place of
// the image name
if ( file_exists( "images/userphoto/" . $pic1 ) ) {
$img_name = $pic1;
}
}
I have broken up the components of the function using line breaks, and used the information returned from pathinfo() to simplify the process of determining the thumbnail name.
Updated to incorporate feedback from #DisgruntledGoat
Why are you even concerned about the performance of this function? Assuming you call it only once (say, when the "main" filename is generated) and store the result, its runtime should be essentially zero compared to DB and filesystem access. If you're calling it on every access to re-compute the thumbnail path, well, that's wasteful but it's still not going to be significantly impacting your runtime.
Now, if you want it to look nicer and be more maintainable, that's a worthwhile goal.
The easiest way to fix this is to thumbnail all user profile pics before hand and keep it around so you don't keep resizing.
$img_name = preg_replace('/^(.*)(\..*?)$/', '\1_thumb\2', $file);
Edit: bbcode disappeared with \.