Track urls using php and mysql - php

How to track the page views and ip address of the short url this code is creating. thanks in advance.
PHP Code
<?php
//include database connection details
include('db.php');
//redirect to real link if URL is set
if (!empty($_GET['url'])) {
$redirect = mysql_fetch_assoc(mysql_query("SELECT url_link FROM urls WHERE url_short = '".addslashes($_GET['url'])."'"));
$redirect = "http://".str_replace("http://","",$redirect[url_link]);
header('HTTP/1.1 301 Moved Permanently');
header("Location: ".$redirect);
}
//
//insert new url
if ($_POST['url'] && $_POST['url'] != 'http://') {
//get random string for URL and add http:// if not already there
$short = substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 5);
mysql_query("INSERT INTO urls (url_link, url_short, url_ip, url_date) VALUES
(
'".addslashes($_POST['url'])."',
'".$short."',
'".$_SERVER['REMOTE_ADDR']."',
'".time()."'
)
");
$redirect = "?s=$short";
header('Location: '.$redirect); die;
}
<h1> URL to shrink: </h1>
<form id="form1" name="form1" method="post" action="">
<input name="url" type="text" id="url" value="http://" size="75" />
<input type="submit" name="Submit" value="Go" />
</form>
<!--if form was just posted-->
<?php if (!empty($_GET['s'])) { ?>
<br />
<h2>Here's the short URL: <?php echo $server_name; ?><?php echo $_GET['s']; ?></h2>
<?php } ?>
.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php?url=$1 [L,QSA]

You'll need to create a separate table for keeping a count of the hits and IP's your shortened URL's are getting. Create a table (let's call it "hits") containing url_id and ip_address as it's columns.
Inside your if (!empty($_GET['url'])) condition, make an insert into the hits table with the ID of the URL it has requested and the IP address the request came from.

How to track the page views and ip address of the short url this code is creating.
Enable logging in your webserver and then use a log file analyzer that will give you that information (most common logfile analyzers do have the info you're looking for).

Related

How to submit a form by appending textbox value to URL in PHP?

I have a HTML form containing a textbox and a submit button. When I submit the form, I want textbox value appending to the URL.
For example, if my domain is http://www.example.com/ and form lies on index.php. Suppose textbox value is "test" then when the form is submitted the URL should change to http://www.example.com/test. How can we achieve it?
HTML Code:
<form method="post" action="">
<input type="text" name="txtname" value="<?php echo $name; ?>" />
<input type="submit" name="btnsubmit" value="Submit" />
</form>
PHP Code:
<?php
$name = NULL;
if(isset($_POST['btnsubmit']))
{
$name = $_POST["txtname"];
}
?>
.htaccess Code:
# .htaccess mod_rewrite
# example.com
#Enable mod rewrite
Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
How about a jQuery solution? Something like...
$(document).ready(function(){
var txtname = $('#txtname').val();
var url = window.location.href;
var new_url = url + "/" + txtname;
$('#formid').on('submit', function(e){
e.preventDefault();
// Do what you need to do here.
console.log(new_url);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formid" method="post" action="">
<input id="txtname" type="text" name="txtname" value="testname" />
<input type="submit" name="btnsubmit" value="Submit" />
</form>
You could use header:
$name = $_POST['txtname'];
header('Location: http://www.example.com/$name');
If you want to get the value without the error you can set the variable to empty like this:
$name = isset($_POST['txtname']) ? $_POST['txtname'] : '';
Place that after your opening php tag.

PHP: Validating Form When Routing

I'm trying to validate a form that's being submitted through a PHP router.
All my traffic is sent to index.php via htaccess. to index.php:
RewriteEngine On
RewriteBase /router
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /divbase/index.php?/$1 [L]
index.php then provides the appropriate content:
<?php
Router::get('/form', function() {
include 'content/form.php';
});
?>
so when you go to example.com/form, the form page is loaded:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
However, when I try to submit the form on that page it 404s. After doing some troubleshooting, it looks like the PHP thinks that the form is being submitted to index.php rather than form.php.
I've tried to set the form action to:
<?php "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
But it still 404s. Does anyone have any suggestions for this?
You need to add another route for POST, for example...
Router::get('/form', function() {
include 'content/form.php';
});
Router::post('/form', function() {
echo 'Hello world';
});
Your form is using method="post" so you need to add a POST route

Remove question mark added to url using form 'get' method

I am using a form and the 'get' method to offer users a return option to an unknown url that they came from within my site, as per the code below. I prefer this to just the browsers back button and it works without javascript.
The problem I am having is that some browsers (chrome, safari, there may be others) are adding a question mark to the end of the url they are referred back to. I don't want this for seo reasons.
My question is either:
1) Can I prevent the question mark within my php code somehow; or
2) Please could somebody show me how to redirect the url using htaccess, I potentially have urls that could end:-
.html?
.htm?
.php?
/?
Thanks in advance.
<?php
if (isset ($_SERVER['HTTP_REFERER']) ) {
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo '<br /><form action="' . $url . '" method="get">
<div id="submit"><input type="submit" value="Return to previous page" /></div>
</form>';
}
?>
The ? probably gets added because you're doing a GET request from a form.
Why not do something like:
<input type="button" onclick='document.location.href=<?php echo json_encode($url);?>'>;
use POST method instead of GET
Is it pertinent that you use a form for this? Why not use a hyperlink and style it to look however you want with CSS?
You could use try using a button instead of creating an input value that will be passed.
<form action="url" method="get">
<button type="submit">Return to previous page</button>
</form>
Instead of posting to random URLs (which is not really a good idea) consider using redirects
A solution would be
<?php
if (isset ($_SERVER['HTTP_REFERER']) ) {
$url = htmlspecialchars($_SERVER['HTTP_REFERER'],ENT_QUOTES,'UTF-8');
echo '<br /><form action="redirect.php" method="get">
<input type="hidden" name="return" value="'.$url.'">
<div id="submit"><input type="submit" value="Return to previous page" /></div>
</form>';
}
?>
then in redirect.php
<?php
if (isset ($_GET['return'] ) {
$url = $_GET['return'];
header('Location: '.$url, true, 303); // or 302 for compatibility reasons
echo 'Continue';
exit;
}else{
echo 'Error, no redirect specified';
}
you can replace action="GET" and $_GET with action="POST" and $_POST and it will work the same.
or simply
if (isset ($_SERVER['HTTP_REFERER']) ) {
$url = htmlspecialchars($_SERVER['HTTP_REFERER'],ENT_QUOTES,'UTF-8');
echo 'Return to previous page';
}
both will still create a new history entry in the browser.
In the htaccess you should have something like this:
RewriteEngine on
RewriteRule ^myPage-([a-zA-Z0-9_]*).html myPHPfile.php?var=$1
By the above piece added to your htaccess, when a URL like myPage-whatever.html is called, it's just like calling myPHPfile.php?var=whatever

$_POST Empty with .htaccess

I was searching now quite a bit on the internet but can not find any solution.
I have an .htaccess file, which rewrites my query string into the GET variable.
This works absolutely fine.
when it comes to the POST variable, it is the first time I get into this trouble.
I have used this .htaccess file already a lot of times on different servers, but now one of my client's server doesn't want to work.
When ever I post a form the whole POST variable is empty... I will post my .htaccess file, any help is appreciated.
Options +FollowSymLinks
Options +Indexes
RewriteEngine on
RewriteBase /
RewriteRule ^pages.*$ /error/404 [L]
RewriteRule ^classes.*$ /error/404 [L]
RewriteRule ^templates.*$ /error/404 [L]
RewriteRule ^common.*$ /error/404 [L]
RewriteRule ^([A-Za-z0-9-_]+)/?$ /?p=$1&s=index&a=index&n=index&%{QUERY_STRING} [L]
RewriteRule ^([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ /?p=$1&s=$2&a=index&n=index&%{QUERY_STRING} [L]
RewriteRule ^([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ /?p=$1&s=$2&a=$3&n=index&%{QUERY_STRING} [L]
RewriteRule ^([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ /?p=$1&s=$2&a=$3&n=$4&%{QUERY_STRING} [L]
RewriteRule ^([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/([A-Za-z0-9-_]+)/?$ /?p=$1&s=$2&a=$3&n=$4&o=$5&%{QUERY_STRING} [L]
ErrorDocument 404 /error/404.php
the form looks like this
<div class="login">
<form action="/administrator" method="post">
<table cellspacing="0" cellpadding="0" width="100%">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="passwort" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Anmelden" /></td>
</tr>
</table>
</form>
</div>
and the login php file like this
<?php
session_start();
if( isset($_SESSION['login']) && $_SESSION['login'] === TRUE ) {
header('Location: /administrator');
exit;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$passwort = $_POST['passwort'];
$hostname = $_SERVER['HTTP_HOST'];
$path = dirname($_SERVER['PHP_SELF']);
if ($username == 'xxx' && $passwort == 'xxx') {
$_SESSION['login'] = true;
header('Location: /administrator');
exit;
}
}
?>
Your RewriteRule are active for GET, not for POST.
check if your /administrator script (why haven't you called it directly as administrator.php?) is called or create a rule for its access. Check in the access log to be sure you're calling the script when you post to it.
Add something like :
RewriteRule ^administrator administrator.php [L]
or RewriteRule ^administrator pathtoyourscript/administrator.php [L]
check without session to be sure it's not interacting badly with it.
You can use var_dump($_POST) to display all data. If there is no display, you've not called the right script or your path is wrong.

integrating tiny url with codeigniter

I have PHP code for shortening a URL. I want to integrate it with CodeIgniter. How can I do this?
I have 3 pages: index.php, page.php and a .htaccess file and one database backup file.
index.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$url=$_GET['url'];
$url_details=mysql_fetch_array(mysql_query("select * from tinyurls where shorturl like ('".$url."')"));
if(!empty($url_details)){
header("location: ".$url_details['actualurl']);
}else{
echo '<h2 style="color:red">Error 404: Page not found</h2>';
}
?>
page.php
<?php
if(isset($_POST['url'])){
mysql_connect("localhost","root","");
mysql_select_db("test");
$exist=mysql_fetch_array(mysql_query("select * from tinyurls where actualurl='".$_POST['url']."'"));
if(empty($exist))
{
function get_random_word($length=6){
$chars='abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$word="";
for($i=0;$i<$length;$i++){
$word.=substr($chars,rand(1,strlen($chars)),1);
}
$isexist=mysql_fetch_array(mysql_query("select id from tinyurls where shorturl like ('".$word."')"));
if(empty($isexist)){
return $word;
}else{
return "";
}
}
$tiny_word="";
while($tiny_word==""){
$tiny_word=get_random_word();
}
mysql_query("insert into tinyurls set shorturl='".$tiny_word."', actualurl='".$_POST['url']."'");
}else{
$tiny_word=$exist['shorturl'];
}
echo "TinyURL: http://".$_SERVER['SERVER_NAME']."/tinyurl/".$tiny_word."<br/><br/>";
}
?>
<html>
<head><title>Shorten URL</title></head>
<body>
<form method="post" action="">
Enter the URL:<br/>
<input type="text" name="url" style="padding:5px;width:500px"/><br/><br/>
<input type="submit" style="padding:5px" value="Shorten URL">
</form>
</body>
</html>
.htaccess file
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^p\/(.*)$ page.php?q=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
How can I integrate it with CodeIgniter?
when iam integrating this with codeigniter the controller goes to the home page of my site not to the original url
In your code you're just echoing the URL instead of redirecting it:
header('Location: http://' . $_SERVER['SERVER_NAME'] . '/tinyurl/' . $tiny_word);

Categories