I want my form to check if the file name equals the users name, in principle everything works fine how I tested it, but the problem I'm having is that the spell check includes the format letters of the image, thus giving a non match.
Example:
Username tries to upload a picture which is correctly named Username.png
The system would work fine, but it takes into account the .png as well, thus gives out a non match. Is there a way I could try and exclude the image format name from the if statement? Because that is pretty much the only problem I'm having with my function, I tried renaming myself to Username.png and then the form works great, but in practice nobody will use such a weird username lol. I'm sorry if my question is a bit confusing or too long, hope it is as clear as I think it is. I will include my small snippet of code here:
if ( ($_FILES["fileToUpload"]["name"]) != $ir['username'] )
{
echo "Sorry, your file is not correctly named.";
$uploadOk = 0;
}
I tried adding a .png after the $ir['username'] like so: $ir['username'].png but then the form just gives out a critical error, so I assume this is a bad spot to write it in. Is there a better way I could do this and is there a way at all? Maybe I could make the form not show up the .png for example? I'm unsure how I could handle this at this point, any input would be invaluable. Thank you for your time, have a good day!
Edit: I will include the form itself as well:
<form action='upload.php' method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload' id='fileToUpload'><br>
<input type='submit' value='Upload Picture' name='submit'>
</form>
There are several ways of doing that.
The easiest is to split your filename on ., remove the last one and glue it again.
$filename = explode('.', $_FILES["fileToUpload"]["name"]);
array_pop($filename);
$filemame = implode('.', $filename);
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 form with the possibility to upload an image from the computer to a server, but it won't work. I don't get any error message, so that's quite annoying. (First I got permission denied, but that was solved by changing the rights), but now when I submit the form, everything goes normally, but the file isn't copied to the destination folder. (The folder exists: I tried it with file_exist()...)
Here's part of the code:
<form action='/changingfruit/index.php?item=bad' name='form' method='post' enctype='multipart/form-data'>
<tr>
<td><input type='text' name='titel_nl' value="titel nl" /><br/><input type='text' name='titel_fr' value="titel fr"/></td>
<td><input type='file' name='text_nl' id='text_nl' accept="image/*"/><br/><input type='file' name='text_fr' id="test_fr" accept="image/*"/></td>
<td class="vTop"><input type="submit" value="Bewaar"/></td>
</tr>
</form>
Part where the values are being send to the db:
$str_titel_nl = $_POST["titel_nl"];
$str_titel_fr = $_POST["titel_fr"];
$str_text_nl = $_FILES["text_nl"]["name"];
$str_text_fr = $_FILES["text_fr"]["name"];
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
(of course the above is just a part of the code: but it's this part that wont work:
if(!empty($_FILES["text_nl"]["name"])){
$tmp = $_FILES['text_nl']['tmp_name'] ;
$foto = $_FILES['text_nl']['name'] ;
$copied = copy($tmp, $images_nl.$foto);
unlink($tmp);
}
The code below this part also works fine, so no error, but also no image.
Does someone knows where the problem could be?
Thanks so much in advance!
FOUND THE ANSWER
So it was indeed a permission problem. Everything was 777, but the last folder where the image was put had 755. (/fruits/img/2012/thumb/) the thumb was 755.I just overlooked it. Thanks everyone for the help!
Your upload code is very messy. Instead of using copy you should be using move_uploaded_file, and also validate that it actually worked and then perform whatever actions needed.
I'm also not sure why each of your line is starts with <?php and ends with ?> ?
You can write it all as one block instead, and i think it would also make more sense and would make your code cleaner for sure.
Last thing i would recommend is reading "Handling File Uploads" from the PHP Manual. It might shed some light on the problems you're having.
P.S. Try adding on top ini_set("display_errors","On"); error_reporting(E_ALL); and see if you're getting any error messages.
please have a look on below link.
PHP upload file to web server from form. error message
http://patelmilap.wordpress.com/2012/01/30/php-file-upload/
you can try this
$flag = #copy($temp, $move);
if ( $flag === true )
{
print "Uploaded";
}
I have posted a simple solution for file uploading without worrying about the implementation .
Click to see the thread
image uploading issue in codeigniter 2.1.0
Please read this section
in that $uploader->getMessage(); will return error string related to the upload failure . So you can understand why the uploading failed .
Thanks
I am using a foreach php statement to list all of the uploaded files within a directory.
It looks like this:
<?php
$path = "$dir/";
foreach (glob("$path*") as $filename) {
$path_parts = pathinfo($filename);
$result = $path_parts['filename'];
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
?>
This prints out a nice simple list of all files.
What I would like to do for each item, is add a delete button next to it. I am thinking the only way to do this, would be to add a form into the foreach statement, with just a button that posts the $filename variable to some PHP with the delete function in.
The only thing I am uncertain of is if the best way to get the filename to the new php.
I am thinking along the lines of:
<?php
$path = "$dir/";
foreach (glob("$path*") as $filename) {
$path_parts = pathinfo($filename);
$result = $path_parts['filename'];
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
echo "<form method='post' action='delete.php'>
<button type='submit' name='submit' value='Submit' />
</form>";
}
?>
So using that, I can create a button next to the filename for deletion, but the only way I can think of taking the actualy filename through to the delete PHP file, is to add in a hidden text field with the filename as the value.
This would work but seems a bit clunky. Can anyone advise if this is acceptable or if there is a better alternative?
The addition of the filename/id/whatever to the form is not really that clunky .. it's more of a necessity unless you want javascript to be mandatory (then you can get the filename from the sibling li or something. However, there are a couple problems:
HTML
You have a random tr tag (should this be br) at the end of each list. Your li are outside of a ul or ol block, and the form must be inside of an li (that is you cannot have <ul><li /><form /></ul> as valid markup). Not a huge deal, but this may cause some display problems for you.
UI
It would be pretty annoying to have to click individual "deletes" on a long list of files, and it looks like there is no way to recover from this. Even better would be to have them be check boxes so you could delete multiple files at once and change your mind before your final decision. Then, you only need one form and it makes even more sense to have individual inputs for each file.
Security
I'm not sure how you get $dir (I really hope register globals isn't on), but you should make absolutely certain that requested file deletions contain a valid path to delete and preferably don't contain ../ or a leading / or something. You should validate this input.
A hidden field with the file name would suffice, you can use php's $_POST to get the filename in the other script. Another option would be to post it to the script using a get parameter with the filename, so you only change the get parameter part.
The real problem is that you should sanitize the input the second script receives. It is just very important that people can only delete files they're allowed to delete.
At the very minimum you should check if the file is in a specific folder. Other options are only deleting files from one folder (so not accepting paths) or abstracting filenames away behind id's
So im here trying to learn more php and... trying to add an image that a user would upload(an avatar) to the server via move_uploaded_file...oh and im on WAMP right now fyi.
the book im reading ...long story short, the example shown doesnt work. Ive Googled around and literally copy pasted a few relavant examples ive found and still....well to be clear, be it that i wrote it or from the net, i can upload the image name (along with other values) to tables on the db i have set up but the image itself doesn't move to the directory I've set up for it.
I've stripped all my apps code to a simple table and simple php to make sure nothing was conflicting etc, and still nada.
here is my html:
<form method="post" action="testUpload.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="32768" >
<table summary="guitarwars lesson" width="500">
<tr>
<td>load picture:</td>
<td><input type="file" name="screenshot" id="screenshot" ></td>
</tr>
<tr>
<td><input type="submit" name="submit" action="submit"></td>
</tr>
</table>
</form>
here is my php:
<?php
$screenshot = $_FILES['screenshot']['name'];
//$destination = "images/user_avatars/$screenshot";
$insertValues = "INSERT INTO testdb(screenshot) VALUES ('$screenshot')";
//---declare connection.
$connect2db = mysqli_connect('127.0.0.1','root','pass','dbname');
if(!$connect2db){
die("Sorry but theres a connection to database error" . mysqli_error);
} else {
//pg intro mssg
echo ' <span style="font-size:25px; color:green;"> --- Link Established with Database ---.<span/><br/><br/>';
}
// put into db.
if(!empty($screenshot)) {
$insertData = mysqli_query($connect2db, $insertValues);
echo 'data submitted. thank you';
move_uploaded_file ($_FILES['screenshot']['tmp_name'],"images/user_avatars/{$screenshot}");
echo 'IMAGE UPLOAD COMPLETE';
}
mysqli_close($connect2db);
?>
now i dont get an error...i actually get the echo "image upload complete" part...
and like i said, with the app code, i get multiple values AND the image name going through and being saved onto the db, but the image itself being moved from temp to my location is a no go.
any tips links, etc i gladly appreciate.
Thank you in advance.
If that's code from your book, then throw the book out and burn it as fast as you can.
a) You're wide open to SQL injection attacks. Any decent PHP tutorial that shows how to deal with databases should START with sql injection attack mitigation strategies.
b) Your connection-failed error uses mysqli_error, which is an undefined constant. You probably want mysqli_error(), which is a function call
c) The code assumes the upload completed successfully. Uploads can/will fail at the drop of a hat, so NOT checking for errors is the fast road to hair-pulling. At minimum the script should have something like
if ($_FILES['screenshot']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['screenshot']['error']);
}
Those error codes are defined here.
d) Your code is using the user-supplied filename to store the file onto the sever. Nothing says that a malicious user can't hack the filename to include path information, so your code is actually allowing that nasty user to scribble on ANY file on your server which the webserver process has write access to. This is BAD
e) Your code also assumes the file move succeeded, without checking for errors. It should have at mininum
$status = move_uploaded_file(...);
if (!$status) {
die("Move failed!");
}
or something similar.
f) Your code assumes that all the database queries succeeded. Even if your query string is 100% perfectly formed (yours aren't, see (a) above), queries can fail for any number of other reasons. At bare mininum you should have:
$result = mysql_query(...) or die(mysqli_error());
As a start you could add
if(!move_uploaded_file(...))
die('error');
if you replace
move_uploaded_file ($_FILES['screenshot']['tmp_name'],"images/user_avatars/{$screenshot}");
echo 'IMAGE UPLOAD COMPLETE';
with
if (move_uploaded_file ($_FILES['screenshot']['tmp_name'],"images/user_avatars/{$screenshot}")) {
echo 'IMAGE UPLOAD COMPLETE';
}
you would then get the echo if it was successful
Try to supply the absolute path:
move_uploaded_file ($_FILES['screenshot']['tmp_name'],"/path/to/images/user_avatars/{$screenshot}");
I've been all over the internet reading up on APC, and it seems like a nifty way to detect file Uploading.
I am, however, having a problem.
I know how to call files and everything using Ajax, and that is what I am planning to do, but for Testing sake, I'm doing something like this.
Ok, so I have 3 files.
form.php
upload.php
status.php
form.php contains:
<input type="hidden" name="APC_UPLOAD_PROGRESS" value="1234" />
<input type="file" id="fileIn" name="file" />
(I am aware that I will need to use a unique ID in APC_UPLOAD_PROGRESS. Again, this is just for testings sake.)
Ok, Now Upload.php has the regular PHP upload script:
$origin = $_FILES['file']['name'];
if(move_uploaded_file(...etc...etc)...
And Status.php uses APC:
$upload = apc_fetch('upload_1234');
if ($upload) {
if ($upload['done'])
$percent = 100;
else if ($upload['total'] == 0)
$percent = 0;
else
$percent = $upload['current'] / $upload['total'] * 100;
echo $percent;
}
Now What I am doing is uploading a file using a regular HTTP method, and using another window to monitor Status.php.
The problem is; Status.php returns nothing!
However, If i write
print_r(apc_fetch('upload_1234'));
into upload.php, it returns the correct array, with all the details etc..
What am I doing wrong?
Thanks.
When this happens, something to check is that your hidden input element with the APC_UPLOAD_PROGRESS key is placed immediately before the file input in your form.
I know the form in the example above does do this, but it's easily missed in a more complicated form layout.