Go to the menu - Go to the contents

[Site map] You are here --- > Newbies Paradise > Forums > Website > PHP > Your own Functions and Tips > Read the topic

Your own Functions and Tips

The tips than can be useful for developping websites / applications in PHP

You have to be registered to post messages

Page 1  2  Next
Author Message
1 visitor on this topic (1 anonymous user)
Page 1  2  Next
Offline Talus # Posted on 02/12/2007 02:12:53 PM
I'm a dummy.
Avatar
Group : Members
Hello,

On the french version ("SdZ") of the Newbies Paradise, there is the topic, where you can post your own functions, that you thinks they can be sueful for everybody.

Here is the nCode for posting functions / tips (without spaces):

Code: Ncode
<quote name="Your function" ><code type="php">Your PHP code</ code></ quote>
(and, eventually, further more explication on the function)


OR

Code: Ncode
<quote name="your tip">your tip</quote>
(and, eventually, further more explication on the tip)


Let me show you an example :

You must know...


  • The absolute link to youor script (Example :c:\wamp\web\myscript.php)
  • Have PHP installed you do not need apache or SQL)
  • where the php executable file is (usually, it is c:\php\php.exe, or, for those who are usign EasyPHP, c:\Program Files\Easy PHP\php.exe
  • how to go to the windows console
  • How To

  • Go where php is installed
  • run the command to check the php syntax of your file


The command


Code: Others
php.exe -l c:\wamp\web\myscript.php


That's all, folks !
Edited on 02/15/2007 10:04:23 PM by Talus

WarmBB's Project (still) under developpement (French for the moment)
 
Offline mickael9 # Posted on 02/12/2007 03:04:24 PM
Group : Members
Hi, here is my Database class which is protected against SQL Injection.

Code: PHP

class Db
{
    var $Connection;
    var $Debug;
    var $ReqsCount = 0;

    function Connect($Server, $User, $Password, $Base)
    {
        $this->Connection = @mysql_connect($Server, $User, $Password);
       
        if (!$this->Connection)
            $this->_Error('Connection to MySql has failed.', E_USER_ERROR);
       
        if (!@mysql_select_db($Base, $this->Connection))
            $this->_Error('Unable to select database.', E_USER_ERROR);
    }

    function Query($Query)
    {
        $ArgsCount = func_num_args();

        if ($ArgsCount > 1)
        {
            $Args  = func_get_args();
           
            array_shift($Args);

            $Args  = array_map('mysql_real_escape_string', $Args);
            $Query = vsprintf($Query, $Args);
        }
       
        if ($this->Debug)
            echo '<p><strong>SQL Query</strong> : ' . htmlspecialchars($Query) . ' -> ';

        $Result = @mysql_query($Query, $this->Connection);
       
        if (!$Result)
        {
            if ($this->Debug)
                echo '<span style="color: red; font-weight: bold;">ERROR</span></p>';

            $this->_Error('Query has failed');
        }
        else
        {
            $this->ReqsCount++;

            if ($this->Debug)
                echo '<span style="color: green; font-weight: bold;">OK</span></p>';
        }

        if ($Result === true) // UPDATE, DELETE, DROP, ... statments
            return true;

        else
            return new RecordSet($Result);
    }

    function _Error($Message, $ErrorType = null)
    {
        $Error = 'SQL Error : ' . $Message;
       
        if ($this->Debug)
            $Error .= ' (' . htmlspecialchars(mysql_error()) . ')';
       
        trigger_error($Error, ($ErrorType == null ? E_USER_WARNING : $ErrorType));
    }
}

class RecordSet
{
    var $Resource;
    var $IsEmpty = false;
   
    function RecordSet($Resource)
    {
        $this->Resource = $Resource;
        $this->IsEmpty  = ($this->Number() == 0);
    }
   
    function Next($ResultType = null)
    {
        if (!$this->Resource)
            return false;
       
        if ($ResultType == null)
            return mysql_fetch_array($this->Resource);
       
        return mysql_fetch_array($this->Resource, $ResultType);
    }
   
    function All($ResultType = null)
    {
        $All = Array();
       
        $this->ResetPointer();
       
        while ($Rec = $this->Next($ResultType))
            $All[] = $Rec;
       
        return $All;
    }
   
    function Part($StartIndex, $ElementCount = null, $ResultType = null)
    {
        $Part = $this->All($ResultType);
        $Part = array_slice($Part, $StartIndex, $ElementCount);

        return $Part;
    }
    function Number()
    {
        if (!$this->Resource)
            return 0;

        return mysql_num_rows($this->Resource);
    }
   
    function ResetPointer()
    {
        return mysql_data_seek($this->Resource, 0);
    }
}



Usage example :
Code: PHP

$db = new Db();
$db->Connect('localhost', 'me', 'password', 'db1');

$recs = $db->Query('SELECT col1, col2, col3 FROM table1 WHERE blah = "%s" AND id = %d', $_GET['blah'], $_GET['numeric_val']);

if (!$recs->IsEmpty)
    print_r($recs->All());

else
    echo 'No record';
Edited on 02/12/2007 03:05:57 PM by mickael9
Offline timmywrath # Posted on 02/12/2007 05:00:52 PM
I don't wanna say it.
Avatar
Group : Read only
Thanks mickael9 ;)

Here's a very good one (but that must come from the fact that I created it :p ) :
Quote : Referer
Code: PHP

session_start(); /* We start the session (doh) */
/***    REFERER FUNCTION
        Sends an e-mail to [myemail@example.com] containing the URL of the webpage that got a visitor to your website
       
        PARAMETRERS/ARGUMENTS
        None
***/
    
function referer() {
        $message = 'Here is the URL of the webpage that sent ' . $_SERVER['REMOTE_ADDR'] . ' (the visitor\'s IP adress) to your website (on the page ' . $_SERVER['PHP_SELF'] . ') :\n" ' . $_SERVER['HTTP_REFERER'] . '\n\nThis information may be incorrect (there is about a 1.5% chance) ; do not trust it at 100%.'; /* We create the message */
        $message = wordwrap($message, 70); /* we cut it with a wordwrap for the e-mail to be correctly displayed */
        mail('[myemail@example.com]', 'Referer', $message); /* and we finally send the message */
        }


Yes I know, it's fabulous isn't it o_O
What? Alright I'll explain what it does :o
You will have to replace all the [myemail@example.com]s by your e-mail (without the pair of '[]').
It will send you an e-mail containing the URL of the webpage that got your visitor to that page of your website.
Sorry if you do not get it ^^

Here's a usage example:
Code: PHP
<?php referer(); ?>

Ain't it easy ;)

NOTE: when you insert the code of the function in the webpage, you must do so at the beginning, before any xHTML.
Offline anonymousguest # Posted on 02/12/2007 08:32:27 PM
I'm the Dude!
Avatar
Group : Members
Hello,
timmywrath > how many visitors do you have a day? o_O
Seriously, if a visitor loads 1 page you receive 1 mail, imagine if you have 20 (that's not much) and that each one refresh the page about 3 times(that's not much either), you'll receive 60 mails.

"Mondays suck!"
 
Offline SunBall # Posted on 02/12/2007 08:56:54 PM
Group : Members
+1 for anonymousguest ...

Please add my mail on your messenger ;)
I want much person in my messenger :p
Zozor is god, look his birthday Here ..
He was born at 00/00/0000 ! Incredible !
 
Offline Worldedit # Posted on 02/12/2007 11:22:05 PM
Avatar
Group : Members
This function was posted in the french site du zero by Winzou, I changed it a while

Code: PHP
function get_page($page, $nomber_page)
{
        $list_page = array();
        for ($i=1;$i <= $nomber_page;$i++)
        {
                        if (($i < 3) || ($i > $nomber_page - 3) || (($i < $page + 3) && ($i > $page - 3)))
                        $list_page[] = $i;
                        else
                        {
                        if ($i >= 3 && $i <= $page - 3) $i = $page - 3;
                                       
                        elseif ($i >= $page + 3 && $i <= $nomber_page - 3)                                     $i = $nomber_page - $nb;

                        $list_page[] = '...';
                        }
        }
return $list_page;
}


How to use ?

Code: PHP

$p = get_page($page,$totalpage);
for ($i=0; $i<=$total_of_page; $i++)
{
if ($p[$i] == $page) echo'<strong>'.$p[$i].'</strong>  ';
else echo '<a href="'.ADRESS.'index.php?page='.$p[$i].'">'.$p[$i].'</a>  ';
}


What do you get ?

Quote : page 140

Page : 1 2 ... 138 139 140 141 142 ... 298 299 300


Quote : page 1 (first)

Page : 1 2 3 ... 298 299 300


Quote : Page 300 (last)

Page : 1 2 ... 298 299 300


Please note that the page you are currently reading will not be a link.

(I hope Winzou don't mind that I use and post his function :s )
Offline Talus # Posted on 02/13/2007 04:48:27 PM
I'm a dummy.
Avatar
Group : Members
I think he will mind about the "W" you put in his name =D

Anyway, i think a foreach should be better =)

WarmBB's Project (still) under developpement (French for the moment)
 
Offline Dentuk # Posted on 02/13/2007 06:23:40 PM
Group : Members
Worldedit, you've forgotten the 3rd parameter, $nb, which has a default value on the french version (set to 3) and which is used in the elseif().
And with your code you may write links such as this one :Code: HTML
<a href="?page=...">...</a>

Hello ! :D
 
Offline Dj-Serpen # Posted on 02/14/2007 04:57:15 PM
NP is cool!
Group : Members
When you code comment your code!

(The quote tip is not functionnal!)

If you have problems, search the tutorials and the forums.
If your problem don't appear, post on the forum!
 
Offline mwsaz # Posted on 02/14/2007 05:00:31 PM
Tremulous : open source FPS
Avatar
Validators
Here is the nCode for posting functions / tips (without spaces):
And no need to add spaces if in code : ncode

Computers are like air conditioned : they stop working when you open windows.
About tutorial validation: I deal with newly submitted tutos every Monday, Wednesday and Thursday.
 
Offline Talus # Posted on 02/15/2007 10:05:02 PM
I'm a dummy.
Avatar
Group : Members
I know, but each time, i've got a syntax error with the ncode :x

WarmBB's Project (still) under developpement (French for the moment)
 
Offline Talus # Posted on 02/16/2007 11:51:17 PM
I'm a dummy.
Avatar
Group : Members
A little "Up" (even if it doesn't really matters, anyway), to post a little function, to check the script's execution's time :

Quote : Script's Execution's Time
Code: PHP
function chrono($time = 0, $round = 3){
    $chrono = array_sum(explode(' ', microtime()));

    return ($time > 0) ? round(abs($chrono - $time), $round) : $chrono;
}


Use :


Code: PHP
(// -- Function)
$chrono = chrono(0);
// -- Your script, anything you want.
echo 'script executed in ' . chrono($chrono, 3) . ' secs.';
?>
Edited on 02/17/2007 11:45:27 AM by Talus

WarmBB's Project (still) under developpement (French for the moment)
 
Offline anonymousguest # Posted on 02/17/2007 12:49:01 AM
I'm the Dude!
Avatar
Group : Members
Are you sure of this : "round(abs($chrono + $time), $round)" ? ^^

"Mondays suck!"
 
Offline Pinedjem # Posted on 02/17/2007 03:47:50 AM
Bouh!
Group : Members
abs() put a number to his positive form so, that function isn't very useful here. Generally, when you do a soustraction with the first number bigger than the second, there is no need to use such function!

Pinedjem

Even the smallest person can change the course of the future.
 
Offline Talus # Posted on 02/17/2007 11:44:00 AM
I'm a dummy.
Avatar
Group : Members
I know, but sometimes, you can have a negative timestamp. That's why i'm usign abs().

(And i've corrected a mistake in the function. Not $chrono + $time, but $chrono - $time =D
Edited on 02/17/2007 11:46:00 AM by Talus

WarmBB's Project (still) under developpement (French for the moment)
 
Offline TheDead Master # Posted on 02/17/2007 04:13:31 PM
4 8 15 16 23 42
Avatar
Group : Members
Quote : Number of queries per page

Code: PHP
<?php
$nb_queries = 0;

function query($query)
{
    global $nb_queries;
    ++$nb_queries;
 
   return mysql_query($query);
}

?>



Usage example:
Code: PHP
<?php

$sql = 'SELECT username
            FROM user'
;

$query = query($sql);

$data = mysql_fetch_assoc($query);

//[...]

echo $nb_queries,' Queries';

?>
Edited on 02/17/2007 09:36:24 PM by TheDead Master
Offline anonymousguest # Posted on 02/17/2007 04:28:41 PM
I'm the Dude!
Avatar
Group : Members
TheDead Master > a ';' is missing in your function.
Talus > that's the mistake I was talking about ;)

"Mondays suck!"
 
Offline Talus # Posted on 02/17/2007 06:59:40 PM
I'm a dummy.
Avatar
Group : Members
Ah, I've believed that you were talking aboout the usage of the abs() function =D

WarmBB's Project (still) under developpement (French for the moment)
 
Offline TheDead Master # Posted on 02/17/2007 09:37:27 PM
4 8 15 16 23 42
Avatar
Group : Members
Quote : anonymousguest
TheDead Master > a ';' is missing in your function.


Oops yes. :huh:
Thanks
Offline TheDead Master # Posted on 05/25/2007 01:21:26 AM
4 8 15 16 23 42
Avatar
Group : Members
Quote: Get ip

Code: PHP
<?php

function getIp($arg = NULL)
{
    if ( !empty($arg) )
    {
        $array_arg = array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR');

        if ( in_array($arg, $array_arg) )
        {
            if ( isset($_SERVER[$arg]) )
                return $_SERVER[$arg];
            else
                return NULL;
        }
    }
    else
    {
        if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) )
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if( isset($_SERVER['HTTP_CLIENT_IP']) )
            return $_SERVER['HTTP_CLIENT_IP'];
        else
            return $_SERVER['REMOTE_ADDR'];
    }
       
}

?>



Usage example:
Code: PHP
<?php

echo getIp();
echo getIp('HTTP_X_FORWARDED_FOR');
echo getIp('HTTP_CLIENT_IP');
echo getIp('REMOTE_ADDR');

?>
Edited on 06/01/2007 04:00:50 PM by TheDead Master
Offline ixM # Posted on 05/25/2007 11:08:15 AM
Made in Belgium
Avatar
Admins
I do really like the $nomber var that is used in a code :D

Everything's a fallacy
 
Offline mwsaz # Posted on 05/25/2007 04:56:25 PM
Tremulous : open source FPS
Avatar
Validators
Quote: Worldedit

Code: PHP
function get_page($page, $nomber_page)
{
        $list_page = array();
        for ($i=1;$i <= $nomber_page;$i++)
        {
                        if (($i < 3) || ($i > $nomber_page - 3) || (($i < $page + 3) && ($i > $page - 3)))
                        $list_page[] = $i;
                        else
                        {
                        if ($i >= 3 && $i <= $page - 3) $i = $page - 3;
                                       
                        elseif ($i >= $page + 3 && $i <= $nomber_page - 3)                                     $i = $nomber_page - $nb;

                        $list_page[] = '...';
                        }
        }
return $list_page;
}


(I hope Winzou don't mind that I use and post his function :s )

1) it's _w_inzou :whistle:
2) Ahem... Isn't this a bug :
Quote
1 2 ... 138 139 140 141 142 ... 298 299 300

sould be
Quote
1 2 3 ... 137 138 139 140 141 142 143 ... 298 299 300


Corrected :
Code: PHP
<?php
        function get_list_page($page, $nb_page, $nb = 3, $delimiter = '...')
                {
                for ($i=1;$i <= $nb_page;$i++)
                        {
                        if (($i <= $nb) OR ($i > $nb_page - $nb) OR (($i <= $page + $nb) AND ($i >= $page - $nb)))
                                $list_page[] = $i;
                        else
                                {
                                if ($i > $nb AND $i <= $page - $nb)
                                        $i = $page - $nb - 1; // -1 beacause the for will do a +1
                                elseif ($i >= $page + $nb AND $i <= $nb_page - $nb)
                                        $i = $nb_page - $nb;
                                $list_page[] = $delimiter;
                                }
                        }
                return $list_page;
                }
               
        echo '<pre>',print_r(get_list_page(20, 50, 3), true),'</pre>';
?>

And I also love the $nomber :p


For the get_ip, it is dangerous to rely on FORWARDED_FOR, as you can put whatever you want in these headers.
You should check both for a ban system.
Edited on 05/25/2007 04:58:30 PM by mwsaz

Computers are like air conditioned : they stop working when you open windows.
About tutorial validation: I deal with newly submitted tutos every Monday, Wednesday and Thursday.
 
Offline Zozor # Posted on 05/25/2007 05:00:55 PM
Hiii Haaan !
Avatar
Group : Banned
Quote: html_specialchars_decode
Code: PHP
<?php
        function html_specialchars_decode($texte)
        {
                $from = array('&gt;', '&lt;', '&#039;', '&quot;', '&amp;');
                $to = array('>', '<', "'", '"', '&');
                $return = str_replace($from, $to, $texte);
                return $return;
        }
?>

This may be useful if you want to accept those signs : “ < ”, “ > ”, “ & ”, “ ' ”, “ " ”.



Quote: TheDead Master
Quote: Number of queries per page

Code: PHP
<?php
$nb_queries = 0;

function query($query)
{
    global $nb_queries;
    ++$nb_queries;
 
   return mysql_query($query);
}

?>


...


Why “ ++$nb_queries; ”? What is the difference with “ $nb_queries++; ”?

Thanks!
Edited on 05/25/2007 05:42:56 PM by Zozor
Offline ixM # Posted on 05/25/2007 05:38:53 PM
Made in Belgium
Avatar
Admins
There is no difference here.

If you had written something like

Code: PHP
<?php
$i = 0;

if($i++ == 0) {
    echo 'OK';
} else {
    echo 'NOK';
}

$i = 0;

if(++$i == 0) {
    echo 'NOK';
} else {
    echo 'OK';
}
?>


You would have two times OK displayed.

++$i increments the var content before using it wehn $i++ use it and then increments it. You can imagine looking at the content while you're working on it :
with ++$i, you would first see it being incremented and the comparison would be done
whereas with $i++ the comparison would be done and then $i would be incremented :)

Cya

Everything's a fallacy
 
Offline Zozor # Posted on 05/25/2007 05:46:15 PM
Hiii Haaan !
Avatar
Group : Banned
Thank you!

I think I will use it in my own scripts!
Offline TheDead Master # Posted on 06/01/2007 04:06:38 PM
4 8 15 16 23 42
Avatar
Group : Members
Quote: mwsaz
For the get_ip, it is dangerous to rely on FORWARDED_FOR, as you can put whatever you want in these headers.
You should check both for a ban system.


Ok, i edited the post.

Thanks :)
Offline fredleshaman # Posted on 09/20/2007 11:05:39 PM
ShowMeYour shortness of breath
Avatar
Group : Members

Percent bar



Code: PHP - Show / hide line numbering
  1. <?php
  2.         function PercentBar($number,$MinFilling,$MaxFilling,$Round)
  3.         {
  4.                 $Percent = ($number-$MinFilling)/(($MaxFilling-$MinFilling)/100);
  5.                 $Green = 2.55*$Percent;
  6.                 $Red = 255-(2.55*$Percent);
  7. ?>
  8.                 <style type="text/css">
  9.                         .PercentBar
  10.                         {
  11.                                 width: 200px;
  12.                                 height: 18px;
  13.                                 border: black 1px solid;
  14.                         }
  15.                         .Bar
  16.                         {
  17.                                 width: <?php echo ceil(2*$Percent);?>px;
  18.                                 height: 18px;
  19.                                 background-color: rgb(<?php echo ceil($Red).','.ceil($Green).',0';?>);
  20.                         }
  21.                 </style>
  22.                 <div class="PercentBar">
  23.                         <div class="Bar">
  24.                         </div>
  25.                 </div>
  26.                 <p class="Percent_Bar">
  27.                         <?php echo (ceil($Percent*$Round))/$Round.'%'; ?>
  28.                 </p>
  29. <?php
  30.         }
  31.         PercentBar(123.334,0,145.4554,1000);
  32. ?>


A little explanation :p :
Here is a function who shows a bar with a pourcent of filling.

For instance, in the last line of my php script:
  • 123.334 is the filling number
  • 0 is the minimum filling of the bar
  • 145.4554 is the maximum filling of the bar
  • 1000 is the decimal average of the number in the text under the bar.


With this exemple, my generated bar will be a lightly green because the filling pourcent is about 84.792%,

But if it's ~10%, the bar will be a dark red.

So, I hope you'll enjoy :) .

bb!
Edited on 11/07/2007 10:05:43 PM by fredleshaman

WWW << (Wh)one Wild Way
 
Offline mwsaz # Posted on 09/27/2007 07:29:25 PM
Tremulous : open source FPS
Avatar
Validators
No french please >_<

Computers are like air conditioned : they stop working when you open windows.
About tutorial validation: I deal with newly submitted tutos every Monday, Wednesday and Thursday.
 
Offline fredleshaman # Posted on 10/24/2007 11:10:59 PM
ShowMeYour shortness of breath
Avatar
Group : Members
Oh, sorry I've just edited the post.

bb.

Edit - Blend: thanks, now it's done :) .
Edited on 10/31/2007 08:08:02 PM by fredleshaman

WWW << (Wh)one Wild Way
 
Offline blend # Posted on 10/30/2007 08:13:44 PM
Group : Members
Please change pourcent by percent :)

Goodbye Microsoft: say "goodbye Windows"!
please,forgive me for my poor english User image
 

Back to "PHP" or to the boards list

You have to be registered to post messages

Change your template | Learn more about NP | Site map | Terms of use | Rules | RSS tutorials | RSS news
Powered by Simple IT SARL: Contact us

There is nothing else to read, you have to go up now !

Do you want to be published here? Contact us.

Number of Newbies connected 4 Newbies Connected | SQL requests 7 Requests | Page loading delay 0.2378s (0.2133s)