PHP Snippets

Support, Snippets & Projects

Moderators: Moderator, Global Moderator

Post Reply
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Displaying visitors browser information.

Simply paste the following code into your pages source:

Code: Select all

<?php 
    echo $_SERVER['HTTP_USER_AGENT']; 
?>
RuffRyders.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Displaying Your Servers Information.

Simply paste the following code into your source.

Code: Select all

<?php 
   phpinfo(); 
?>
RuffRyders.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Simply paste the following snippets into your pages source:

Displaying a visitors IP address.

Code: Select all

<?php 
echo "Your IP Address: ", $_SERVER['REMOTE_ADDR'];
?>
Displaying your servers IP address.

Code: Select all

<?php
echo "Server Address: ", $_SERVER['SERVER_ADDR'];
?>
RuffRyders.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Random Quote.

Simply paste the following snippet into your pages source.

Code: Select all

<?php 

$quote[1]="This is quote 1"; 
$quote[2]="This is quote 2"; 
$quote[3]="This is quote 3"; 
$quote[4]="This is quote 4"; 
$quote[5]="This is quote 5"; 

$random = rand(1, count($quote)); 

echo "$quote[$random]"; 

?>
RuffRyders.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Referer.

Simply tells the visitor which site they previously came from to get to your site.

Code: Select all

<?php

echo $_SERVER['HTTP_REFERER']; 

?>
RuffRyders
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Include a page.

What this does is include a page within another page.

Code: Select all

<?php
include "yourpage.php";
?>
RuffRyders.
The bruises fade but memories are made.
False_Pretense
Newbie
Newbie
Posts: 47
Joined: Wed Jun 16, 2004 5:37 pm

PHP Snippets

Post by False_Pretense »

this is a flat unique ip counter. it writes to two files you will have to make "ips.txt" "logipdates.txt" it uses a loop to count the ips from the ips.txt file. The logipdates.txt is for putting a date and time to the ip hits.


[html]<?php $file = "C:/yoursite/text/ips.txt";
$logdate = "C:/yoursite/text/logipdates.txt";
$today = date (" m,d,Y,g:ia");

// Obtain users IP address
$getip = getenv(REMOTE_ADDR);
$addip = "TRUE";
$count = 0;

// Open $file and search each line (IP address) for a match
$fpip = fopen($file,"r");
while (!feof($fpip))
{
$line = fgets($fpip, 4096); //gets one line at a time
$line=trim($line);
if ($line != "")
{
$count++;
}
}

// If IP is already logged
if ($line==$getip)
{
$addip = "FALSE";
}
{
fclose($fpip);
}

// If the IP was not previously logged, append it to $file
if ($addip == "TRUE")
{
$fpip = fopen($file,"a");
fwrite($fpip, "\n");
fwrite($fpip, $getip);
fclose($fpip);
$count++;
$fpd = fopen($logdate, "a");
fwrite($fpdate, "\n");
fwrite($fpdate, $ipadd);
fwrite($fpdate, $today);
fclose($fpdate);
}

// Display count
echo $count;
readfile ("$logdate");
?>[/html]

Chucked in some [html ] and [/ html] (without spaces), easier to read /blum.gif' class='bbc_emoticon' alt=':P' />
Last edited by False_Pretense on Fri May 14, 2004 6:35 pm, edited 1 time in total.
Image
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Displaying Users Hostname.

[quote]<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
echo $hostname;
?>[/quote]

RuffRyders.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Simple Calculator.

Code: Select all

<?PHP 

if(!$_POST['act']) 
{ 
  echo ' 
<form method="post" action="'.$_SERVER['PHP_SELF'].'"> 
  <input type="text" name="z1" size="5"> 
  <select name="act"> 
   <option value="add">[ + ]</option> 
   <option value="sub">[ - ]</option> 
   <option value="div">[ / ]</option> 
   <option value="mul">[ x ]</option> 
   <option value="pro">[ % ]</option> 
  </select> 
  <input type="text" name="z2" size="5"> 
  <input type="submit" name="doit" value="Calculate"> 
</form> 
'; 
}else{ 
  if($_POST['act'] == 'add') 
  { 
   $calc = ($_POST['z1']+$_POST['z2']); 
   $op = '+'; 
  } 
  if($_POST['act'] == 'sub') 
  { 
   $calc = ($_POST['z1']-$_POST['z2']); 
   $op = '-'; 
  } 
  if($_POST['act'] == 'div') 
  { 
   $calc = ($_POST['z1']/$_POST['z2']); 
   $op = '/'; 
  } 
  if($_POST['act'] == 'mul') 
  { 
   $calc = ($_POST['z1']*$_POST['z2']); 
   $op = 'x'; 
  } 
  if($_POST['act'] == 'pro') 
  { 
   $calc = (($_POST['z2']*$_POST['z1'])/100); 
   $op = '% of'; 
  } 
  echo $_POST['z1'].' '.$op.' '.$_POST['z2'].' = '.$calc; 
} 

?>
RuffRyders.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Unique ID:

Code: Select all

<?php 
   echo $_SERVER['UNIQUE_ID'];
?>
---------------

Servers administrator:

Code: Select all

<?php 
   echo $_SERVER['SERVER_ADMIN'];
?>
---------------

Displays the port the visitor is connecting through:

Code: Select all

<?php 
   echo $_SERVER['SERVER_PORT'];
?>
---------------

Servers software:

Code: Select all

<?php
   echo $_SERVER['SERVER_SOFTWARE'];
?>
---------------

The language and country:

Code: Select all

<?php
   echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
?>
The bruises fade but memories are made.
Tami
Administrator
Administrator
Posts: 10892
Joined: Sun Apr 25, 2004 6:05 am

PHP Snippets

Post by Tami »

Originally Posted by MaGiC on GraphixGround March 3 2004

Getting Started

Create a file named hello.php and put it in your web server's root directory (DOCUMENT_ROOT) with the following content:

Code: Select all

<html>
 <head>
  <title>[color=green]PAGE TITLE[/color] </title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?>
</body>
</html>
Use your browser to access the file with your web server's URL, ending with the "/hello.php" file reference. When developing locally this URL will be something like [url="http://localhost/hello.php"]http://localhost/hello.php[/url] or [url="http://127.0.0.1/hello.php"]http://127.0.0.1/hello.php[/url] but this depends on the web server's configuration. Although this is outside the scope of this tutorial, see also the DocumentRoot and ServerName directives in your web server's configuration file (for Apache, this is httpd.conf). If everything is configured correctly, this file will be parsed by PHP and the following output will be sent to your browser:

Code: Select all

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <p>Hello World</p>
 </body>
</html>
Forms

Code: Select all

<form action="action.php" method="post">
 Your name: <input type="text" name="name" />
 Your age: <input type="text" name="age" />
 <input type="submit" />
</form>
There is nothing special about this form. It is a straight HTML form with no special tags of any kind. When the user fills in this form and hits the submit button, the action.php page is called. In this file you would write something like this:

Code: Select all

Hi <?php echo $_POST['name']; ?>.
You are <?php echo $_POST['age']; ?> years old.
Then the script should show:

Hi Danny. You are 14 years old.

It should be obvious what this does. There is nothing more to it. The $_POST['name'] and $_POST['age'] variables are automatically set for you by PHP. Earlier we used the $_SERVER autoglobal; above we just introduced the $_POST autoglobal which contains all POST data. Notice how the method of our form is POST. If we used the method GET then our form information would live in the $_GET autoglobal instead. You may also use the $_REQUEST autoglobal, if you do not care about the source of your request data. It contains the merged information of GET, POST and COOKIE data.

(More Will Be Added Later!)
Image

[color=\"#41211C\"]It takes years to build up trust and only seconds to destroy it

[/color]
to@ds
Sr. Member
Sr. Member
Posts: 376
Joined: Wed Jun 16, 2004 5:37 pm

PHP Snippets

Post by to@ds »

I tried some of RuffRyders codes, the Unique ID, and Display Visitors IP, but couldnt get them to work. Ive not done any PHP before some Im a total newb. I tried putting them in the head, and body of my pages and neither worked. Any help would be great

Thanks
[align=center]Image[/align]

[align=center][color=\"#CC0000\"]"You may give a toad a wart, but a toad will never give you a wart"[/color][/align]

[align=center]eighty4toads.co.uk[/align]
Sp3culuM
Hero Member
Hero Member
Posts: 662
Joined: Mon May 17, 2004 7:36 am

PHP Snippets

Post by Sp3culuM »

Try this..

Code: Select all

<html>
<head>
<title>PHPness</title>
</head>
<body>
<?
if(getenv(HTTP_CLIENT_IP)) { 
          $_ip = getenv(HTTP_CLIENT_IP); 
} 
elseif(getenv(HTTP_X_FORWARDED_FOR)) { 
          $_ip = getenv(HTTP_X_FORWARDED_FOR); 
} 
else { 
          $_ip = $REMOTE_ADDR; 
}
echo "Your IP: ".$_ip.".";
echo "Unique ID: ".$_SERVER['UNIQUE_ID'].".";
?>
</body>
</html>
Also.. are you running these on a PHP enabled server? Silly question I know, but you can't run it locally without speciallist software installed.
Image
to@ds
Sr. Member
Sr. Member
Posts: 376
Joined: Wed Jun 16, 2004 5:37 pm

PHP Snippets

Post by to@ds »

Ahhh, I thought that might have been the problem. I need some kind of compiler then I take it. Can you name any programs to help? Thanks /bow.gif' class='bbc_emoticon' alt='(bow)' />
[align=center]Image[/align]

[align=center][color=\"#CC0000\"]"You may give a toad a wart, but a toad will never give you a wart"[/color][/align]

[align=center]eighty4toads.co.uk[/align]
Sp3culuM
Hero Member
Hero Member
Posts: 662
Joined: Mon May 17, 2004 7:36 am

PHP Snippets

Post by Sp3culuM »

There's quite a few, appserv and easyphp to name a few. Sorry I don't have the links to the sites any more, thought I did but can't find them /rolleyes.gif' class='bbc_emoticon' alt=':rolleyes:' />
Image
to@ds
Sr. Member
Sr. Member
Posts: 376
Joined: Wed Jun 16, 2004 5:37 pm

PHP Snippets

Post by to@ds »

Nice one. Im sure I'll get them from cnet or something.
[align=center]Image[/align]

[align=center][color=\"#CC0000\"]"You may give a toad a wart, but a toad will never give you a wart"[/color][/align]

[align=center]eighty4toads.co.uk[/align]
to@ds
Sr. Member
Sr. Member
Posts: 376
Joined: Wed Jun 16, 2004 5:37 pm

PHP Snippets

Post by to@ds »

[url="http://www.easyphp.org/"]http://www.easyphp.org/[/url] incase anyone wanted to know.
[align=center]Image[/align]

[align=center][color=\"#CC0000\"]"You may give a toad a wart, but a toad will never give you a wart"[/color][/align]

[align=center]eighty4toads.co.uk[/align]
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

A simple way you could ban a user.

Code: Select all

<?php 
$ip = getenv("REMOTE_ADDR"); 
if ($ip =="12.345.678.9") 
{ 
echo "You're banned from this site :)"; 
exit(); 
} 
?>
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

A simple way to echo text for those whom are new to php.

Code: Select all

<?php
echo "Your text here."; 
?>
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

A Quick log in to Invision based forums for your site.

Code: Select all

<form style="display:inline" action="http://forums.killagraphix.com/index.php?act=Login&CODE=01&CookieDate=1" method="post">
<input type="text" size="10" name="UserName" onfocus="this.value=''" value="User Name">
<input type="password" size="10" name="PassWord" onfocus="this.value=''" value="ibfrules">
<input type="submit" value="Go">
</form>
Credit to Lightsup55.

If you wish to use this code on your site, for your forums be sure to replace forums.killagraphix.com with your boards url for eg. yourdomain.com/forum/

I know this isn't a php script but I thought I'd paste it here any how.
Last edited by RuffRyders on Sat Oct 30, 2004 4:53 pm, edited 1 time in total.
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Seeing how a lot of you use phpbb forums I thought I'd post this:

Let's take a look at the phpBB table phpBB_users; you'll see a list
of fields. The fields we need are:
-> username
-> user_posts
What we are going to do is:
-> Get username & user's post count from the database
-> Get the next username & user's post count
-> Compare them
-> If the second user's post count is bigger, get put username & post count
into a variable and compare it with the next record.

Code: Select all

<?php 
    $username    = 'username'; 
    $password     = 'password'; 
    $host        = 'localhost'; 
    $connection = mysql_connect ($username, $password, $host);    //Create a MySQL 
connection 

    $query = 'SELECT * from phpbb_users';                 //Create the query 

    $result = mysql_db_query ($db, $query, $connection);        //Run the query on 
the database 

    $user1_posts     = $row['0'];                    //Create 2 empty variables to compare 
    $user1_name        = $row['0'];                //the usernames & post counts 

    while ($row = mysql_fetch_array($result)) {            //Fetch the results from var 
$result 
        $user2_posts     = $row['user_posts'];            //Put the username & post count into 
an temporary variable 
        $user2_name    = $row['username'];            // 
        if ($user2_posts > $user1_posts) {            //Compare the post counts 
            $user1_posts     = $row['user_posts'];        //If the new one is bigger, replace 
the old one with the new one 
            $user1_name    = $row['username']; 
        } 
    } 

    print ('Top poster: ' . $user1_name . ' with ' . $user1_posts . '.'); 
?>
That's it!
For questions about this script you can email me at rein3000@hotmail.com
or surf to www.rynusrein.nl.tt.

Taken from: [url="http://www.phpcafe.net/index.php/pg/tutorials/lang/1/skin/1/CODE/02/id/15"]Here[/url]
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Browser Redirect:

Alright, this is a simple little script which will take you to one page if you're using Internet Explorer, and another page if you're using some other browser. Lets decide what this is going to do in English:

If the browser is MicroSoft Internet Explorer (MSIE), then go to spoono.com
If the browser isn't MSIE, then redirect to yahoo.com.

The most essential part of this is that this code has to be sent out before any output to the HTML page. Make sure it is the first line of code on your PHP page. With that said, here is the PHP:

<?
//if its MSIE then
if ($name = strstr ($HTTP_USER_AGENT, "MSIE"))
{
//go to Spoono
Header ("Location: [url="http://www.spoono.com/");"]http://www.spoono.com/");[/url]
}
else
{
//else go to Yahoo
Header ("Location: [url="http://www.yahoo.com/");"]http://www.yahoo.com/");[/url]
}
?>

Tutorial courtesy of [url="http://www.spoono.com"]Spoono[/url].
The bruises fade but memories are made.
RuffRyders
Hero Member
Hero Member
Posts: 1138
Joined: Mon Jun 14, 2004 12:47 am

PHP Snippets

Post by RuffRyders »

Use this as a gateway to detect a users accepted language and for example redirect him/her to the right page.

Code: Select all

<?php

function lixlpixel_get_env_var($Var)
{
 if(empty($GLOBALS[$Var]))
 {
  $GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))?
  $GLOBALS['_SERVER'][$Var]:
  (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var]))?
  $GLOBALS['HTTP_SERVER_VARS'][$Var]:'';
 }
}

function lixlpixel_detect_lang()
{
 // Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
 lixlpixel_get_env_var('HTTP_ACCEPT_LANGUAGE');
 lixlpixel_get_env_var('HTTP_USER_AGENT');
 
 $_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
 $_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
 
 // Try to detect Primary language if several languages are accepted.
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(strpos($_AL, $K)===0)
   return $K;
 }
 
 // Try to detect any language if not yet detected.
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(strpos($_AL, $K)!==false)
   return $K;
 }
 foreach($GLOBALS['_LANG'] as $K)
 {
  if(preg_match("/[\[\( ]{$K}[;,_\-\)]/",$_UA))
   return $K;
 }
 
 // Return default language if language is not yet detected.
 return $GLOBALS['_DLANG'];
}

// Define default language.
$GLOBALS['_DLANG']='en';

// Define all available languages.
// WARNING: uncomment all available languages

$GLOBALS['_LANG'] = array(
'af', // afrikaans.
'ar', // arabic.
'bg', // bulgarian.
'ca', // catalan.
'cs', // czech.
'da', // danish.
'de', // german.
'el', // greek.
'en', // english.
'es', // spanish.
'et', // estonian.
'fi', // finnish.
'fr', // french.
'gl', // galician.
'he', // hebrew.
'hi', // hindi.
'hr', // croatian.
'hu', // hungarian.
'id', // indonesian.
'it', // italian.
'ja', // japanese.
'ko', // korean.
'ka', // georgian.
'lt', // lithuanian.
'lv', // latvian.
'ms', // malay.
'nl', // dutch.
'no', // norwegian.
'pl', // polish.
'pt', // portuguese.
'ro', // romanian.
'ru', // russian.
'sk', // slovak.
'sl', // slovenian.
'sq', // albanian.
'sr', // serbian.
'sv', // swedish.
'th', // thai.
'tr', // turkish.
'uk', // ukrainian.
'zh' // chinese.
);

// Redirect to the correct location.

//header('location: http://www.your_site.com/index_'.lixlpixel_detect_lang().'.php'); // Example Implementation
echo 'The Language detected is: '.lixlpixel_detect_lang(); // For Demonstration

?>
Credit to lixlpixel.
The bruises fade but memories are made.
Post Reply

Return to “PHP &amp; MySQL”