Detecting between the lowercase and uppercase php - php

I am using this script to delete picture from my server. But at the same time I want to protect the files in my server. Not accidentally delete but I noticed that if I typed the file index.pHp or index.Php is deleted from my server. Although setting it will not delete why php or this method not know between lowercase and uppercase.
What is not done right?
<?php
error_reporting (0);
$thefile = $_GET ['filetodel'];
$filename = "$thefile";
//$filename = "picture1.jpg";
/*protect some files*/
if ($thefile=='index.php' or $thefile=='INDEX.PHP' or $thefile=='UPLOADS.ZIP' or $thefile=='uploads.zip' or $thefile=='del.php'or $thefile=='DEL.PHP' or $thefile==NULL or $thefile=='.htaccess' or $thefile=='.HTACCESS' )
{
exit("<h2>cannot delete $thefile</h2>");
}
if ($thefile=="$thefile")
{
if (file_exists($filename))
{
unlink ("$thefile");
echo "<h2> file $thefile is delete</h2>";
}
else
{
echo "<h2>The<br>";
echo "$filename<br>";
echo "Does not exist</h2>";
}
}
?>

Just convert the input to lowercase and test it once, rather than worrying about every possible mix of case:
if (strtolower($thefile) == 'index.php') {
// ...
}
For the next iteration, you could store your protected files in an array:
$protected_files = array('index.php', 'uploads.zip', 'del.php', '.htaccess');
if (in_array(strtolower($thefile), $protected_files) || $thefile==NULL) {
// ...
}

the problem is here:
if ($thefile=="$thefile")
as if your 1st condition for file check is false than the second condition is
if ($thefile=="$thefile")
which is always true so it will unlink the file
Also add one line as below just before 1st condition
$thefile = strtolower($thefile);

Related

Perform Delete, Edit and search operation on a file using php

I have a task to do in which i have to list the directories with it's files which i did, but i don't understand how to delete file or edit specific file in the directories any help will be appreciated Thanks.
<?php
error_reporting(0);
if(isset($_GET['dir']))
{
// /$path = 'E:\xampp\\'.$_GET['dir'];
$path = $_GET['dir'];
}
else
{
$path = 'E:\xampp\\';
}
if(is_dir($path))
{
$arrDir = scandir($path);
echo "<ul>";
foreach ($arrDir as $key => $value)
{
echo "<a href='http://localhost/vishrut/FileUpload/filelist.php?
dir=".$path.'/'.$value."'>".$value.'</a><br>';
}
echo "</ul>";
}
else
{
echo "<textarea>";
echo file_get_contents($path);
echo "</textarea>"."<br>";
}
?>
There are lots of PHP's functions to handle files: https://www.php.net/manual/en/ref.filesystem.php
For your needs see these:
file_get_contents to read the entire file contents
file_put_contents to write the content in a file
unlink to delete a file
So, the steps to modify a file may be:
get the complete contents with file_get_contents:
$contents = file_get_contents($filePath);
apply your edits to the $contents content:
$newContents = ...
overwrite the file content:
file_put_contents($filePath, $newContents);
To delete a file is simple:
unlink($filePath);
It's important to note that your code is subjected to injection because you don't check the user data passed with $_GET.
If your script will be used only by you it's ok, instead you must check all user input: the first rule of Web programming is NEVER TRUST YOUR USERS! Also trusted users may write wrong characters in the url and that may have unexpected results (e.g. delete the wrong file!)
Read https://www.php.net/manual/en/mongodb.security.script_injection.php

file_exists returning false when filename is passed through a variable

I'm stumped, and I'm sure I'm missing something really basic here. Safe mode is disabled, the file exists.
This code:
$dir = "textfiles"
chdir('../'.$dir."/");
//using a Windows Slash here(Wamp Stack, on Windows 7 Dev environment
$filename = getcwd() ."\\". $row[0];
//echoing this outputs:
//C:\wamp\www\wordpress\textfiles\New Text Document.txt
$filename = str_replace("\\","\\\\",$filename);
//echoing this outputs C:\\wamp\\www\\wordpress\\textfiles\\New Text Document.txt
//escaping slashes in filename to prevent escaping. I SUSPECT my issue may be
// related to this
//if (file_exists("C:\\wamp\\www\\wordpress\\textfiles\\New Text Document.txt")) {
//Line above is commented out, but when it replaces the line below, this thing
//returns True
if (file_exists($filename)) {echo "Yes";}
else { echo $filename;}
Comment out line
/* $filename = str_replace("\\","\\\\",$filename); */
And your code should work.

move_uploaded_file moves the file into destination, but returns false, why?

I'm facing a strange situation here: I have an advanced multipart file upload script, which, for example, checks for duplicate filenames by scanning the destination folder and then renames the duplicate names with iteration number. Now, the problem here is, that for some reason, script passess with green lights if no duplicates are submitted, but if duplicate is inputted, script will return false in move_upload_file part, but however, still manage to create the proper duplicate into destination folder. I was just wondering, why and how the move_upload_file function returns false, but still proceeds moving the file?
Here is simplified snippet of the script, just trying to point you out to the problem:
<?php
//I'll loop all the files, which are submitted (in array)
foreach($_FILES['myFiles']['tmp_name'] as $key => $tmp_path) {
//Alot of stuff (most likely unrelated) happens here
//filepath contains both destination folder and filename
$filepath = $destination_folder.$filename;
if (file_exists($filepath)) {
$duplicate_filename = true;
//Some more stuff happens here. Then comes the actual moving part. Before this we have found duplicates
//for this upload file and counted proper duplicate value.
$file_increment = $num_of_filename_duplicates + 1;
while ($duplicate_filename == true) {
if(file_exists($filepath)) {
//Separate filename parts and make new duplicate name with increment value
$info = pathinfo($filename);
$basename = basename($filename,'.'.$info['extension']);
$newfilename = $basename."(".$file_increment.").".$info['extension'];
$filepath = $destination_folder.$newfilename;
//Now, this returns me false, but still creates the file into destination
if(move_uploaded_file($tmp_path, $filepath)) {
$file_success = true;
$file_increment++;
}
//So thats why this is true and I'll get the file_error
else {
$file_error = "File error: Uploading of the file failed.";
break;
}
}
else {
$duplicate_filename = false;
}
}
}
}
?>
The only reasons can be:
1) If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
2) If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
Your case seems to be 2. Try to set the following at the top of your script to see errors:
error_reporting(E_ALL);
ini_set("display_errors", 1);
Don't try to find some magic. Just debug your code.

What PHP function(s) should I use to cut off the end of a string?

I have a filename stored with the directory as a value.
Ex. /var/www/remove_this.php
In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.
There are so many string editing functions, I don't know a good approach. Thanks!
dirname() will return you the directory part of the path
Use pathinfo() to get info about the file itself.
$file = '/var/www/remove_this.php';
$pathinfo = pathinfo($file);
$dir = $pathinfo['dirname']; // '/var/www/'
You could use string functions, but for this case PHP has some smarter directory functions:
$dir = dirname('/var/www/remove_this.php'); // /var/www
pathinfo is an excellent one as well.
<?php
$file="/var/www/remove_this.php";
$folder=dirname($var);
if (!file_exsts($folder))
{
if (mkdir($folder,777,true))
{
echo "Folder created\n";
} else
{
echo "Folder creation failed\n";
}
} else
{
echo "Folder exists already\n";
}
?>

PHP not stopping the include (break)

I'm trying to get my script to find all of the PHP files in my include directory and put them in to an array (I've done the array part). Then, the script does a for loop to check if the GET request matches the current position value in the array (or whatever you want to call it).
But, if it doesn't find it at all.. it will include the default page, but obviously if it does it'll include the file it matched.
The problem is.. the break command isn't working at all. So, it's including the default page if it's been matched. Please help.
<?php
if(!defined("PLUGIN")){
echo "You cannot view this file directly.";
} else {
$glob = glob("inc/*.php");
$count = count($glob);
for($i=0;$i<$count;$i++){
$explode = explode("/", $glob[$i]);
$explode2 = explode(".", $explode[1]);
if($_GET["page"] == $explode2[0]){
include $glob[$i];
break;
} include_once "default.php";
}
}
?>
As it stands now, your loop will include the default page on EVERY iteration of the loop, until it matches that get/explode combination.
As well, using explode for analyzing file paths is poor practice. Instead, use path_info():
$found = false;
foreach ($glob as $file) {
$basename = path_info($file, PATHINFO_FILENAME);
if ($basename == $_GET['page']) {
$found = true;
break;
} else {
include($basename); // probably need to adjust this to make it a full filename
}
}
if (!$found) {
include('default.php'); // include this only if no other match was found.
}

Categories