PHP file neither moved nor unmoved - php

I can't seem to figure out why this is happening. When I run the following code:
$uref = APACHE_ROOT . UPLOAD_PATH . $applicant . "_ref_{$email}_{$year}";
if ( !move_uploaded_file( $_FILES['file']['tmp_name'], $uref ) ) {
echo "Move failed";
} elseif ( move_uploaded_file( $_FILES['ref']['tmp_name'], $uref) ) {
echo "Move succeeded";
}
Neither statement gets returned. Both paths exist; one file was successfully uploaded and this started happening after only the second upload attempt.
Any ideas why?
Thanks for any suggestions.

if ( !move_uploaded_file( $_FILES['file']['tmp_name'], $uref ) ) {
echo "Move failed";
} elseif ( move_uploaded_file( $_FILES['ref']['tmp_name'], $uref) ) {
echo "Move succeeded";
}
If your first call returns true, because the file is moved, then the second will return false, because the file is no longer there.
You're much better off just having a simple if / else - the first call can be either true or false, so you don't need to re-check.

First, is $uref = APACHE_ROOT . UPLOAD_PATH . $applicant . "_ref_{$email}_{$year}"; a directory?
If it is, then you are trying to write to a directory, which is probably going to fail if the directory already exists.
Also, only check the running once.
The first time, move_file_uploaded will be executed to check if it is negative. It's obviously true, so it goes to the second to check if it's true, and it's returning false.
Do this instead:
$uref = APACHE_ROOT . UPLOAD_PATH . $applicant . "_ref_{$email}_{$year}";
if(move_uploaded_file( $_FILES['file']['tmp_name'], $uref )){
echo "Move succeeded";
} else {
echo "Move failed";
}

Related

php move_uploaded_file returns true but file is missing on localhost

I am trying to move one image to new folder move_uploaded_file is returning 1 but the file is missing, I am working on localhost with XAMPP
$name = basename($_FILES['arr']['name'][0]);
move_uploaded_file($_FILES['arr']['tmp_name'][0],"\Images");
$name = basename($_FILES['arr']['name'][0]);
move_uploaded_file($_FILES['arr']['tmp_name'][0],'/images/' . $filename);
You have to add a destination for the file to go, including the filename that you wish to assign to it.
Refer to: http://php.net/manual/en/function.move-uploaded-file.php
You should specify the destination file name
if ( move_uploaded_file($_FILES['arr']['tmp_name'],dirname(__FILE__) . '/images/' . $_FILES['arr']['name'] ) ) {
echo "file uploaded";
} else {
echo "error in uploading";
}

PHP unlink (delele ) multiple files on server

Sometimes, I have to delete multiple files in different folders on the server. It's a tedious job to to this one by one via FTP. I wrote a little script that does the job. I can import the list of files in Excel and copy and paste them in the script. However, my approach is not elegant:
$file1 = "some-file.php";
$file12 = "some-file2.php";
...
if (!empty($file1)) {
if ( #unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file1 ) )
{
echo 'The file <strong><span style="color:green;">' . $file1 . '</span></strong> was deleted!<br />';
}
else
{
echo 'Couldn't delete the file <strong><span style="color:red;">' . $file1 . '</span></strong>!<br />';
}}
if (!empty($file2)) { ...
I would rather like to do this with a foreach and an array, but don't know how. Any help would be appreciated!
Just put your files into an array and loop it.
$files = array('some-file.php', 'some-file2.php');
foreach ($files as $file) {
if ( #unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file ) ) {
echo 'The file <strong><span style="color:green;">' . $file . '</span></strong> was deleted!<br />';
} else {
echo 'Couldn\'t delete the file <strong><span style="color:red;">' . $file . '</span></strong>!<br />';
}
}
also, i think its better if you use file_exists()
if (file_exists($file1))
{
unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file1 );
clearstatcache();
}

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.

How to use Unlink() function

I'm trying to use PHP unlink() function to delete away the specific document in the folder. That particular folder has already been assigned to full rights to the IIS user.
Code:
$Path = './doc/stuffs/sample.docx';
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
It keep return fail. The sample.docx does reside on that particular path. Kindly advise.
I found this information in the comments of the function unlink()
Under Windows System and Apache, denied access to file is an usual
error to unlink file. To delete file you must to change the file's owner.
An example:
chown($tempDirectory . '/' . $fileName, 666); //Insert an Invalid UserId to set to Nobody Owern; 666 is my standard for "Nobody"
unlink($tempDirectory . '/' . $fileName);
So try something like this:
$path = './doc/stuffs/sample.docx';
chown($path, 666);
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
EDIT 1
Try to use this in the path:
$path = '.'
. DIRECTORY_SEPARATOR . 'doc'
. DIRECTORY_SEPARATOR . 'stuffs'
. DIRECTORY_SEPARATOR . 'sample.docx';
Try this:
$Path = './doc/stuffs/sample.docx';
if (file_exists($Path)){
if (unlink($Path)) {
echo "success";
} else {
echo "fail";
}
} else {
echo "file does not exist";
}
If you get file does not exist, you have the wrong path. If not, it may be a permissions issue.
This should work once you are done with the permission issue. Also try
ini_set('display_errors', 'On');
That will tell you whats wrong
define("BASE_URL", DIRECTORY_SEPARATOR . "book" . DIRECTORY_SEPARATOR);
define("ROOT_PATH", $_SERVER['DOCUMENT_ROOT'] . BASE_URL);
$path = "doc/stuffs/sample.docx";
if (unlink(ROOT_PATH . $Path)) {
echo "success";
} else {
echo "fail";
}
// http://localhost/book/doc/stuffs/sample.docx
// C:/xampp/htdocs\book\doc/stuffs/sample.docx
You need the full file path to the file of interest. For example: C:\doc\stuff\sample.docx. Try using __DIR__ or __FILE__ to get your relative file position so you can navigate to the file of interest.

check if file exist in folder

My script:
$secret = check_input($_GET['secret']);
if(isset($_POST['register'])) {
if (isset($secret) || !empty($secret)) {
if (file_exists(ROOT . '/intl/codes/' . $secret)) {
unlink(ROOT . '/intl/codes/' . $secret);
$trusted = 'yes';
} else {
$trusted = 'no';
}
}
//$_POST['register'] register details...
}
Is there another way to do it (simplier, etc.)?
If $secret doesn't exist in the /codes/ folder, it produces Warning: unlink Is a directory How to get rid of that?
Why $trusted always gives yes even if the file doesn't exist ?
To delete a directory, you should be using rmdir() instead of unlink().
$secret = check_input($_GET['secret']);
if(isset($_POST['register'])) {
if (!empty($secret)) {
if(file_exists(ROOT . '/intl/codes/' . $secret)) {
rmdir(ROOT . '/intl/codes/' . $secret);
$trusted = 'yes';
} else {
$trusted = 'no';
}
}
//$_POST['register'] register details...
}
Although, there is a serious security risk here! If your check_input() does not properly sanitize $secret, you could rmdir('/intl/codes/../') which is the same as deleting /intl/.
Try something like this:
$allowed = ROOT. '/intl/codes/';
$path = realpath($allowed . check_input($_GET['secret']));
if(strpos($path, $allowed) === 0) { //Check that $path is within allowed directory
if(is_dir($path)) {
rmdir($path);
} else if(file_exists($path)) {
unlink($path);
} else {
echo "File/folder not found";
}
} else {
echo "Untrusted user tried to delete outside of allowed directory";
}
You can use just if (!empty($secret)) - empty() returns TRUE for NULL value as well.
Use if (file_exists(ROOT . '/intl/codes/' . $secret) && !is_dir(ROOT . '/intl/codes/' . $secret)) to check if your file is not a directory and get rid of that warning. If you still wanna remove the directory, use rmdir() function.
file_exists() returns TRUE for directories as well. So, you should also check if the argument is a directory with is_dir() , as i said before.
if (file_exists(ROOT . '/intl/codes/' . $secret)) {
unlink(ROOT . '/intl/codes/' . $secret);
$trusted = 'yes';
} else {
$trusted = 'no';
}
Is there another way to do it (more simplier, etc.)?
No, Only way is to use file_exists
If $secret doesn't exist in /codes/ folder, it produce Warning: unlink Is a directory How get rid of of that?
It seems $secret points to a directory. The execution path reaches to unlink because if part returns true. So it exists. To delete a directory use rmdir()
Why $trusted always give's yes even if file doesn't exist ?
Because unlink deletes it and sets $trusted to yes. When you search after deletion you see it doesn't exist but $trusted contains yes
Obviously your $secret is an empty string, but it's passing your isset() test.
So the directory ROOT . '/intl/codes/' does exist (thus passing file_exists() check), but you can't unlink() the directory (neither is it your intention here).
Make sure that you have something non-empty in $_GET['secret'] and verify your check_input() function.
P.S. You probably should remove isset($secret) part of the condition. !empty($secret) is enough here and it will fix your script.
as stated by php documentation about file_exists():
Checks whether a file or directory exists
My only guess for your question #3 is: You check if file exists and it does. Only, it's not file, it's directory.
as for #2, also as stated by the error message, you can do something like this:
$file_to_check = ROOT . '/intl/codes/' . $secret;
if (file_exists($file_to_check)) {
if( !is_dir( $file_to_check ) )
unlink($file_to_check);
else
rmdir( $file_to_check );
$trusted = 'yes';
}
and for your #1 question, you might one to do something like this:
$secret = input_get($_GET['secret']);
if(isset($_POST['register']) && !empty($secret)) {
$file_to_check = ROOT . '/intl/codes/' . $secret;
if (file_exists($file_to_check)) {
if( !is_dir( $file_to_check ) )
unlink($file_to_check);
else
rmdir( $file_to_check );
$trusted = 'yes';
} else {
$trusted = 'no';
}
}
function input_get($key, $default = ""){
if(!isset($_GET[$key])){
return $default;
} else {
//do input cleanup first, if you want
return $_GET[$key];
}
}
A little bit of explanation:
I don't know what check_input() does, so I created wrapper function for $_GET[] called input_get(). It removes the need to do isset() and also fill in the default value.
I put ROOT . '/intl/codes/' . $secret; into variable $file_to_check so that you don't have to type it again and again.

Categories