copy php no error - 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

Related

Basic PHP Upload Form Issue

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);

Image uploader working perfectly for an insert form but not for an update form

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.

PHP file upload gives successful error code, but no image appears

For the sake of clarity I'll break this up into easy to navigate and readable sections.
The Issue:
The $_FILES super-global doesn't appear to hold any information after I upload a file. Despite this, I get error code 0 (successful upload) which seems contradictory.
Background:
I've been working on a personal website for a while now, and am working on a post management system. It's been going great so far, but I'm stuck fast trying to upload an image using $_FILES.
I've done this kind of thing many times at school and my job, but there appears to be some sort of issue with my computer, or I'm having a massive stroke of idiocy.
To fix this issue I've already:
Enabled file uploads in php.ini-production for the version I am using (php 7.1.7)
Changed values such as upload_max_filesize and post_max_size to 100m
Inspected the error code PHP is returning, returns error code 0, or UPLOAD_ERR_OK
Checked my own code for any simple mistakes I'm making. I can't see any, but that's usually the case when you have an error.
I'll include a small test page I wrote, and is demonstrating the issue:
text.php:
<?php
if(isset($_POST['submit'])){
echo $_FILES['a']['error'];
if(isset($_FILE['a']['tmp_name'])){
echo "hello";
}
}
?>
<form action = "text.php" method = "POST" enctype="multipart/form-data">
<label for = "a"> Send Image </label>
<input type = "file" name = "a" id = "a">
<input type = "submit" name = "submit" value = "Submit">
</form>
when the form is submitted, I get error code 0 but the hello test statement does not trigger.
Global array is named $_FILES you are checking for isset($_FILE['a']['tmp_name']
And if you want to check for uploaded file try using
if (is_uploaded_file($_FILES['a']['tmp_name'])) {
//file is uploaded
}

uploading img to server using move_uploaded_file() help

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}");

PHP Uploading Issue

I've worked with a few scripts to begin uploading files on my development machine. Problem is, despite the expected ease of this operation, Apache seems to time-out whenever I try to upload an image. Uploading is set to On and the tmp directory is set in php.ini.
I tried uploading the main gif from Google, an 8.36KB image. It should be fine and well within the limits to PHPs uploading capabilities.
Here is a copy of the script. There should be an easy fix. As requested, I changed the tilde to an actual directory.
<?php
if (!isset($_GET['upload'])) { ?>
<form method="post" action="index.php?upload=true" enctype="multipart/form-data">
<input type="file" name="file" class="form">
<input name="submit" type="submit">
</form>
<? } else if (isset($_GET['upload']) && $_GET['upload'] == 'true') {
$url = $_FILES['file']['name'];
$move = move_uploaded_file($_FILES['file']['tmp_name'], "/Users/<username>/Sites/file.jpg");
if ($move) {
echo "Success!";
} else {
echo "Err..."
}
} ?>
Thanks,
Dan
EDIT:
I fixed it, with help from a few of the answers, to one of which I will mark.
A few things here were causing this behavior.
Permissions on the images directory were not set to allow the _www user to access it. A chmod -R 777 images seemed to fix it, as well as a sudo chown _www images.
The form output may have been corrupting the PHP script itself. As suggested, an ECHO <<< ...END helped, I think.
What is it that leads you to believe that Apache is timing out rather than, say, outright failing in some way? Because what leaps out at me is that you're trying to move the file to ~/file.jpg, which I'm nearly certain will not work; ~ is a construct that only normally has meaning inside shells, unless one of PHP's freakish obscure features is processing it in contexts like this. Anyway, try putting the actual directory.
This is more than likely an issue with the size of the file and/or a permission issue between the Apache user and the directory specified. For instance make sure the Apache instance is not running under user (nobody).
Comment to chaos:
He is right the tilde (~) can cause issues, but would probably not cause a timeout; it would display a warning. Even if it does work on your system it would probably deposit the file into an unexpected directory or run into some issues if the Apache user (ie www) does not have a valid home directory set.
If the issue is filesize, add the following lines to your php.ini file and it should work:
upload_max_filesize = 500M ;
post_max_size = 500M ;
PHP by default has a 30 second timeout on the page. So if your upload takes longer than 30 seconds it will fail. Set the timeout either in your php.ini or put the following code at the top of the file.
ini_set(max_execution_time, 90);
The second argument represents the time in seconds before the page will timeout. Set it to whatever time you feel is appropriate. Also, chaos is correct in that '~' is a construct that commonly has meaning only inside shells.
Re: http://ca2.php.net/manual/en/ini.list.php
EDIT:
The problem is that you reopened the tag in the middle of a conditional. Trying your code I get a syntax error. It's strange that you were able to see any web form. This is the fixed code (that works for me).
<?php
if (!isset($_GET['upload'])) {
ECHO <<<END
<form method="post" action="index.php?upload=true" enctype="multipart/form-data">
<input type="file" name="file" class="form">
<input name="submit" type="submit">
</form>
END;
} else if (isset($_GET['upload']) && $_GET['upload'] == 'true') {
$url = $_FILES['file']['name'];
$move = move_uploaded_file($_FILES['file']['tmp_name'], "/Users/<username>/Sites/file.jpg");
if ($move) {
echo "Success!";
} else {
echo "Err...";
}
} ?>

Categories