PHP dynamically generated hit counter - php

I am a total PHP novice and am trying to write what I think is a pretty simple script. This is the code I have so far:
HTML / PHP
<?php
$hits = file_get_contents('hits.txt');
++$hits;
file_put_contents('hits.txt', $hits);
echo $hits;
$url = $_GET['w'];
?>
<iframe src="<?php echo $url; ?>"></iframe>
<p>
<?php echo $hits; ?>
</p>
The result is a page with an iframe and a hit counter.
The problem with this script is that if the variable $url changes, the hit counter does not. My goal would be that if I visited http://www.website.com/index.php?w=blue.html I would get a different counter than if I visited http://www.website.com/index.php?w=yellow.html.
EDIT: I should add that this script is designed to accept any URL. I realize this complicates things significantly. My ultimate goal would be that if the counter didn't already exist for that particular URL, it would be generated on the fly.

Your current code saves the hit points for every page to the same file as a simple string.
You have a number of options. Here's one that would work if you prefer to stick with text files instead of databases.
You could take the URL in, hash it, and save the counter for that page in a hash-named text file.
Something like
if( isset($_GET) && !empty($_GET['W']) ){
$url = md5($_GET['w']);
$hits = file_get_contents('/hit_counters/'.$url.'.txt');
$hits++;
file_put_contents('/hit_counters/'.$url.'.txt', $hits);
}
and then later you could echo out the hits under that or pull the hits in on another script and echo like that.
If you need it to create new ones on the fly, you could add something like
if(!is_file('/hit_counters/'.$url.'.txt')){
$fh= fopen('/hit_counters/'.$url.'.txt', 'w');
fwrite($fh, '1');
fclose($fh);
}
NOTE
This could end up creating a ton of tiny text files, though. So be aware. If you are worried about that, you would really need to look into a database or read in a text file line by line to find the same hash.
TO IMPLEMENT
Replace the top part of your code within the <?php ?> with the following:
if( isset($_GET) && !empty($_GET['W']) ){
$url = md5($_GET['w']);
if(!is_file('/hit_counters/'.$url.'.txt')){
$fh= fopen('/hit_counters/'.$url.'.txt', 'w');
fwrite($fh, '1');
fclose($fh);
}else{
$hits = file_get_contents('/hit_counters/'.$url.'.txt');
$hits++;
file_put_contents('/hit_counters/'.$url.'.txt', $hits);
}
}
This will take the page name in, hash it, check to see if /hit_counters/THEHASH.txt exists, and create it if not or add +1 to it otherwise. A hash is sort of like encryption, but not really. It will change your $_get['w'] into a longer random-looking string.

You're writing the same hits.txt file regardless of what $_GET['w'] is set to. Try putting the hits.txt file in a folder like this:
<?php
$url = $_GET['w'];
$dir = str_replace(".html", "", $url);
$hits = file_get_contents($dir.'/hits.txt');
++$hits;
file_put_contents($dir.'/hits.txt', $hits);
echo $hits;
?>
<iframe src="<?php echo $url; ?>"></iframe>
<p>
<?php echo $hits; ?>
</p>

Related

Simple Snippet to read and show content from file

I am looking for a simple solution to add a Snippet in my index.php file to load and display the content shown in a file from an other Domain.
Plan was to add the Code to the 'Footer' before to show a floating ad on several of my websites.
Sourcesite: http://domainX.tld/floating/floater.txt
Content of file: little bit css for styling of the ad + script snippet for a close button + html to get it into shape.
Target Site gets a simple snippet to show content from txt file as its own content.
I have tried by now
<?php
$StrLessDescription = ("//domainX.tld/floating/floater.txt");
$file_contents = file_get_contents($StrLessDescription);
?>
Site loads but doen't shows anything of my code.
<?php
$handle = fopen("//domainX.tld/floating/floater.txt", "rb");
$delimiter = ",";
while (!feof($handle) ) {
$line = fgets($handle);
$data = explode($delimiter, $line);
foreach($data as $v) {
echo $v;
}
}
fclose($handle);
?>
Site wouldn't even load.
<?php
$f = fopen("//domain.tld/floating/floatr.txt", "r");
// Read line by line until end of file
while(!feof($f)) {
echo fgets($f) . "<br />";
}
fclose($f);
?>
Creates an endless amount of where my Code should be
Other Fails i have deleted already.
Once i had a simple snippet that had done the trick, does one have any idea how to accomplish that again?
This should do the trick:
<?php
echo file_get_contents('//domain.tld/floating/floatr.txt');
Sticking to the straightest way to do it as your intention is and supposing that:
URL you provide for the txt file is correct
you have read access to it
the file has contents to display
your PHP version is (PHP 4 >= 4.3.0, PHP 5, PHP 7) to support
the file_get_contents() function
You are missing in your first approach to echo the contents of your variable $StrLessDescription to send it to output.
<?php
$StrLessDescription = ("//domainX.tld/floating/floater.txt");
$file_contents = file_get_contents($StrLessDescription);
echo $file_contents;
?>
Remember that for large projects you could consider using a framework to achieve the same goal in a more organized way. This is a solution to a quick-and-dirty approach you inquiry.

PHP include inside of an existing code?

Here's my code:
<?php
if(isset($_GET['p']))
{
$nshortname = strip_tags($_GET['p']);
$check = mysql_query("SELECT * FROM pages WHERE `shortname` = '$nshortname'");
if(mysql_num_rows($check) == 0)
{
echo '<center><font size="50" style="font-weight:bold;">404</font><br>Appears this page is a dead end</center>';
}
else
{
$h = mysql_fetch_array($check);
//post details
$title = $h["title"];
$content = $h["content"];
$shortname = $h["shortname"];
// Start of page content
echo '
<p>
<font size="5pt">'.$title.'</font><br><hr>
'.$content.'<br>
';
// End of page content
}
}
else
{
echo 'No page has been selected to view';
}
?>
What it does exactly, is it grabs pages from my database and reads them, so for example if I have a page in that table called "test" I can go to it by http://mylink.com/?p=test. Although i've come up with an issue. On one of those pages that come from the database I want to include but when I type it into the database field and go back to the page it shows with nothing.
I went to the source of the page in my browser and found out the code turned into <!--?php include "inc/extra/plugins/header/slideshow.php"?-->
Does anyone know how I can sold it from turning into <!--? and make my include code work.
I would caution against using eval() of unknown content. Basically, the content comes from your database, but that doesn't guarantee it's safe to execute as code! There are a lot of ways it could cause errors or do something malicious.
But you also have other dangerous security gaffes in your code. You should learn about how to defend against SQL injection vulnerabilities and Cross-Site Scripting (XSS) vulnerabilities and File Inclusion vulnerabilities.
Use mysql_real_escape_string() if you are still using the deprecated ext/mysql. But if you can, switch to mysqli or PDO_mysql and use prepared statements with parameters.
Always output dynamic content with htmlspecialchars(). What if the content contains Javascript code? It could cause mischief.
Never eval() arbitrary content as code. You have no control over what that content is, or what it could do when you execute it.
Be as restrictive as possible - if you want to include a file, store the filename separately from content (e.g. in a separate column), and use it only for including files.
Here's an example with some of these problems fixed in your code:
<?php
if(isset($_GET['p']))
{
$nshortname = mysql_real_escape_string($_GET['p']);
$check = mysql_query("SELECT * FROM pages WHERE `shortname` = '$nshortname'");
if(mysql_num_rows($check) == 0)
{
echo '<center><font size="50" style="font-weight:bold;">404</font><br>Appears this page is a dead end</center>';
}
else
{
$h = mysql_fetch_array($check);
//post details
$title = htmlspecialchars($h["title"]);
$content = htmlspecialchars($h["content"]);
$shortname = $h["shortname"];
// Start of page content
echo '
<p>
<font size="5pt">'.$title.'</font><br><hr>
'.$content.'<br>
';
// End of page content
// Start of include
if ($h["include"]) {
// strip out anything like "../../.." etc.
// to make sure this is only a simple filename.
$include = basename($h["include"]);
include "inc/extra/plugins/header/{$include}.php";
}
// End of plugin inclusion
}
}
else
{
echo 'No page has been selected to view';
}
?>
Also check out http://www.sitepoint.com/php-security-blunders/ and http://phpsec.org/projects/phpsecinfo/
Re your comments:
To allow a limited set of basic HTML, the best tool you need to use is http://htmlpurifier.org
I'm not sure what to say about your include displaying code instead of working. I just tested this, and the following two files seem to work exactly as intended:
foo.php:
<?php
echo "<h1>START FOO</h2>";
if ($_GET["include"]) {
$include = basename($_GET["include"]);
include "./{$include}.php";
}
echo "<h1>END FOO</h2>";
bar.php:
<?php
echo "<h2>BAR</h2>";
If you have a variable $content which is html with php, you can use
eval("?>" . $content . "<?php");
This will output $content having processed all the <?php ?> tags.

PHP: How to get only the current folder of a website

For example I have a website that points to a page like this:
http://www.mysite.com/folder/file
How can I get determine /folder so that I can go further an quote an if statement like
if /folder then echo something
Why do I need this?
I am trying to tell facebook which image to pick from a page. Actually I have a pretty simple page structure and the image that facebook should take is always at first but somehow it does choose another one from time to time. I guess because the other images are loaded faster. And the old way to rel="img_src" doesn't seem to work anymore as that I could just add it to the wanted image.
So well of course I use the open graph protocol to tell facebook which Image it should use.
I am working with a cms were I can output the path of the image depending on the id the image has. I have two different id's for the different kind of pages living in two different folders.
This leads to:
if index --> echo meta og for index img
else if /folderone (with id1) --> echo meta og for id1
else if /foldertwo (with id2) --> echo meta og for id2
This is why I need to know the foldername.
Now with the answer I have following setup, just that you know:
<?php $folder = dirname($_SERVER['SCRIPT_NAME']); ?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/") echo "<meta property='og:image' content='http://www.mysite.com/img/img.jpg'/>" ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderOne") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id1}'/> " ;?>
<?php if (dirname($_SERVER['SCRIPT_NAME']) == "/folderTwo") echo "<meta property='og:image' content='http://www.mysite.com/img/{$img_id2}'/> " ;?>
parse_url &
explode
$path = parse_url($url, PHP_URL_PATH);
gives you
/folder/file
then you can explode() to separate the path values and check the first one to see if it is 'folder'
Example here: http://tehplayground.com/#7TIKAwp6J
Example code:
$url = "http://www.mysite.com/folder/file";
$path = parse_url($url, PHP_URL_PATH);
$arr = explode("/",$path);
echo $arr[1]; // leading slash makes [0] ""
outputs
folder
$script = $_SERVER['SCRIPT_NAME'];
echo dirname($script);
Possibly use "get current working directory" function getcwd()?
Explode it by directory separator.
Then grab the last element like this:
$var = getcwd();
$var = explode('\\', $var); // your OS might use '/' instead
$var = end($var);
I suppose this assumes you're not using some kind of MVC framework that uses routing.
I hope that helps!
I think this is nicer than exploding the string:
function getCurrentDirectory(){
$curDirPath = getcwd();
return substr($curDirPath, strrpos($curDirPath, '/') + 1);
}
getcwd() gives you the current directory's path, and then you can truncate it starting right after the last occurrence of the / in its file path.
$dir_list = explode('/', dirname($_SERVER['SCRIPT_FILENAME']));
$this_folder = $dir_list[count($dir_list)-1];
...
if ($this_folder) == "folderOne") echo "...."
...
if(dirname('yoursite/folder')){

PHP SESSIONS Problem

I have two scripts but I can't make them work together.
1- A simply page views counter
<?php
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];
?>
2 - A Random link from a list but without repeat the links
<?php
if (empty($_SESSION['links'])) {
// first time visit, populate random links in session
$links = array('http://some-site.com', 'http://some-other-site.com', 'http://example.com');
shuffle($links);
$_SESSION['links'] = $links;
}
$link = array_shift($_SESSION['links']);
$_SESSION['links'][] = $link;
?>
For some reason if I use one of them the other will stop to work, both had worked fine but I can't make them work together on the same site.
On the header I have <?php session_start(); ?> but I also moved the script to different parts of the site and I get always the same problem, one stop to work. I also had the <?php session_start();?> at the start of each piece of code but nothing seems to work.
At some point I manage to make both scripts work but the page views counter script was counting from 3 to 3, not from 1 to 1 - Note that the random link script have also 3 values on it; so my guess is that something is incompatible with both scripts
Any help and guide in how or where I need to place the code will be appreciated.
Thanks and sorry for my English
Daniel
try is on the top of the code
just add "$_SESSION['views'] = 0;" to the top once when u run the main script i think it will work
$_SESSION['views'] = 0;
if (empty($_SESSION['links'])) {
// first time visit, populate random links in session
$links = array('http://some-site.com', 'http://some-other-site.com',
'http://example.com');
shuffle($links);
$_SESSION['links'] = $links;
}
$link = array_shift($_SESSION['links']);
$_SESSION['links'][] = $link;
echo "<pre>";
print_r($_SESSION['links']);
echo "</pre>"
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Pageviews=". $_SESSION['views'];

PHP: How do I display the contents of a textfile on my page?

I have a .txt file on my web server (locally) and wish to display the contents within a page (stored on the same server) via PHP echo.
The .txt file contains a number that is updated by another script on another page, but for this page I just want to pull the number/txt file contents from the file and echo it (to save the page having to do the calculation involved in getting the number again).
How can I do this?
Here's what I've got so far:
<?php
$myFile = "http://renownestates.com/cache/feedSubscribers.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 1);
fclose($fh);
echo $theData;
?>
Here, try this (assuming it's a small file!):
<?php
echo file_get_contents( "filename.php" ); // get the contents, and echo it out.
?>
Documentation is here.
For just reading file and outputting it the best one would be readfile.
If you aren't looking to do anything to the stuff in the file, just display it, you can actually just include() it. include works for any file type, but of course it runs any php code it finds inside.
I had to use nl2br to display the carriage returns correctly and it worked for me:
<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>
I have to display files of computer code. If special characters are inside the file like less than or greater than, a simple "include" will not display them. Try:
$file = 'code.ino';
$orig = file_get_contents($file);
$a = htmlentities($orig);
echo '<code>';
echo '<pre>';
echo $a;
echo '</pre>';
echo '</code>';
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Try this to open a file in php
Refer this: (http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)
if you just want to show the file itself:
header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);
Use PHP's fopen

Categories