Statement running regardless of If Statement - php

The 'unlink()' method is executed even though no images have been uploaded, why is this and how can I fix it?
If (isset($_FILES["image"]["name"])) {
move_uploaded_file($_FILES["imageUp"]["tmp_name"],
"C:/xampp/htdocs/" . $_FILES["image"]["name"]);
//if (file_exists($delete)) {
unlink($delete);
}
else {
$img = $data['row']->image_name;
}
//}

isset($_FILES["image"]["name"]
will always be set even if you upload a file or not. isset checks whether the thing is set or not. So it will always be true.
So you need to change your code :
if (isset($_FILES["image"]["name"]) && !empty($_FILES["image"]["name"])) {
move_uploaded_file($_FILES["imageUp"]["tmp_name"],
"C:/xampp/htdocs/" . $_FILES["image"]["name"]);
//if (file_exists($delete)) {
unlink($delete);
} else {
$img = $data['row']->image_name;
}
Please try with this. Hope this helps :)

According to the php documentation move_uploaded_file returns TRUE if everything went OK and FALSE if there was a problem.
So as you say, the image is not moving because move_uploaded_file is returning FALSE.
You can prove changing your code to this:
var_dump(move_uploaded_file($_FILES["imageUp"]["tmp_name"],
"C:/xampp/htdocs/" . $_FILES["image"]["name"]));
And seeing what is returning.
move_uploaded_file will return FALSE when:
The destination doesnt exists
The server doesnt have enough permissions to move the file to the destination
The file did not upload because it is bigger than the php.ini variable upload_max_filesize
The file did not upload because it is bigger than the php.ini variable post_max_size
Check and correct all those points and it should be working.

The real reason why unlink() is executed is that you've disabled the if-condition
if (file_exists($delete)) by using //.
here is the code, you may want to write:
if (isset($_FILES["image"]["name"]) && is_uploaded_file($_FILES['image']['tmp_name'])) {
move_uploaded_file($_FILES["image"]["tmp_name"],
"C:/xampp/htdocs/" . $_FILES["image"]["name"]);
if (file_exists($delete)) {
unlink($delete);
} else {
$img = $data['row']->image_name;
}
}
and make sure $delete is save! Imagine if $delete is equal to 'C:\users\your-name\some-private-file'.
If you need more help, please give us more code sourrounding this snippet.

Related

Using phpseclib to check if file already exists

I'm trying to create a script that will send across files from one server to another. My script successfully does that as well as checks if the file has something in it or not. My next step is to check whether the file already exists on the server; if the file already exists it does not send and if it does not exist, it does send.
I've tried a few different things and can't seem to get my head around it. How can I get it to check whether the file already exists or not? Any help would be appreciated!
(I had a look at some similar questions but couldn't find anything specific to my issue.)
require('constants.php');
$files = $sftp->nlist('out/');
foreach($files as $file) {
if(basename((string) $file)) {
if(strpos($file,".") > 1) { //Checks if file
$filesize = $sftp->size('out/'.$file); //gets filesize
if($filesize > 1){
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
else {
$sftp->get('out/'.$file, 'import/'.$file); //Sends file over
//$sftp->delete('out/'.$file); //Deletes file from out folder
}
else {
echo $file. ' is empty.</br>';
}
}
}
}
}
EDIT: To try and get this to work, I wrote the following if statement to see if it was finding the file test.php;
if (file_exists('test.txt')){
echo 'True';
} else {
echo 'False';
}
This returned true (a good start) but as soon as I put this into my code, I just get a 500 Internal Server Error (extremely unhelpful). I cannot turn on errors as it is on a server that multiple people use.
I also tried changing the file_exists line to;
if (file_exists('test.txt'))
in the hopes that would work but still didn't work.
Just to clarify, I'm sending the files from the remote server to my local server.
There is a closing curly brace missing right before the second else keyword.
Please try to use a code editor with proper syntax highlighting and code formatting to spot such mistakes on the fly while you are still editing the PHP file.
The corrected and formatted code:
require('constants.php');
$files = $sftp->nlist('out/');
foreach ($files as $file) {
if (basename((string)$file)) {
if (strpos($file, ".") > 1) { //Checks if file
$filesize = $sftp->size('out/' . $file); //gets filesize
if ($filesize > 1) {
if (file_exists('import/' . $file)) {
echo $file . ' already exists';
} else {
$sftp->get('out/' . $file, 'import/' . $file); //Sends file over
}
} else {
echo $file . ' is empty.</br>';
}
}
}
}
Your code checks the file exist in your local server not in remote server.
if (file_exists('import/'.$file)){
echo $file.' already exists';
}
You need to check in remote server using sftp object like
if($sftp->file_exists('import/'.$file)){
echo $file.' already exists';
}
Edit:
Add clearstatcache() before checking file_exists() function as the results of the function get cached.
Refer: file_exists

move_uploaded_file not working despite correct path and existing file

I'm really struggling with an issue relating the move_uploaded_file function of php.
The path should be correct, but see yourself:
$imgDir = "../img/".$CATEGORY;
$fileName = $_FILES['image']['name'];
$maxsize = 800;
$compQuality= 75;
if(!is_dir($imgDir)) {
mkdir($imgDir.'/tn', 0777, true);
chmod($imgDir, 0777);
chmod($imgDir, 0777);
}
$imgDir = $imgDir."/";
$imgTnDir = $imgDir."tn/";
I have also tested it by echo-ing everything and it seems to work, but when it comes to the move_uploaded_file it still does not work, even though I test if the file really exists:
if(file_exists($imgDir.$fileName)) {
$status = "The file ".$fileName." already exists, please choose a different title.";
}
if(!move_uploaded_file($_FILES['image']['tmp_name'], $imgDir.$fileName)) {
$status = "File upload failed, sorry.";
}
if(!empty($status)) {
echo $status;
exit();
}
I hope that someone can help me. If you want I can print anything out you need or give you more snippets of the code. The var $_FILES['image']['tmp_name'] does not only exist, but has a proper name by the way.
Also I have checked the php.ini and both uploading is allowed and the size is surely set high enough.
Thank you in advance.
make sure that you have the right path in $imgDir. You can try:
if(!is_writable($imgDir)) { exit('CANNOT_WRITE_IN_DIR'); }
and also you can use an absolute path, like this:
$imgDir = __DIR__ . "/../img/".$CATEGORY;

PHP uploading issues

I'm having strange issues when uploading to the server via PHP.
I get the type of the file (working properly, it shows them via echo)
$file = $_FILES['file'];
$typeFile = end(explode(".", $file['name']));
Then I make some comparasions to let them upload it or not, here are the fille types allowed
if($file['size'] <= 52428800) { //50MB, and my file is about 2,5MB
if($fileType == "nlpack" || $fileType == "nl2pkg" || $fileType == "nlpark") {
$id = add_to_db($file['name']); //Adding to database the name, this will return an id, it works
if($id) {
mkdir("uploads/".$id); //create a folder where to add the file, working fine!
if(move_uploaded_file($file['tmp_name']), ".uploads/".$id."/".$file['name']) {
echo "file uploaded correctly";
}
else {
echo "has been an error"; //it enters here, while the other file types enters in the if()
}
}
else {
echo "Has been an error";
}
} else {
//alert an error
}
}
The thing is, that "nlpack" file type doesn't uploads, and it enters the if() because I checked it with echos, while the other two are uploaded without problem.
I also check the file size, but that's running fine.
Any ideas of what is going on?
Thanks in advance
Make sure the filesize isn't exceeding the settings in your php.ini or the file will just fail to upload.
upload_max_filesize integer
The maximum size of an uploaded file.
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
AND if muliple:
max_file_uploads integer
The maximum number of files allowed to be uploaded simultaneously. Starting with PHP 5.3.4, upload fields left blank on submission do not count towards this limit.

File_exists if statement not failing

So I have this If statement that is supposed to check if the file exist and if it fail it should show a default file but the else is not triggering instead it shows "upload//"
if(file_exists($_SERVER['DOCUMENT_ROOT'] ."/uploads/".$photo['album_id'].'/'.
$photo['photo_filename']) == TRUE) {
//gets image if it exist, this part works
$imgsrc .= "../uploads/".$photo['album_id'].'/'.$photo['photo_filename'];
} else {
//gets a default image if it doesn't exist, this doesn't work
$imgsrc .='../uploads/45/image.jpg"';
}
So what happens is either the file name shows from the first part of the if state or "uploads//" shows but what does not show is the else part "../uploads/45/image.jpg". So it looks like it isn't failing.
From the php manual for file_exists
Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
to make sure that the file exist:
$filename = "/uploads/".$photo['album_id'].'/'.$photo['photo_filename'];
$filepath = $_SERVER['DOCUMENT_ROOT'].$filename;
if(file_exists($filepath) && is_file($filepath)){
$imgsrc = '..'.$filename;
}
else{
$imgsrc .='../uploads/45/image.jpg';
}
And for file_exists you don't need to == true. you can just if(file_exists($filepath)).
try this condition:
$file = $_SERVER['DOCUMENT_ROOT'] ."/uploads/".$photo['album_id'].'/'.$photo['photo_filename'];
if(file_exists($file) && !is_dir($file))

php file is writable but cannot be deleted

I am using this function. is_file and is_writable return true, but when I true to unlink, it gives an error. This is on windows server.
if(is_file($fileToDelete)) {
if(is_writable($fileToDelete)) {
unlink($fileToDelete);
}
}
The file is a PDF document, which I have open. I thought is_writable would return false in this case, but it doesn't.
So how can I tell if a file can be deleted or not?
Thank you
What about doing it the other way around? Just try to delete the file and check whether it is really gone?
#unlink($fileToDelete);
if(is_file($fileToDelete)) {
// file was locked (or permissions error)
}
Not sure whether this is workable in your specific case though, but judging by the code in your question this should be what you want.
Are you using the file? I mean, did you open it by doing fopen($file)?
Do a fclose($file) before trying to delete the file.
For them who don't want to delete the file before the check, the solution is here :
$file = "test.pdf";
if (!is_file($file)) {
print "File doesn't exist.";
} else {
$fh = #fopen($file, "r+");
if ($fh) {
print "File is not opened and seems able to be deleted.";
fclose($fh);
} else {
print "File seems to be opened somewhere and can't be deleted.";
}
}
Simple, and efficient.

Categories