simulate web interaction with python php session_start() doesn't work - php

I have the following html page
<?php session_start(); ?>
<html>
<body>
<?php
echo '<!-- cookies -->';
foreach($_COOKIE as $k => $v) {
echo '<!-- ' . $k . '=>' . $v . ' -->';
}
?>
</body>
</html>
which yields the following page source when I view the page with https://daley.ws/file1.php
<html>
<body>
<!-- cookies --><!-- PHPSESSID=>22u20jsi288vtk5epser56d2bn7leb6n --></body>
</html>
the following python code is run on my mac:
#!/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
import urllib.request
REQ_HOST = "daley.ws"
DALEY_WS = 'https://daley.ws'
DALEY_WS_FILE1 = '{}/file1.php'.format(DALEY_WS)
DALEY_WS_FILE2 = '{}/file2.php'.format(DALEY_WS)
if __name__ == "__main__":
print(DALEY_WS_FILE1)
req = urllib.request.Request(DALEY_WS_FILE1,\
unverifiable=True, origin_req_host=REQ_HOST,\
method='POST')
with urllib.request.urlopen(req) as response:
data = response.read().decode()
print('data: {}'.format(data))
and produces the following output:
https://daley.ws/file1.php
data: <html>
<body>
<!-- cookies --></body>
</html>
why is the PHPSESSID cookie not present? and how do I fix the python code so that the page produces the proper output.

There is no issue with the Python code.
When you load the page the first time in the browser, the cookie is not in the source code. But when you refresh it (the second request, but with Cookie:) it is in the source code.
It's not present in HTML, because the PHP session cookie is NOT in $_COOKIE, unless you send the cookie in the first place with HTTP header Cookie:. Try session_id() in PHP or response.getheader("Set-Cookie") in Python to get the current session cookie.

Related

Output part of the HTML file before running time-consuming commands

I'm trying to use output buffers in PHP to update the interface of the web page.
The simplified HTML structure is as follow:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>Some Header Here</h1>
<?php
ob_implicit_flush(true);
$buffer = str_repeat(" ", 4096)."\r\n<span></span>\r\n"; // to ensure the browser to print ("flush") the output
ob_start();
echo '<p>Start operation</p>' . $buffer . PHP_EOL;
ob_flush(); flush(); ob_clean();
$response = shell_exec('a_long_running_command1'); // which will execute for around 3 minutes
echo '<p>Command 1 Response: ' . $response . '</p>' . PHP_EOL;
ob_flush(); flush(); ob_clean();
$response = shell_exec('a_long_running_command2'); // which will execute for around 5 minutes
echo '<p>Command 2 Response: ' . $response . '</p>' . PHP_EOL;
ob_flush(); flush(); ob_clean();
ob_end_flush();
echo '<p>Task Complete</p>' . PHP_EOL;
?>
</body>
</html>
whereas Command 1 & 2 are CPU-intensive tasks running on a Linux-based server.
However, once entered the page, the page is blank (and the browser (Chrome) indicates it keeps loading) until Command 1 is complete. How can I display the first <h1> header and the "Start Operation" heading first?
One more greedy question: is it possible for me to display the elapsed time on the page so that the user knows the command is still running?
I know I can achieve this via AJAX calls, but I don't want the user to:
refresh the page (which might lead to Command 1 & 2 being run for more than 1 instance in the server)
know the AJAX call so that he can replay the AJAX call

Logged in user name and last name wont show on the navbar

I'm a beginner in php and I want the name and last name of the logged in user to show on my navbar. Instead it shows the php code. This is my code inside the navbar.
<?php
echo "<p>" . $_SESSION['vorname'] . " " . $_SESSION['nachname'] . "</p>";
?>
This is what it shows instead.
The output on the screen.
I changed the file extension to .php and this is what it outputs now.
PHP-Files have to be saved with the .php file extension to be executed. I suppose the other working files all have the right file extension?
You have to save all files with php code as .php.
Inside them you can use clean HTML:
<html>
<head></head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
or HTML mixed with PHP:
<html>
<head></head>
<body>
<?php echo '<h1>Hello, World!</h1>'; ?>
<?php echo '<p>You are logged as '.$_SESSION['vorname'].' '.$_SESSION['nachname'].'</p>'; ?>
</body>
</html>
And remember to use PHP server (XAMPP, WAMP) on localhost - PHP files will not work if you open them directly in web browser (i.e. file:///C:/xampp/htdocs/hello/index.php )
The notice suggests that session is not started in your script, so you need to call session_start() prior to accessing $_SESSION variable. It would also be wise to check whether the user is logged in or not:
<?php
session_start();
if (isset($_SESSION['vorname'], $_SESSION['nachname'])) {
echo "<p>" . $_SESSION['vorname'] . " " . $_SESSION['nachname'] . "</p>";
} else {
echo "<p>No user is logged in</p>";
}
?>

PHP files being run using shell_exec() accessing cookies

I am building a site that is intentionally vulnerable to LFI exploits for teaching purposes (similar to Natas). Here is my code:
File being run through CLI (/etc/flags/challenge):
<?php
//This file must be located at /etc/flags/challenge
require_once('/var/www/html/class.sqlite.php');
require_once('/var/www/html/inc.func.php');
$dbuser = base64_decode($_COOKIE['loggedin']);
$sqlite = new sqlite("/var/www/html/db/$dbuser/challenge.db");
$flag = $sqlite->getflag($dbuser);
echo "The flag is $flag";
?>
Main file:
<html>
<head>
<title>Challenge</title>
</head>
<body>
Home About
<br>
<?php
if (array_key_exists('file', $_GET)) {
$shell = shell_exec('php ' . $_GET['file']);
echo $shell;
}
?>
<!--The flag is located at /etc/flags/challenge-->
</body>
</html>
Currently, /etc/flags/challenge is not able to access the loggedin cookie. What is the best way to allow the /etc/flags/challenge to access that cookie?
You could read the cookie in the main script and then pass it as a command-line argument:
In the main file:
Add $cookie = $_COOKIE['loggedin'];, and change $shell = ... to $shell = shell_exec('php ' . $_GET['file'] . ' ' . $cookie);
In the CLI file:
Add $cookie = $argv[1];
Read this for more info on command line arguments in PHP

PHP $_server name and uri

Hi I'm trying to get a piece of html to only show on the main page which is http://www.domain.com/ ... I wrote the code below but it doesn't work the HTML is showing regardless of the page, am I missing something
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
?>
<div style="margin:0 auto;">
<div style="float:left">
<?php endif; ?>
First of all - please change
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
into
$hweb = 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$hweb may be initialized somewhere before.
Second:
As long as you request 'http://www.domain.com/somename.php' your if condition will never get executed. REQUEST_URI will always hold '/somename.php' except you use some url rewriting.
Third:
Make sure all calls go to 'http://www.domain.com' and not to 'http://domain.com'. Subdomain configurtaions sometimes are very complicated.
At the risk of getting it wrong again..
Why not initialize a variable in the main file before including the header
<?php
$mainfile = true;
?>
then in the header
<?php
if ($mainfile===true)
....
This way the main file can be called anything and be placed anywhere.
Solution 1:
If the above code is written inside 'http://www.domain.com/index.php' file then it may work fine.
Solution 2:
else make sure that $hewb is set with null value earlier b4 this code so that ".=" would not add extra value b4 'http...'.
Now
$hweb = '';
echo $hweb .= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
That is because the the HTML is inline in the php file but outside of the PHP tags. You can simply echo the HTML inside the if.
if ($hweb == 'http://www.domain.com/')
{
echo '<div style="margin:0 auto;">';
echo '<div style="float:left">';
}
or if you have lots of HTML you could do it like this
<?php
ob_start();
?>
<html>
<body>
<p>This HTML only be echoed </p>
</body>
</html>
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
{
ob_end_flush();
}
else
{
ob_end_clean(); // Probably not needed
}
?>

Why doesn't file_get_contents work?

Why does file_get_contents not work for me? In the test file code below, it seems that everyone's examples that I've searched for all have this function listed, but it never gets executed. Is this a problem with the web hosting service? Can someone test this code on their server just to see if the geocoding array output actually gets printed out as a string? Of course, I am trying to assign the output to a variable, but there is no output here in this test file....
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
Check file_get_contents PHP Manual return value. If the value is FALSE then it could not read the file. If the value is NULL then the function itself is disabled.
To learn more what might gone wrong with the file_get_contents operation you must enable error reporting and the display of errors to actually read them.
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
You can get more details about the why the call is failing by checking the INI values on your server. One value the directly effects the file_get_contents function is allow_url_fopen. You can do this by running the following code. You should note, that if it reports that fopen is not allowed, then you'll have to ask your provider to change this setting on your server in order for any code that require this function to work with URLs.
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
# Enable Error Reporting and Display:
error_reporting(~0);
ini_set('display_errors', 1);
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>', $url, '</p>';
$jsonData = file_get_contents($url);
echo '<pre>', htmlspecialchars(substr($jsonData, 128)), sprintf(' ... (%d)', strlen((string)$jsonData)), '</pre>';
# Output information about allow_url_fopen:
if (ini_get('allow_url_fopen') == 1) {
echo '<p style="color: #0A0;">fopen is allowed on this host.</p>';
} else {
echo '<p style="color: #A00;">fopen is not allowed on this host.</p>';
}
# Decide what to do based on return value:
if ($jsonData === FALSE) {
echo "Failed to open the URL ", htmlspecialchars($url);
} elseif ($jsonData === NULL) {
echo "Function is disabled.";
} else {
echo '<pre>', htmlspecialchars($jsonData), '</pre>';
}
?>
</body>
</html>
If all of this fails, it might be due to the use of short open tags, <?. The example code in this answer has been therefore changed to make use of <?php to work correctly as this is guaranteed to work on in all version of PHP, no matter what configuration options are set. To do so for your own script, just replace <? or <?php.
If PHP's allow_url_fopen ini directive is set to true, and if curl doesn't work either (see this answer for an example of how to use it instead of file_get_contents), then the problem could be that your server has a firewall preventing scripts from getting the contents of arbitrary urls (which could potentially allow malicious code to fetch things).
I had this problem, and found that the solution for me was to edit the firewall settings to explicitly allow requests to the domain (or IP address) in question.
If it is a local file, you have to wrap it in htmlspecialchars like so:
$myfile = htmlspecialchars(file_get_contents($file_name));
Then it works
Wrap your $adr in urlencode().
I was having this problem and this solved it for me.
//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:
sudo chmod 775 file.jpeg
and then you can access if the above mentioned problems are not your case.

Categories