Category Archives: programming

PHP code to get domain name from a URL

To get the domain name use this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
$url = 'http://www.example.com/process.php?act=update&id=33'
 
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i', "http://www.php.net/index.html", $matches);
$host = $matches[1];
 
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
 
// host will return: www.example.com
// $matches[0] will return: example.com
?>

To get the script name use this

$_SERVER[‘SCRIPT_NAME’]

// will return: /process.php

and to get the parameters passed, use this

$_SERVER[“QUERY_STRING”]

// will return: act=update&id=33

How to randomly read line from a file

This is a very basic way to build a ‘dynamic’ content to your site. You can randomly display quotes, testimonials or what ever content you want with a pre-loaded content in a text file.

Let say you want to display a random quote line from a file.

1
2
3
4
5
6
7
8
<?
function randomLine($filename)
{
    $lines = file($filename) ;
    echo $lines[array_rand($lines)] ;
}
randomLine("quotes.txt"); // example code to call function
?>

Also read how to write to a flat file (to make it even more dynamic – can add content via form)

How to send email using PHP mail() function

Here’s a quick way to send an email. You only need one line for that. I always use this script to send an alert on any event triggered. Let say somebody just make a payment on your site.

$headers = "From: sendername <sender@example.com>\r\n";
$headers .= 'Cc: cc@example.com' . "\r\n";
$headers .= 'Bcc: bcc@example.com' . "\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
mail('recipient@example.com','Subject','Message',$headers);

For the “from” email, some hosting requires you to use only registered email address in your hosting/domain.

How to write to a flat file with PHP

Sometimes writing to a file is much easier that writing to a database. It is quite a tedious job to create a database, create a user to point to a database then create table and so on.

With a flat file you can just create a blank file (with any extension). I prefer still to use .php file so that people cannot read the file via web.

Here is the code to write and append to a file.

1
2
3
4
5
6
7
$name = "anyname"; $email = "anyemail";
$myFile = "yourdatafile.php";
 
$fh = fopen($myFile, 'a') or die("Failed to open file.");
$stringData = "$name;;$email\n";
fwrite($fh, $stringData);
fclose($fh);

Make sure you set your file to 666 (writable). If you want to overwrite each time data is saved, use fopen($myFile, ‘w’) ~ parameter ‘w’ instead of ‘a’

How to display all PHP server variables

Sometimes I get confused with what result a server variables would return.  For example between the $_SERVER[‘SCRIPTNAME’] and $_SERVER[‘SCRIPT_FILENAME’].

Use the following code to display all server variables. From there you can decide which server variable is suitable to use.

1
2
3
4
echo "<table>";
foreach($_SERVER as $key=>$value)
        echo "<tr><td>$key</td><td>$value</td></tr>";
echo "</table>";

PHP function for pagination/paging

Found this function. Not tested yet but maybe useful in the future.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
// example variable
$sql_limit = (isset($_GET['limit'])) ? $_GET['limit'] : 0;
 
function navigation_links($curr_limit, $num_records, $limit_val, $limit_var = "limit", $next = "next >", $prev = "< prev", $seperator = "|") {
    // rebuild query string
    if (!empty($_SERVER['QUERY_STRING'])) {
        $parts = explode("&", $_SERVER['QUERY_STRING']);
        $newParts = array();
        foreach ($parts as $val) {
            if (stristr($val, $limit_var) == false) array_push($newParts, $val);
        }
        $qs = (count($newParts) > 0) ? "&".implode("&", $newParts) : "";
    } else {
        $qs = "";
    }
    $navi = "";
    if ($curr_limit > 0) {
        $navi .= "<a href="".$_SERVER['PHP_SELF']."?".$limit_var. "=".($curr_limit-$limit_val).$qs."">".$prev."</a>";
    }
    $navi .= " ".$seperator." ";
    if ($curr_limit < ($num_records-$limit_val)) {
        $navi .= "<a href="".$_SERVER['PHP_SELF']."?".$limit_var. "=".($curr_limit+$limit_val).$qs."">".$next."</a>";
    }
    return trim($navi, " | ");
}
 
// example placing links ($num_all is the value of all records in you result set)
echo navigation_links($sql_limit, $num_all, 10);
?>

source | more functions avail.

Javascript banner rotation script

This script is given by a friend long time ago. Very useful but it is not so dynamic. You can easily change parameter to suit your need.

The javascript code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<script LANGUAGE="JavaScript">
<!-- Hide from JavaScript-Impaired Browsers
/* First, if you load fewer or more than 6 sponsors
   into your rotator, change the "number_of_sponsors" variable
   to the actual number of sponsor .gifs you plan to
   load. */
   number_of_sponsors=3;
var sctr=0;
var halt=0;
var isn=new Array();
for (i=0;i<number_of_sponsors;i++){
 isn[i]=new Image();
}
/* The sponsor .gif names are loaded into the isn[x]
   sponsor images array.  You may load any number of
   sponsor images (.gif or .jpg or both) into this
   array. They must all be the same size, however.
   Substitute your own .gif filenames for the ones
   shown here. Note that the first .gif must appear
   in the isn[0] array element. */
isn[0].src="images/suggest.png";
isn[1].src="images/claim.png";
isn[2].src="http://www.example.com/images/layout.png";
 
 
/* Finally, replace the URL's below with those of
   your sponsors IN THE SAME ORDER. */
var durl=new Array();
durl[0]="";
durl[1]="http://www.google.com";
durl[2]="layout.php";
 
/* This script is set to rotate every 10 seconds.
   (5000=5 seconds, so 30000 would equal 30, etc)
   You should change the number in the setTimeout()
   call below for the number of seconds you wish. */
function rotateIt(){
 if (halt!=1){
  sctr++;
  if (sctr>number_of_sponsors-1){
   sctr=0;
   }
  document.sponsor.src=isn[sctr].src;
  setTimeout("rotateIt()",3000);
  }
 }
/* This code will work just fine with or without
   frames.  However, if you are in frames and wish
   to replicate the TARGET="_top" call to remove
   frames, change the location.href call to:
    parent.location.href=durl[sctr];
   below. */
function doIt(){
 halt=1;
 parent.location.href=durl[sctr];
 }
function dispIt(){
 parent.window.status=durl[sctr];
 }
// End Hiding --></script>

Code in HTML body (to display)

1
2
3
4
5
6
7
8
9
10
 
<a HREF="http://www.example.com"
            onClick="doIt();return false" onMouseover="dispIt();return true;"><img
            SRC="images/claim.png" NAME="sponsor" BORDER="0"
            HEIGHT="150" WIDTH="490" NATURALSIZEFLAG="0" ALIGN="BOTTOM"></a>
 
<script LANGUAGE="JavaScript"><!-- Hide JavaScript from Java-Impaired Browsers
sctr=0;
rotateIt();
// End Hiding --></script>

PHP header forwarding not working

If you are finding that header() is not working for no obvious reason, make use of the headers_sent() function to drill down to the cause of the problem.

Consider the following scenario,

1
2
3
4
5
6
7
<?php
// Sign out
signOut();
 
// Redirect back to the main page
header("Location: http://mysite.com/mainpage");
?>

If for some reason, the header() call to redirect is not working, there won’t be any error messages, making it difficult to debug.  However, using headers_sent(), you may easily find the source of the problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// Sign out
signOut();
 
/*
* If headers were already sent for some reason,
* the upcoming call to header() will not work...
*/
if(headers_sent($file, $line)){
// ... where were the mysterious headers sent from?
echo "Headers were already sent in $file on line $line...";
}
 
// Redirect back to the main page
header("Location: http://mysite.com/mainpage");
?>

source (comment by jasper)