PHP: $_POST/$_COOKIE to variables - php

I've downloaded such script:
$QUERY_STRING="login";
if (file_exists("passwd.dat") && $QUERY_STRING != ""):
require ("passwd.dat");
if (!isset($alogin) || md5($pass) != $Password[$alogin] || !isset($Password[$alogin])):
$logined = 0;
//$error = "Неверный логин или пароль!<br>";
setcookie("alogin","",0);
setcookie("pass","",0);
else:
$logined = 1;
setcookie("alogin",$alogin,time()+60*60*24*30*12);
setcookie("pass",$pass,time()+60*60*24*30*12);
endif;
endif;
?>
and it works just fine on remote server, but doesn't work on local one. As I figured out, on remote machine $_POST/$_COOKIE arrays are "unpacked" to just variables, e.g. if $_POST['abc'] is defined you can access it via $abc. What mechanism is it? Just don't know where to look...

This setting is called register_globals and you should never, ever use it. You should instead modify the script so that it accesses $_POST['abc'] directly, which is the correct way.
If the script is long and/or complicated, then simply accept the fact that it is crap and find a better one.

This is called register_globals and it is depecrated as of PHP 5.3.0.

Related

Get variable from remote php function without allow_url_include on

i need to call one variable (keyword) from remote php file (config.php) --> server2
and to include in php function which is in another web server
i know by default php doesnt allow inclusion
is there any way around for me to get the variable without setting allow_url_include on
this is the function.php on server 1
<?php
include('config.php');
if ($_GET){
$req_url = $_SERVER['QUERY_STRING'];
$page = substr($req_url, strrpos($req_url, '=')+1);
$number = (int)$page;
$xurl=('https://example.com/?q=' . $keyword .'');
}
echo xurl;
?>
and here's the config.php on server 2
<?php
$base="http://example2.com";
$baseurl="http://example2.com/get.php?";
$basejson="http://example.com/function.php";
$keyword = "mountain";
?>
No, you cannot do that. It would be an extreme security gap.
If you have access to the remote webserver you may do an scp via exec and copy the file to your local server on each request. Or define a caching time and do it once every hour or whatever.

create a filter from cgi, env variables not being passed

I've got a compiled C program which is a cgi, which works fine if I call it directly from php web page with appropriate GET or POST requests.
I'm trying to have a php program call the cgi, capture the data and modify it before echoing it back to the user.
I've tried:
<?php
foreach($_REQUEST as $i => $j)
apache_setenv($i,$j);
$out = shell_exec("cgi-bin/Mycgi.cgi");
// will modify out here
echo $out;
?>
but Mycgi.cgi never sees the environment variables. Am I totally misunderstanding how this is supposed to work?
where am I going wrong?
You have to set the environment variables explicitly using putenv, before calling shell_exec in your script.
putenv("VARIABLE=value");
My solution, which works very well is:
in php build up a string with the following info (QUERY_STRING is just and example)
$qs =
'env REQUEST_METHOD=GET QUERY_STRING="Birthday=15&BirthMonth=3&BirthYear=1988" ../../cgi-bin/mycgi.cgi';
$output = '';
exec($qs,$output);
And that's all there is to it.

PHP filter_input(INPUT_SERVER, 'REQUEST_METHOD') returns null?

Why does this line return null in my live server?
filter_input(INPUT_SERVER, 'REQUEST_METHOD');
The live server is php5.5.9
Have I missed something?
I thought it is used to replace the global method below?
$_SERVER['REQUEST_METHOD'];
some of the code,
public function __construct()
{
// Construct other generic data.
$this->clientRequestMethod = filter_input(INPUT_GET, 'method'); // such as list, add, update, etc
$this->clientPostMethod = filter_input(INPUT_POST, 'method'); // such as update
$this->serverRequestMethod = filter_input(INPUT_SERVER, 'REQUEST_METHOD'); //such as get or post
}
public function processEntry()
{
// Determine the $_SERVER['REQUEST_METHOD'] whether it is post or get.
if ($this->serverRequestMethod === 'POST' && $this->clientPostMethod != null)
{
$this->processPost();
}
else if($this->serverRequestMethod === 'GET' && $this->clientRequestMethod != null)
{
$this->processRequest();
}
}
So the problem/bug is this:
filter_input() doesn't work with INPUT_SERVER or INPUT_ENV when you use FASTCGI
The bug has been known for years and I found nothing saying it was addressed. I found several work-arounds but no complete solution so I plopped the best work-around into this helper function for a project-wide solution. To provide some level of security and avoid train wrecks, the function falls back to filter_var() where filter_input() fails. It uses the same format as the native filter_input() function for easy integration into projects and easy future removal should the bug ever be fixed.
function filter_input_fix ($type, $variable_name, $filter = FILTER_DEFAULT, $options = NULL )
{
$checkTypes =[
INPUT_GET,
INPUT_POST,
INPUT_COOKIE
];
if ($options === NULL) {
// No idea if this should be here or not
// Maybe someone could let me know if this should be removed?
$options = FILTER_NULL_ON_FAILURE;
}
if (in_array($type, $checkTypes) || filter_has_var($type, $variable_name)) {
return filter_input($type, $variable_name, $filter, $options);
} else if ($type == INPUT_SERVER && isset($_SERVER[$variable_name])) {
return filter_var($_SERVER[$variable_name], $filter, $options);
} else if ($type == INPUT_ENV && isset($_ENV[$variable_name])) {
return filter_var($_ENV[$variable_name], $filter, $options);
} else {
return NULL;
}
}
This seems the best solution. Please let me know if it contains errors that might cause issues.
I had the same problem where it was working on my local machine (OSX Mavericks, PHP version 5.4.24) and not on my live server (Cent OS 5). I upgraded the server from 5.3.9 to 5.5.15 (and added the mb and mcrypt functions although that's probably irrelevant) and now it works.
This probably isn't helpful if you're on a shared host but you could ask them if they can rebuild PHP/Apache.
I was having the same issue in my XAMPP localhost as well and was looking for solutions madly. What I ended up with, it is a known PHP bug for this function if you are running the PHP in FCGI mode (FCGI/PHP 5.4 in my case). I was confirmed going through this link.
The workaround I used is to filter_var($_SERVER['PHP_AUTH_USER'], FILTER_SANITIZE_STRING) but this is not an alternative of filter_input. filter_input is more secure.
FastCGI seems to cause strange side-effects with unexpected null values when using INPUT_SERVER and INPUT_ENV with this function. You can use this code to see if it affects your server.
If you want to be on the safe side, using the superglobal $_SERVER and $ENV variables will always work. You can still use the filter* functions for Get/Post/Cookie without a problem, which is the important part!
Source: http://php.net/manual/es/function.filter-input.php#77307
I solve it changing my php.ini from:
variables_order = "GPCS"
To:
variables_order = "GPCSE"
By default PHP wasn't registering the environment variables, so this change enabled them. The interesting is that the INPUT_SERVER variables came back to work too!
Just two addiotional informations, i am using PHP 7.0.13 and as said in other answers, this issue is related to a PHP bug.
Another option is use the following:
filter_var(getenv('REQUEST_METHOD'));
My personal solution was to change filter_input to filter_var :
With filter_input (not working on a Siteground shared hosting):
filter_input(INPUT_SERVER, 'REQUEST_URI')
With filter_var (now it works on Siteground)
filter_var($_SERVER['REQUEST_URI'],FILTER_UNSAFE_RAW, FILTER_NULL_ON_FAILURE)
The problem affects Apache + fcgid + php-cgi 8.1.9 too.
It't caused by auto_globals_jit enabled (default) . When disabled (in php.ini on php startup), filter_input(INPUT_SERVER) works correctly.

php session sharing, in a desperate attempt to execute code in a different scope

I wonder why something like this wouldn't work (actually doesn't work):
4.php :
<php
session_start();
$my_id = session_id();
$_SESSION['username'] = (($_SESSION['username'] == 'nimic') ? 's-a schimbat' : $_GET['test']);
file_put_contents('comm.g', PHP_EOL.$my_id, FILE_APPEND);
sleep(3); // can be left out
echo $_SESSION['username'];
?>
4.php is a simple page that only sets the "username" component of $_SESSION, then writes the session id to a file, after which it echoes the $_SESSION['username'] value.
Then:
3.php :
<php
while(true)
{
if(file_exists("comm.g"))
{
$c = file("comm.g");
unlink("comm.g");
session_start();
foreach($c as $k => $v)
{
if($v != '')
{
$my_id = session_id();
session_write_close();
session_id($v);
session_start();
file_put_contents("result.cc", $_SESSION['username'].'---'.$v.'END'.PHP_EOL.PHP_EOL, FILE_APPEND);
$_SESSION['username'] = 'somethingelse';
session_id($my_id);
session_start();
}
}
session_write_close();
}
}
?>
3.php is run by a cronjob, every minute, for about 30 seconds (until server kills it). Anyway in result.cc I find (in those 30 available seconds) the expected result... the value of $_GET['test'].
But it does not modify the value of $_SESSION['username'], I didn't even expect such a behavior actually, I knew that sleep wouldn't be enough, but still, on a refresh shouldn't it be modified?...
I know that my code is awful, it is just a test, if it works it would be improved.
But I don't seem to figure it out. What am I doing wrong?
Actually I am doing a lot of things wrong, the system itself should not be used like this, I know that too, but still, right now this is my only option. I have more complicated ideas about this thing, but if this won't work, the others won't work either.
My intention actually is to execute code in separate thread so that I can escape some changes (like registering a wrapper for the file scheme, and having no power to unregister (restore) it when I need to, inside the wrapper class that is) that I made there. Unorthodox method, I know...
So, can you help with any ideas? Thank you.
EDIT 1
Even if lead me to an interesting idea #Ben's answer wasn't exact... Actually in cookies is kept only the session id, I replaced the need for cookies by using a file, so that the cronjob knew what session should be modified, I got the correct value for $_SESSION['username'] for any "registred" sessions, but even so, I was unable to modify the damn values, it was like they were marked readonly. Now, reconsidering, I found the idea still on it's feet, being viable, and a solution whatsoever.
So my questions still is up... WHY wouldn't it work?
Here's your problem: 3.php is run by a cronjob.
The session requires cookies, which requires a web browser and browser state. If you run the script as a cron job, there is no session.
A solution to your actual problem that you might want to consider is Runkit Sandbox: http://php.net/manual/en/runkit.sandbox.php
Ok, so here's an example of 3.php with unnecessary code removed, and "session_write_close()" added immediately after the data assignment. Don't know if it will work, but it's worth a shot. Also, a while(true) loop with nothing to slow it down when the file doesn't exist will sit there and use 100% of a cpu (until the server kills it), not to mention constant file system accesses. Really, you should be adding a sleep in there to curb it. So without further ado:
<?php
while(true)
{
if(file_exists("comm.g"))
{
$c = file("comm.g");
unlink("comm.g");
foreach($c as $k => $v)
{
if($v != '')
{
session_id($v);
session_start();
file_put_contents("result.cc", $_SESSION['username'].'---'.$v.'END'.PHP_EOL.PHP_EOL, FILE_APPEND);
$_SESSION['username'] = 'somethingelse';
session_write_close();
}
}
}
usleep(200000); // Sleep for 1/5 of a second, to avoid a 100% cpu hog and constant stream of file system accesses
}
?>

PHP voting code works on 5.2.5 but not on 5.2.11 anymore

Ok, so a little while back I had some help writing some PHP voting code, it worked just fine after I upgraded my server to use the latest version of PHP. However now I have switched servers, and the PHP isn't as up to date as the other one. Anyways here's my code:
<?php
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}
if($_GET['click'] == 'up1'){
file_put_contents('vote/1u.txt', ((int) file_get_contents('vote/1u.txt')) + 1);
header('Location: ' . $_SERVER['SCRIPT_NAME']);
die;
}
?>
Execute and display:
<img src="images/thumbsup.jpg" width="40px"border="0"> <br>Votes: <?php echo file_get_contents('vote/up1.txt'); ?>
Now when on my other server (PHP version 5.2.5) this code worked great! However on my new server the PHP version is 5.2.11, and because of this the code won't work. My question is, is there any way to make this more compatible with an earlier version of PHP, or to write completely new code that will work just like this one? Or is there a way to tell my servers to use PHP 5.2.5+? I'm using cPanel X admin panel.
I have set the text file permissions to 777 and still nothing!
you are checking for variable "click" but executing the code only if it equals "up1".
But your link tells click to equals "yes" so that part of the code is never true, hence never executed.
Change your executor to this:
<img src="images/thumbsup.jpg" width="40px"border="0"> <br>Votes: <?php echo file_get_contents('counteru.txt'); ?>
But more logically, your processing code should be rationalized a bit to this:
if the link is clicked :
First, if the data file (lu.txt) does not exist, create it and write '+1' inside of it, else, add 1 to its existing value.
Then, redirects to the initial page.
if($_GET['click'] == 'up1'){
if(!file_exists('vote/1u.txt')){
file_put_contents('vote/1u.txt', '+1');
}else{
$content = file_get_contents('vote/1u.txt');
if(!$content){
die("Error! file_get_content failed !");
}
file_put_contents('vote/1u.txt', ((int)$content) + 1);
}
header('Location: ' . $_SERVER['SCRIPT_NAME']);
}
exit;
Not a bad idea to add a trim() around file_get_contents(). Or to check if $_GET['click'] isset() prior to checking if it's equal to 'up1'.
It's conventional to exit() instead of die() after a header redirect--well, from what I've seen at least.
Basically, during development, turn on error reporting and set your error flag to E_ALL to see everything, including warnings and notices--neither of which halt your code, but should still be known and addressed.
You might discover the reason your code produces different outcomes under different minor versions of PHP by turning on full error reporting.

Categories