move_uploaded_file failing with no error - php

This question has been asked similarly a few times, but those answer's didn't apply to the problem I'm have. I've checked them all.
Basically, the function move_uploaded_file is returning false every time, even though I feel like I have all my ducks in a row. There is no error, it just returns false.
I have checked the file that is being uploaded, it has no errors.
It may be a permissions problem, I tried to change the directory I'm uploading the images to using chmod(dir, 0777). If it were a permissions problem, I'm not sure if this would've fixed it. Edit - Checked iswritable(dir) of the directory and it says its writable.
I do have enctype="multipart/form-data" attribute set in my form.
This is my code:
function uniqueName()
{
$target = dirname(__FILE__) . '/TestProject/';
$uid = uniqid();
$ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$_FILES['photo']['name'] = $uid . "." . $ext;
if(move_uploaded_file($_FILES['photo']['name'], $target . $_FILES['photo']['name']))
echo("upload succeeded");
else {
echo("upload failed");
}
return $target . $_FILES['photo']['name'];
}
Am I missing anything? Any help would be appreciated.

Fixed it, the first parameter of move_uploaded_files() expects the tmp_name, not the name.

first off, and i sometimes forget make sure your form looks like this:
<form id="myform" name="myform" action="#" method="post" enctype="multipart/form-data">
key part of this is the
enctype="multipart/form-data">
and as far as uploading I use the following and it works everytime:
if ($_FILES["fuImg"]["error"] > 0)
{
echo "Error: " . $_FILES["fuImg"]["error"] . "<br>";
}
else
{
move_uploaded_file($_FILES["fuImg"]["tmp_name"], "../img/bands/" . $_FILES["fuImg"]["name"]);
}

Related

Images are not shown and file name changes when uploaded to the database

I can't get the picture to display/show when viewing, although the files are already stored in the database (table 'menu') http://i.imgur.com/wo1w90H.png. Also when I upload the images all at once, their file name would change automatically. I don't know how and why this happens. I use array to upload multiple images.
if (isset($_POST["Submit"])) {
--some code here--
if (isset($_POST["id_list"])) {
// if id list available
foreach($_POST["id_list"] AS $id) {
--some code here--
/* Handle file upload */
if ($_FILES['upload']['error'][$id] == 'UPLOAD_ERR_OK') {
$path = "images/newmenu/";
$path_parts = pathinfo($_FILES["upload"]["name"][$id]);
$extension = $path_parts['extension'];
$picture = md5(uniqid()) . "." . $extension;
if (move_uploaded_file($_FILES['upload']['tmp_name'][$id], $path . "/" . $picture)) {
$update = " UPDATE menu
SET MenuPicture='$picture'
WHERE MenuID=$id";
$mysqli->query($update) or die(mysqli_error($mysqli));
}
}
}
}
}
}
Below is the form and yes it does include enctype="multipart/form-data"
<input type="file" multiple name="upload[' . $id . ']" value="' . $record["MenuPicture"] . '">
Filename changes because you are generating it this way
$picture = md5(uniqid()) . "." . $extension;
uniqid() is based on current time and hashing it will cause the filename to change everytime
When I upload the images all at once, their file name would change automatically
It was due to this:
$picture = md5(uniqid()) . "." . $extension;
// And later
move_uploaded_file($_FILES['upload']['tmp_name'][$id], $path . "/" . $picture)
Basically, you are moving your uploaded file to a new filename for your image file, which is generated using uniqid() and hashed with md5(), with the file extension appended at the end.
I can't get the picture to display/show when viewing
How are you trying to display the picture? Is it from web browser, or you go straight to the directory and open from there? What error(s) did you get, if any?
Actually, have you tried to go to the directory and see whether the file is created inside the images/newmenu/ directory?
Also, for the target upload directory, you might want to append it with $_SERVER['DOCUMENT_ROOT'] so that the target directory is not dependent on where your script is located, but it's always based on the root.
By the way, you might know already, but there is an entry in PHP manual page on uploading multiple files

PHP mkdir with form input and security

I'm trying to make the folder with mkdir but no success, I can see that the path is correct but $_post isn't getting the name of folder from form input ($_post['foldername' is empty) don't know what's the problem. (I have all the permissions to make the folder safe_mode is off
You need to use $_POST to get the filename.
As has been posted in the comments, you also need to do something with $_POST['filename'] to insure that the user is not trying to post a relative path to your script and trying to create folders in locations that you don't intend. At the very least make sure that the variable doesn't contain '..' Since you are prepending a path, I don't think that you have to worry about a direct path to '/' but you may also want to invalidate inputs with a '/' in them.
You could always try this:
<?php
include("models/db-settings.php");
include("models/config.php");
$foldername = $_POST["foldername"];
$filename = $foldername;
$path = __DIR__ . "/uploads/" . $loggedInUser->username;
$fullPath = $path . "/" . $filename;
if (!file_exists($fullPath)){
mkdir($fullPath, 0777);
echo "The directory was successfully created.";
}
echo $fullPath;
?>
<form action="mkdir.php" method="post">
<input type="text" name="foldername" id="foldername" value="FolderName">
<input type="submit" value="submit">
</form>
Change
if (!file_exists($path)) {
mkdir("$path/$filename", 0777);
echo "The directory was successfully created.";
}
to
if (!is_dir($path)) {
mkdir("$path/$filename", 0777);
echo "The directory was successfully created.";
}

Delete the file which has spaces in PHP

I am not sure what the issue is, I am trying to delete a file in PHP. The file has spaces in the filename.
So here, is what I am doing :
$filename = "'" . "files/".$results["filename"] . "'";
if (file_exists($filename))
{
$success = unlink($filename);
}
else
{
$echo "Could not Delete the file " . $filename;
}
However, I am getting a File Not exist error. However, I can see that file exists in the folder.
I know it might have been asked a million times, however I could not find it.

Checking if file exists

I have a piece of code that checks whether an image exists in the file system and if so, displays it.
if (file_exists(realpath(dirname(__FILE__) . $user_image))) {
echo '<img src="'.$user_image.'" />';
}
else {
echo "no image set";
}
If I echo $user_image out, copy and paste the link into the browser, the image is there.
However, here, the 'no image set' is always being reached.
The $user_image contents are http://localhost:8888/mvc/images/users/1.jpg
Some of these functions not needed?
Any ideas?
Broken code or a better way of doing it (that works!)?
Beside #hek2mgl answer which i think is correct, i also think you should switch to is_file() instead of file_exists().
Also, you can go a bit further like:
if(is_file(dirname(__FILE__). '/' . $user_image) && false !== #getimagesize(dirname(__FILE__) . '/'. $user_image)) {
// image is fine
} else {
// it isn't
}
L.E:1
Oh great, now you are telling us what $user_image contains? Couldn't you do it from the start, could you?
So you will have to:
$userImagePath = parse_url($user_image, PHP_URL_PATH);
$fullPath = dirname(__FILE__) . ' / ' . $userImagePath;
if($userImagePath && is_file($fullPath) && false !== #getimagesize($fullPath)) {
// is valid
}else {
// it isn't
}
L.E: 2
Also, storing the entire url is not a good practice, what happens when you switch domain names? Try to store only the relative path, like /blah/images/image.png instead of http://locathost/blah/images/image.png
You missed the directory separator / between path and filename. Add it:
if (file_exists(realpath(dirname(__FILE__) . '/' . $user_image))) {
Note that dirname() will return the directory without a / at the end.

Warning: move_uploaded_file(): it is moved but the Filesize stays at zero

I have been using an upload script on my server, like below
$newname = time() . '_' . $_FILES[$file]["name"];
if (strtolower(end(explode('.', $_FILES[$file]["name"]))) != 'pdf' AND $file != "damage_attachment_damageform_1" AND $file != "damage_attachment_damageform_2" AND $file != "damage_attachment_damageform_3" AND $file != "damage_attachment_damageform_4") {
if (move_uploaded_file($_FILES[$file]["tmp_name"], $_SERVER['DOCUMENT_ROOT'] . '/components/com_fleet/uploads/docs/' . $newname)) {
$images[] = $_SERVER['DOCUMENT_ROOT'] . '/components/com_fleet/uploads/docs/' . $newname;
$docs[] = $_SERVER['DOCUMENT_ROOT'] . '/components/com_fleet/uploads/docs/' . $newname;
} else {
die();
}
}
It uploads an image fine, but since a few days a get a Warning: move_uploaded_file(): Unable to move error. Ive seen these a dozen of times while learning to program, so I did all the usual stuff, check paths, the $_FILES[$file]["error"] and check all the right CHMODs. All is fine, path is spot-on, chmod is too, no errors etc...
1 extra weird thing I noticed the file does get written to the right /docs map but its Filesize is empty, and move_upload_file still sends false...
What am I forgetting? CHOWN maybe? And how can I solve that, I dont have SSH access or something.
Graa after an hour I now found out what was wrong, server Disk Quota was exceeded. Maybe people can still benefit from my problems...

Categories