In this tutorial, you'll learn how to get current web page url from your web browser address bar using php script.

Syntax

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

Overview

In this tutorial, you'll learn 2 functions in php to get full url from address bar.
1. $_SERVER['HTTP_HOST']
2. $_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST'] - This function will show only server name.
$_SERVER['REQUEST_URI'] - This function will show you the path to file of your url.

Code

url

In the image is a url from apple website. When you run $_SERVER['HTTP_HOST'];you'll get result "www.apple.com" only, no "http://" no "/downloads/dashboard/email_messaging/todo.html"

<?php 
$server=$_SERVER['HTTP_HOST'];
echo $server;
?>

You'll get this is result 
www.apple.com
When you run the script "$_SERVER['REQUEST_URI']" you'll get the result below.
no "http://" and no "www.apple.com

Sample 

<?php
$request_url=$_SERVER['REQUEST_URI'];
echo $request_url;
?>


This is a result when you run $_SERVER['REQUEST_URI']
/downloads/dashboard/email_messaging/todo.html
To get full URL from this site you, we have to use (.) to connect 2 functions together and create http:// by yourself.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

Display URL in text box (included javascript, click to select all text in text box)

youtube urlThis is an example of javascript and php script, click to select all text in text box like youtube.com or many other site.

############### Code
<html>
<head>
<title>Get url for address bar</title>
<script type="text/javascript">
function select_all()
{
var text_val=eval("document.form_name.type");
text_val.focus();
text_val.select();
}
</script>
</head>
<body>
<form name=form_name method=post action=''''>
<input name="type" type="text" id="type" value="
<?php $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo $url; ?>" size="50" onClick="select_all();">
</form>

</body>
</html>

Automatic refresh webpage / Set time to redirect


When you need your web page automatically refresh in 5 second or any second you want, you can use this meta tag. It's a simple code, put it between tag ... on your web page. 

This script is easy but powerful. Many websites use this script to redirect their web page or refresh the same page, for example, my website updates in every 10 minutes and I want to show user my latest content then I put this script to my page and set it refreshs in every 10 minutes.

Code

<HEAD>
<meta http-equiv='refresh' content='2;url='file_name or URL'>
</HEAD>
// content = time (second). 
// file_name = name of file you want to refresh or redirect. 
// URL = URL of website that you want to redirect to.
In this tutorial, create 1 PHP file for testing this code.
1. user_online.php 

Steps
1. Create table "user_online" in mysql in database "test".
2. Create file user_online.php.

STEP1: Create table "user_online"


CREATE TABLE `user_online` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'
) TYPE=MyISAM;

STEP2: Create file - user_online.php

############### Code
<?php

session_start();
$session=session_id();
$time=time();
$time_check=$time-600; //SET TIME 10 Minute
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="user_online"; // Table name
// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE session='$session'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count=="0"){

$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";
$result1=mysql_query($sql1);
}

else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";
$result2=mysql_query($sql2);
}
$sql3="SELECT * FROM $tbl_name";
$result3=mysql_query($sql3);
$count_user_online=mysql_num_rows($result3);
echo "User online : $count_user_online ";
// if over 10 minute, delete session 
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";
$result4=mysql_query($sql4);
// Open multiple browser page for result


// Close connection
mysql_close();
?>

The PHP Code

The following PHP code example posts to http://www.example.com/path/to/form sending three sets of values.
<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/path/to/form");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);

$data = array(
    'foo' => 'foo foo foo',
    'bar' => 'bar bar bar',
    'baz' => 'baz baz baz'
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

CURLOPT_RETURNTRANSFER

The "curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);" line is not actually necessary but it means the HTML from the web page returned goes into the $output variable rather than echoed out to standard output.

CURLOPT_POST

The "curl_setopt($ch, CURLOPT_POST, true);" line tells CURL that this is POST instead of the default GET.'

CURLOPT_POSTFIELDS

The $data array contains the POST field values. The first of these has the name 'foo' and value 'foo foo foo'; the equivilent HTML form value for this might be something like <input type='hidden' name='foo' value='foo foo foo' />
The post field values are then set with the "curl_setopt($ch, CURLOPT_POSTFIELDS, $data);" line. $data can optionally be a string formatted in the same way a GET string is (e.g. foo=foo+foo+foo&bar=bar+bar+bar etc) but I find it easier to use an array.

curl_getinfo()

The "$info = curl_getinfo($ch);" is also not required but returns an array of useful data about the request. Example output from the above would look something like so:
Array
(
    [url] => http://www.example.com/path/to/form
    [content_type] => text/html; charset=UTF-8
    [http_code] => 200
    [header_size] => 516
    [request_size] => 197
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 2.256708
    [namelookup_time] => 0.672754
    [connect_time] => 0.899986
    [pretransfer_time] => 0.900012
    [size_upload] => 240
    [size_download] => 18717
    [speed_download] => 8293
    [speed_upload] => 106
    [download_content_length] => 0
    [upload_content_length] => 240
    [starttransfer_time] => 1.12957
    [redirect_time] => 0
)
Getting the http_code from the information can be useful so you know if it successfully connected to the page before parsing any of the return data.
What is JSON:- 
JSON also known as JavaScript Object Notation is a easy way to serialize data for passing through mediums that do not recognized complex data types. JSON is becoming the most popular format for information exchange. Because JSON is widely used for exchanging information across websites and web applications. The web services send and accept serialized data.  JSON is designed for JavaScript. This makes it an excellent choice for web services and AJAX requests. PHP 5.2 is bundled with compiled JSON extension.

json_encode:-
Json encode is used for encoding the data that contain string, numbers etc. json_encode return the value that is recognized by JSON. On other hand we use json_decode to decode this json representational value and use in our code.

json_decode:-
Json decode is used for decoding the value send by the json_encode.

Example:- 
Json process is divided in to two parts:
In first part we create json data using php array and encode this with json_encode.
In second part we receive the the json encoded data and decode this with help of json_decode and will use that data in our php code.

Part 1:-
<?php
$data = array('php'=>3, 'code'=>4, 'beginner'=>22,'java'=>array("javascript","jquery"));
echo json_encode($data);
?>

Part 2:-
<?php
$object=json_decode($data);
echo $object->php; //It will show 3
echo $object->java[0]; //It will show javascript
?>
PHP dynamic drop down menu or horizontal menu:
In  this tutorial of php code for beginners we will show how to create Dynamic drop down menu bar or Dynamic drop down horizontal menu in php with use of mysql database.

Create a database named myhotel and two table in it called state and city.
The state table contain the state name and state id fields  The city table contain city name, city id and state id in which he belong.

State table look like:-
state_id  state_name
Maharashtra
Gujarat
Karnataka

City table look like:-
 city_id  state_id             state_name
Mumbai
Pune
Thane
Gandhi nagar

Step 1:- Create a php configuration file which store the mysql database information. In my case it is config.php

 <?php
$hostname_conn = "localhost";
$database_conn = "myhotel";
$username_conn = "root";
$password_conn = "";

$conn = mysql_connect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_conn, $conn) or die("could not".mysql_error());
?>

Step 2:- Now create php file which contain your Dynamic menu.

 <?php
 // Included configuration file in our code.
include("config.php");
?>
<html>
<head>
<title>Dynamic Drop Down menu in php</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<ul id="Drop_Down_Menu">
<?php
// Creating query to fetch state information from mysql database table.
$state_query = "select * from state";
$state_result = mysql_query($state_query);
while($r = mysql_fetch_array($state_result)){ ?>
<li><a href="#"><?php echo $r['state_name'];?></a>
<ul>
<?php
$city_query = "select * from city where state_id=".$r['state_id'];
$city_result = mysql_query($city_query);
while($r1 = mysql_fetch_array($city_result)){ ?>
<li><a href="#"><?php echo $r1['city_name'];?></a></li>
<?php } ?>
</ul>
</li>
<?php } ?>
</ul>
</body>
</html>

Step 3:- Css for you Menu bar. Put this in to style.css file.

<style type="text/css">
ul {
    font-family: Arial, Verdana;
    font-size: 14px;
    margin: 0;
    padding: 0;
    list-style: none;
}
ul li {
    display: block;
    position: relative;
    float: left;
}
li ul {
    display: none;
}
ul li a {
    display: block;
    text-decoration: none;
    color: #ffffff;
    border-top: 1px solid #ffffff;
    padding: 5px 15px 5px 15px;
    background: #1e7c9a;
    margin-left: 1px;
    white-space: nowrap;
}
ul li a:hover {
background: #3b3b3b;
}
li:hover ul {
    display: block;
    position: absolute;
}
li:hover li {
    float: none;
    font-size: 11px;
}
li:hover a { background: #3b3b3b; }
li:hover li a:hover {
    background: #1e7c9a;
}

</style>

Now your Dynamic drop down menu bar or horizontal menu is ready to use.

Step 1:- Create a simple html form by use of code provided below:

<html> 
<head>
    <title>JavaScript Form Validation</title>
    <script src = "javascript.js" language="javascript" type= "text/javascript"></script> 
  </head>
  <body>
    <form action="" name="Form" onsubmit="return(formvalidate());">
    <table cellspacing="2" cellpadding="2">
    <tr>
      <td align="right">Name</td>
      <td><input type="text" name="Name" /></td>
    </tr>
    <tr>
      <td align="right">Email</td>
      <td><input type="text" name="Email" /></td>
    </tr>
    <tr>
      <td align="right">Pin Code</td>
      <td><input type="text" name="Pin" /></td>
    </tr>
    <tr>
      <td align="right">Country</td>
    <td>
      <select name="Country">
<option value="" selected>Select Country</option>
<option value="1">USA</option>
<option value="2">JAPAN</option>
<option value="3">INDIA</option>
      </select>
    </td>
    </tr>
    <tr>
      <td align="right"></td>
      <td><input type="submit" value="Submit" /></td>
    </tr>
    </table>
    </form>
  </body>
<html>

Step 2:- Now create one Javascript.js file and put the below code inside that file.

function formvalidate()
{

   if( document.Form.Name.value == "" )
   {
     alert( "Please insert your name." );
     document.Form.Name.focus() ;
     return false;
   }
   if( !validateEmail())
   {
     alert( "Please insert your Email address." );
     document.Form.Email.focus() ;
     return false;
   }
   if( document.Form.Pin.value == "" ||isNaN( document.Form.Pin.value ) )
   {
     alert( "Please insert the pin code." );
     document.Form.Pin.focus() ;
     return false;
   }
   if( document.Form.Country.value == "" )
   {
     alert( "Please select your country!" );
     return false;
   }
   return( true );
}

function validateEmail()
{

   var emailID = document.Form.Email.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 )) 
   {
       
       return false;
   }
   return( true );
}
Subscribe to RSS Feed Follow me on Twitter!