Setting up path in the below code - php

<?php
if($_FILES['Filedata']['size']>=520000)
{
echo "\n Sorry, Not Moved Size below 5.2kb or 5200 bytes Only\n";
return;
}
$ext = end(explode('.', strtolower($_FILES['Filedata']['name'])));
if(move_uploaded_file($_FILES['Filedata']['tmp_name'], "./".$_FILES['Filedata']['name']))
{
echo "\nfile moved Success\n";
return;
}
?>
When i set path, it does not work... i dont know where to exactly set path such that the file gets saved in the directory.

See the move_uploaded_file documentation.
The first argument ($_FILES['Filedata']['tmp_name']) is the source, which you shouldn't change. The second argument ("./".$_FILES['Filedata']['name']) is the destination, which will currently put the file in the current working directory with its original name (This can be a security issue; you should put the file in an upload directory that has no execute permissions.)

Related

file_exists() not working as expected

In the code below, file_exists() is not working as expected. Even when I'm trying to upload the same file, the else part gets executed. (ie file_exists() returns false in every case.) What is the reason behind this behavior?
if (isset($_FILES['file']['name']) && isset($_FILES['file']['size']) && isset($_FILES['file']['type']) && isset($_FILES['file']['tmp_name']))
{
if (!empty($_FILES['file']['name']) && strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION))=='jpg' || strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION))=='jpeg')
{
if(file_exists($_FILES['file']['name']))
{
echo 'file exists';
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'], 'Images/'.$_FILES['file']['name']);
echo $_FILES['file']['name'].' Uploaded'.'<br>';
}
}
}
else{
echo 'select your file';
}
The problem
When you use file_exists, you only use the short name of the file.
if(file_exists($_FILES['file']['name']))
For example, if you upload a file called test.jpg, it checks if ./test.jpg exists.
But, when you actually move the uploaded file, you put it in a directory called Images:
move_uploaded_file($_FILES['file']['tmp_name'], 'Images/'.$_FILES['file']['name']);
Now, if you upload that test.jpg, it's moved to ./Images/test.jpg, which isn't found by your other code.
The solution
You should use the same file name in both cases. So, just change the if with the file_exists call to:
if(file_exists('Images/'.$_FILES['file']['name']))
This code adds the folder name to the file name, so that you check for the correct path; uploading test.jpg leads to checking the file ./Images/test.jpg.
$_FILES['file']['name'] is your INPUT / POST data, not your real file;
You should check $your_dir_path_to_file . '/'.$_FILES['file']['name']
Set up the default file system separator (system dependent):
defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR);
If you can, try using absolute path not a relative one and secure the system from names like "../../file.jpg":
defined('BASE_PATH') ? null : define('BASE_PATH', 'C:'.DS.'www'.DS.'Images'.DS);

move_upload_file, return false but still working and not moving correctlly

I am sending image from android apps to server. The problem is image not moving to the correct path, but only at current directory (only in which that php script stored). I tested this codes on local server and webserver, getting same result. Any one can find out whats problems.
Local Server: XAMPP 1.7.7
My PHP Script :
<?php
$base=$_REQUEST['image'];
$Username=$_REQUEST['Username'];
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
$file = fopen($Username.'.png', 'w');
fwrite($file, $binary);
$uploadFilename = '/htdocs/android/ProfileImage/';
$tr =move_uploaded_file($_FILES[$file]['tmp_name'], $uploadFilename);
if($tr)
echo 'true';
else
echo 'false';
echo 'Successfully Uploaded';
?>
Showing Output and Error in Local Server
Strict Standards: Resource ID#3 used as offset, casting to integer (3) in C:\xampp\htdocs\android\uploadSimage.php on line 12
Notice: Undefined offset: 3 in C:\xampp\htdocs\android\uploadSimage.php on line 12
falseSuccessfully Uploaded
Showing Output and Error in Webserver
Notice: Undefined offset: 3 in C:...\uploadSimage.php on line 12
falseSuccessfully Uploaded
move_uploaded_file() expects the second parameter to be a string representing the new path and filename of upload. Currently, you are passing only a path. I also question whether the path is correct. It must be a full path, or a relative path.
You are also using the $_FILES array incorrectly. Are you uploading the image by encoding it in base64 and passing it via the URL's query string? Or are you actually uploading it using a multipart/form-data file upload field?
If you uploaded a file belonging to the upload field called image then you would get access to the file like this:
$origname = $_FILES['image']['name']; // the name from the client device
$temppath = $_FILES['image']['tmp_name']; // the temp location on the PHP server
$error = $_FILES['image']['error']; // > 0 if there was an error
$size = $_FILES['image']['size']; // size of the file
$type = $_FILES['image']['type']; // mime type, cannot be trusted though
You would then move it like this:
// Be careful using the original file name.
// If the user uploads a file with a .php extension, they may be
// able to run PHP code on your server if they can access the upload folder
// You should either generate a random file name or remove the extension
// IF THE DESTINATION FILE EXISTS, IT WILL BE OVERWRITTEN
$newPath = '/home/yoursite/htdocs/uploads/' . $origname;
$moved = move_uploaded_file($_FILES['image']['tmp_name'], $newPath);
if ($moved) {
echo "File was moved successfully.";
} else {
echo "Failed to move file.";
}
EDIT:
If you are in fact uploading the image by encoding it in base64 and sending it over the URL, then you don't need move_uploaded_file at all; in that case you can just write the decoded contents to a file anywhere you like. Keep in mind, the length of the URL may be limited so sending the image in the URL via base64 may not be a good idea.
EDIT 2:
To comment on the questions in your subsequent answer: The php function move_uploaded_file() should only be used when the file you are trying to move was uploaded to PHP using an HTTP POST method upload. It does an internal check to see if the file you are trying to move was uploaded to PHP. If it was not, then it won't move the file. Therefore you shouldn't be using move_uploaded_file() since you confirmed you were uploading the image through the URL.
Since your PHP script's path is C:\xampp\htdocs\android, this means the root path is C:\. The server root is different from your web root or document root which are both relative to your public directory. Any time you are dealing with reading/writing files in PHP, you use the full server path (relative to C:\ or /).
Given the new facts, try some code like this to "upload" the image:
<?php
$base = (isset($_REQUEST['image'])) ? $_REQUEST['image'] : '';
$Username = (isset($_REQUEST['Username'])) ? trim($_REQUEST['Username']) : '';
$binary = #base64_decode($base);
if (empty($Username)) {
die('no username specified');
}
if (!$binary) {
// data was not in base64 or resulted in an empty string
die('invalid image uploaded');
}
$basePath = 'C:\\xampp\\htdocs\\android\\ProfileImage\\';
$imagePath = $basePath . $Username . '.png';
$file = #fopen($imagePath, 'w+');
if (!$file) {
die('failed to open ' . $imagePath . ' for writing');
}
fwrite($file, $binary);
fclose($file);
echo 'Successfully Uploaded';
Make sure to take the necessary precautions so I can't upload an image for another user.
per to this document http://php.net/manual/en/function.move-uploaded-file.php another reason for this problem is invalid File name if your file Name in
move_uploaded_file ( string $filename , string $destination ) be invalid
this function return false
I accessed my server using file zilla and give write Group permissions to the target folder and then it worked.
If you're using XAMPP:
sudo chmod 777 -R /opt/lampp/htdocs/

Why is move_uploaded_file not working?

Whenever I try to move a file it does not work and shows "Image file not uploaded"... I just want to know where the error is...
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if( move_uploaded_file( $target, $destination ) ) {
echo "Image file is successfully loaded";
} else {
echo "Image file not uploaded.";
}
I have checked error log (tail -f /var/log/apache2/error.log) but found nothing.
target and destination both directories have 777 permissions.
Can someone tell me that how to find out the error. Any idea ?
If you are not using HTTP POST upload method then you can use rename()
rename($target, $destination);
Has the file been uploaded in the current request?
move_uploaded_file will refuse to move files that are not uploads. (i.e. $target must equal $_FILES[$field_name]['tmp_name']
If it has been uploaded previously, move_uploaded_file will refuse to work (if it is even still there - PHP will delete it if you don't handle the file on that upload if I remember correctly)
If it is in fact not a file that has been uploaded with this request you'll want to use rename
move_uploaded_file() only works on http post files. http://php.net/manual/en/function.move-uploaded-file.php
to move a file already on the server, you will have to copy the file and unlink the old file
$target = '/var/www/student/public/myimage.jpg';
$destination = '/var/www/student/public/images/myimage.jpg';
if (copy($target, $destination)) {
unlink($target);
} else {
echo "Unable to copy $target to $destination.";
}

PHP move_uploaded_file to directory and create file

I have a script that uploads a file and then moves it to a directory. However the script does not know the name of the file its creating because it hasn't created it yet and cannot find the file to update.
So either one requires a way to make the file first or there is another way of doing this. The code.
<?php
$filename = '/home/divethe1/public_html/update/z-images/admin/upload/test/';
if ($_FILES['thumbfile']['error'] === UPLOAD_ERR_OK) {
$info = getimagesize($_FILES['thumbfile']['tmp_name']);
if (($info[2] !== IMG_GIF) && ($info[2] !== IMG_JPEG)) {
die("not a gif/jpg");
}
if (filesize($_FILES['thumbfile']['tmp_name']) > 100000) {
die("larger than 100000");
}
move_uploaded_file($_FILES['thumbfile']['tmp_name'], $filename . $_FILES['thumbfile']['name']);
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Archiving"</script>Archiving';
}
else
{
echo '<script type="text/javascript">
parent.document.getElementById("thumbprogress").innerHTML = "Invalid File Format"</script>Invalid File Format';
}
?>
Any ideas?
I think you're misunderstanding how move_uploaded_file() works. It doesn't create a file for you. It:
Takes the temporary filethat PHP created for you to hold the upload (the filename/path for which is in $_FILES['thumbfile']['tmp_name'])
does a few security checks to make sure no one's tampered with the file between the time the upload completed and the move_uploaded_file call was issued
then MOVES the file to the location you specify.
It doesn't handle the upload, or receive the file - by the time your upload-handling script gets fired up, the upload has already been completed and the file is waiting in that tmp_name location.
If the move can't be completed for any reason, move_uploaded_file() returns false. It won't warn you if you're overwriting a file in the destination, on the assumption that you know what you're doing.
My mistake. I left the directory test in place. That should have gone. Thanks anyway for all help.

Deleting files in higher directory

I'm having problems deleting a file from a higher directory, I found this post and tried it but no luck....:
gotdalife at gmail dot com 25-Sep-2008
02:04
To anyone who's had a problem with the
permissions denied error, it's
sometimes caused when you try to
delete a file that's in a folder
higher in the hierarchy to your
working directory (i.e. when trying to
delete a path that starts with "../").
So to work around this problem, you
can use chdir() to change the working
directory to the folder where the file
you want to unlink is located.
<?php
> $old = getcwd(); // Save the current directory
> chdir($path_to_file);
> unlink($filename);
> chdir($old); // Restore the old working directory ?>
here is the code that I currently have:
session_start();
if (!isset($_SESSION['agent']) OR ($_SESSION['agent'] !=md5($_SERVER['HTTP_USER_AGENT']))){
require_once ('includes/login_functions.inc.php');
$url = absolute_url();
header("Location: $url");
exit();
}
$folder = $_GET['folder'];
$filename = $_GET['name'];
$path = "../gallery/photos/$folder";
if (isset($_POST['submitted'])) {
if ($_POST['sure'] == 'Yes') {
$old = getcwd(); // Save the current directory
chdir($path);
unlink($filename);
chdir($old); // Restore the old working directory
}
else{
echo '<p>The photo has NOT been deleted.</p>';
}
}
I'm getting the error message :
Warning: unlink() [function.unlink]:
No error in
J:\xampp\htdocs\bunker\admin\delete_file.php
on line 37
line 37 being:
unlink($filename);
can anybody see what I've done wrong?
I always use absolute filepath names.
I'd define the filedir as a constant in your config, then concatenate so you have an absolute filepath, then make a call to unlink().
Btw: I hope you know your code is highly insecure.
See here:
http://bugs.php.net/bug.php?id=43511
and here
http://php.bigresource.com/Track-php-03TimDKO/
http://www.phpbuilder.com/board/showthread.php?t=10357994
Though I wouldnt recommend doing this, as per the comments above. Is there the option for a different approach?

Categories