UseFul PHP Script`s n Code`s

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Display a different image for each day of the week

Description

This PHP script will get the day of the week from the server date and then display an image (jpg or gif) to match.
The code

PHP:
<?php



/**

 * Change the name of the image folder

 *

 * Images must be named Monday.gif, Tuesday.gif etc

 */



// Change to the location of the folder containing the images

$image_folder = "images/days";



// You do not need to edit below this line



$today = date('l');



if (file_exists($image_folder."/".$today.".gif")) {

  echo "<img src=\"$image_folder/".$today.".gif\">";

}

else {

  echo "No image was found for $today";

}



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Random image

Description

Displays a random image on a web page. Images are selected from a folder of your choice.
The code

PHP:
<?php



/*

 * Name your images 1.jpg, 2.jpg etc.

 *

 * Add this line to your page where you want the images to 

 * appear: <?php include "randomimage.php"; ?>

 */ 



// Change this to the total number of images in the folder

$total = "11";



// Change to the type of files to use eg. .jpg or .gif

$file_type = ".jpg";



// Change to the location of the folder containing the images

$image_folder = "images/random";



// You do not need to edit below this line



$start = "1";



$random = mt_rand($start, $total);



$image_name = $random . $file_type;



echo "<img src=\"$image_folder/$image_name\" alt=\"$image_name\" />";



?>

 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Random quote

Description

Displays a random quote on a web page. Quotes are picked from a list that you define.
The code

PHP:
<?php



/**

 * Add this line of code in your page:

 * <?php include "random_quote.php"; ?>

 */



$quotes[] = "This is a quote";

$quotes[] = "This is another";

$quotes[] = "quote 3";

$quotes[] = "quote 4";

$quotes[] = "quote 5";

$quotes[] = "quote 6";



srand ((double) microtime() * 1000000);

$randomquote = rand(0,count($quotes)-1);



echo "<p>" . $quotes[$randomquote] . "</p>";



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Page load time

Description

Outputs the time in seconds that it takes for a PHP page to load.
The code

PHP:
<?php



// Insert this block of code at the very top of your page:



$time = microtime();

$time = explode(" ", $time);

$time = $time[1] + $time[0];

$start = $time;



// Place this part at the very end of your page



$time = microtime();

$time = explode(" ", $time);

$time = $time[1] + $time[0];

$finish = $time;

$totaltime = ($finish - $start);

printf ("This page took %f seconds to load.", $totaltime);



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Visitor information

Description

Displays information about a visitor to a web page. Shows IP address, referrer and browser type.
The code

PHP:
<?php



/**

 * Add this line of code in your page:

 * <?php include "visitor_information.php"; ?>

 */



// Display IP address

echo "<p>IP Address: " . $_SERVER['REMOTE_ADDR'] . "</p>";



// Display the referrer

echo "<p>Referrer: " . $_SERVER['HTTP_REFERER'] . "</p>";



// Display browser type

echo "<p>Browser: " . $_SERVER['HTTP_USER_AGENT'] . "</p>";



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Date file last modified

Description

Outputs the date and time that a file was last modified. Can be formatted however you wish.
The code

PHP:
<?php



// Change to the name of the file

$last_modified = filemtime("thisfile.php");



// Display the results

// eg. Last modified Monday, 27th October, 2003 @ 02:59pm

print "Last modified " . date("l, dS F, Y @ h:ia", $last_modified);



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Page redirect

Description

If you want a PHP redirect script that redirects visitors from a page to a specific URL then this is it. It sends the user from one web page to a different web page address. It is a good alternative to using the meta tag http-equiv option.
The code

PHP:
<?php



/**

 * Place in a blank PHP page

 */



// Change to the URL you want to redirect to

$URL="http://www.example.com";



header ("Location: $URL");



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Word wrap

Description

A function that takes a string of text and wraps it into lines of a length that you determine. Can be useful for guestbooks, news posting scripts etc. to prevent the layout breaking.
The code

PHP:
<?php



/**

 * Example usage:

 * 

 * // Your text

 * $text = "This is a sentence which contains some words.";

 * 

 * // Or from a database result

 * $text = $row['text'];

 * 

 * // Then put it into the function

 * $text = word_wrap($text);

 * 

 * // Output the result

 * echo $text;

 */



    function word_wrap($text) {



        // Define the characters to display per row

        $chars = "10";



        $text = wordwrap($text, $chars, "<br />", 1);



        return $text;



    }



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Server information

Description

A useful built-in PHP function that displays information about the PHP installation on your server, including version number, available libraries etc.
The code

PHP:
<?php



/**

 * View this file in your browser.

 */



    phpinfo();



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Shorten a text string

Description

Function to shorten / truncate a string of text into a specific number of characters and add three dots (...) to the end. This will also round the text to the nearest whole word instead of cutting off part way through a word.
The code

PHP:
<?php



/**

 * Add this to your page:

 * <?php

 * include "shorten_a_text_string.php";

 * echo ShortenText($text);

 * ?>

 * where $text is the text you want to shorten.

 * 

 * Example

 * Test it using this in a PHP page:

 * <?php

 * include "shortentext.php";

 * $text = "The rain in Spain falls mainly on the plain.";

 * echo ShortenText($text);

 * ?>

 */



    function ShortenText($text) {



        // Change to the number of characters you want to display

        $chars = 25;



        $text = $text." ";

        $text = substr($text,0,$chars);

        $text = substr($text,0,strrpos($text,' '));

        $text = $text."...";



        return $text;



    }



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Connect to a MySQL database

Description

A simple little function allowing you to connect to a MySQL database.
The code

PHP:
<?php



/**

 * Edit the database settings to your own.

 * To use, just include the function and 

 * call it using <?php db_connect(); ?>

 *

 * You can then do your database queries

 */



// Edit your database settings

$db_host = "localhost";

$db_user = "username";

$db_pass = "password";

$db_name = "databasename";



function db_connect() {

    global $db_host;

    global $db_user;

    global $db_pass;

    global $db_name;

    $connection = mysql_connect($db_host,$db_user,$db_pass);

    if (!(mysql_select_db($db_name,$connection))) {

        echo "Could not connect to the database";

    }

    return $connection;

}



?>
 

MaD-DoC

Member
Oct 27, 2007
6,337
22
0
SLIIT/Malabe
Display date and time with PHP

Description

Quick one-liner to output the current server date and time on a page.
The code

PHP:
<?php



/**

 * Just add this in your page where you

 * want the date/time to appear

 *

 * For more configuration options look

 * in the PHP manual at http://uk2.php.net/date

 */



// Displays in the format Saturday, November 22, 2003 11.38

echo date("l, F d, Y h:i" ,time());



?>
 

SaNDun

Well-known member
  • May 4, 2006
    12,677
    811
    113
    In La Srinka
    MaD-DoC said:
    Connect to a MySQL database

    Description

    A simple little function allowing you to connect to a MySQL database.
    The code

    PHP:
    <?php
    
    
    
    /**
    
     * Edit the database settings to your own.
    
     * To use, just include the function and 
    
     * call it using <?php db_connect(); ?>
    
     *
    
     * You can then do your database queries
    
     */
    
    
    
    // Edit your database settings
    
    $db_host = "localhost";
    
    $db_user = "username";
    
    $db_pass = "password";
    
    $db_name = "databasename";
    
    
    
    function db_connect() {
    
        global $db_host;
    
        global $db_user;
    
        global $db_pass;
    
        global $db_name;
    
        $connection = mysql_connect($db_host,$db_user,$db_pass);
    
        if (!(mysql_select_db($db_name,$connection))) {
    
            echo "Could not connect to the database";
    
        }
    
        return $connection;
    
    }
    
    
    
    ?>
    hehe.. mokada me function eke one line gobla variable dfine karanna puluwankam thiyagena lines 4k dagena thiyenne :D
     

    MaD-DoC

    Member
    Oct 27, 2007
    6,337
    22
    0
    SLIIT/Malabe
    Validate an email address using regular expressions

    Description

    If you want a PHP script to verify an email address then use this quick and simple PHP regular expression for email validation. This is also case-insensitive, so it will treat all characters as lower case. It is a really easy way to check the syntax and format of an email address.
    The code

    PHP:
    <?php
    
    
    
    $email = "[email protected]";
    
    
    
    if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
    
      echo "Valid email address.";
    
    }
    
    else {
    
      echo "Invalid email address.";
    
    }
    
    
    
    ?>
     

    MaD-DoC

    Member
    Oct 27, 2007
    6,337
    22
    0
    SLIIT/Malabe
    Add data to a MySQL database

    Description

    How to insert and save information into a MySQL database table using PHP.
    The code


    <?php



    /**

    * Change the first line to whatever

    * you use to connect to the database.

    *

    * We're using two values, title and

    * text. Replace these with whatever

    * you want to add to the database.

    *

    * Finally, change tablename to the

    * name of your table.

    */



    // Your database connection code

    db_connect();



    $query = "INSERT INTO tablename(title, text) VALUES('$title','$text')";



    $result = mysql_query($query);



    echo
    "The data has been added to the database.";



    ?>
     

    MaD-DoC

    Member
    Oct 27, 2007
    6,337
    22
    0
    SLIIT/Malabe
    Delete data from a MySQL database

    Description

    How to remove and erase stored information from a MySQL database table.
    The code


    <?php



    /*

    * Change the first line to whatever

    * you use to connect to the database.

    *

    * Change tablename to the name of your

    * database table.

    *

    * This example would delete a row from

    * a table based on the id of the row.

    * You can change this to whatever you

    * want.

    */



    // Your database connection code

    db_connect();



    $query = "DELETE FROM tablename WHERE id = ('$id')";



    $result = mysql_query($query);



    echo
    "The data has been deleted.";



    ?>
     

    MaD-DoC

    Member
    Oct 27, 2007
    6,337
    22
    0
    SLIIT/Malabe
    Send email using the PHP mail() function

    Description

    How to send an email from within a PHP page using the built in mail() function.
    The code


    <?php



    // Your email address

    $email = "[email protected]";



    // The subject

    $subject = "Enter your subject here";



    // The message

    $message = "Enter your message here";



    mail($email, $subject, $message, "From: $email");



    echo
    "The email has been sent.";



    ?>
     

    MaD-DoC

    Member
    Oct 27, 2007
    6,337
    22
    0
    SLIIT/Malabe
    Simple guestbook

    Description

    Allows visitors to your site to read your guestbook entries and post a message of their own. Very simple setup, only requires you to change 4 settings. Uses MySQL to store the entries.
    The code

    PHP:
    <?php
    
    
    
    /**
    
     * Create the table in your MySQL database:
    
     * 
    
     * CREATE TABLE guests (
    
     *   id int(10) NOT NULL auto_increment,
    
     *   name varchar(50) NOT NULL,
    
     *   message varchar(255) NOT NULL,
    
     *   date timestamp(14) NOT NULL,
    
     *   PRIMARY KEY (id)
    
     * )
    
     * 
    
     * Change the database login settings to your own
    
     * 
    
     * The script is now ready to run
    
     */
    
    
    
    // Change these to your own database settings
    
    $host = "localhost";
    
    $user = "username";
    
    $pass = "password";
    
    $db = "database";
    
    
    
    mysql_connect($host, $user, $pass) OR die ("Could not connect to the server.");
    
    mysql_select_db($db) OR die("Could not connect to the database.");
    
          
    
    $name = stripslashes($_POST['txtName']);
    
    $message = stripslashes($_POST['txtMessage']);
    
    
    
    if (!isset($_POST['txtName'])) {
    
    
    
        $query = "SELECT id, name, message, DATE_FORMAT(date, '%D %M, %Y @ %H:%i') as newdate FROM guests ORDER BY id DESC";
    
        $result = mysql_query($query);
    
        
    
        while ($row = mysql_fetch_object($result)) {
    
    
    
    ?>
    
    
    
    <p><strong><?php echo $row->message; ?></strong>
    
    <br />Posted by <?php echo $row->name; ?> on <?php echo $row->newdate; ?></p>
    
    
    
    <?php
    
            
    
        }
    
        
    
    ?>
    
    
    
    <p>Post a message</p>
    
    
    
    <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
    
    
    
        <p><label for="txtName">Name:</label><br />
    
        <input type="text" title="Enter your name" name="txtName" /></p>
    
    
    
        <p><label for="txtMessage">Your message:</label><br />
    
        <textarea title="Enter your message" name="txtMessage"></textarea></p>
    
        
    
        <p><label title="Send your message">
    
        <input type="submit" value="Send" /></label></p>
    
        
    
    </form>
    
    
    
    <?php
    
    
    
    }
    
    
    
    else {
    
    
    
        // Adds the new entry to the database
    
        $query = "INSERT INTO guests SET message='$message', name='$name', date=NOW()";
    
        $result = mysql_query($query);
    
    
    
        // Takes us back to the entries
    
        $ref = $_SERVER['HTTP_REFERER'];
    
        header ("Location: $ref");
    
    }
    
    
    
    ?>
     

    MaD-DoC

    Member
    Oct 27, 2007
    6,337
    22
    0
    SLIIT/Malabe
    Form to mail

    Description

    A simple form mail PHP script that displays a contact form to allow visitors to your site to send you a message via email. Built in security prevents spammers hijacking it from another domain.
    The code


    <?php



    /**

    * Change the email address to your own.

    *

    * $empty_fields_message and $thankyou_message can be changed

    * if you wish.

    */



    // Change to your own email address

    $your_email = "[email protected]";



    // This is what is displayed in the email subject line

    // Change it if you want

    $subject = "Message via your contact form";



    // This is displayed if all the fields are not filled in

    $empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";



    // This is displayed when the email has been sent

    $thankyou_message = "<p>Thankyou. Your message has been sent.</p>";



    // You do not need to edit below this line



    $name = stripslashes($_POST['txtName']);

    $email = stripslashes($_POST['txtEmail']);

    $message = stripslashes($_POST['txtMessage']);



    if (!isset(
    $_POST['txtName'])) {



    ?>



    <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">



    <p><label for="txtName">Name:</label><br />

    <input type="text" title="Enter your name" name="txtName" /></p>



    <p><label for="txtEmail">Email:</label><br />

    <input type="text" title="Enter your email address" name="txtEmail" /></p>



    <p><label for="txtMessage">Your message:</label><br />

    <textarea title="Enter your message" name="txtMessage"></textarea></p>



    <p><label title="Send your message">

    <input type="submit" value="Send" /></label></p>



    </form>



    <?php



    }



    elseif (empty(
    $name) || empty($email) || empty($message)) {



    echo
    $empty_fields_message;



    }



    else {



    // Stop the form being used from an external URL

    // Get the referring URL

    $referer = $_SERVER['HTTP_REFERER'];

    // Get the URL of this page

    $this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];

    // If the referring URL and the URL of this page don't match then

    // display a message and don't send the email.

    if ($referer != $this_url) {

    echo
    "You do not have permission to use this script from another URL.";

    exit;

    }



    // The URLs matched so send the email

    mail($your_email, $subject, $message, "From: $name <$email>");



    // Display the thankyou message

    echo $thankyou_message;



    }



    ?>