Reply LinkBack Thread Tools Search this Thread
Old 21-10-2007, 16:53   #21 (permalink)
KayGee
Registered User
 
Join Date: Oct 2007
Posts: 7
New to PHP...need help

Quote:
Originally Posted by Naatan
Some usefull functions there

Function to get the user IP, since one single technique doesn't always work

PHP Code:
function get_IP() {
    if (empty(
$_SERVER["HTTP_X_FORWARDED_FOR"])) {
        
$ip_address $_SERVER["REMOTE_ADDR"];
    } else {
        
$ip_address $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    if(
strpos($ip_address',') !== false) {
        
$ip_address explode(','$ip_address);
        
$ip_address $ip_address[0];
    }
    return 
$ip_address;


Or this one I got from another site, I don't remember where, it treats a string as if it is included by include();

Only downside is that you can't declare functions since it's already inside a function.

PHP Code:
function phpWrapper($content) {
    global 
$page;
    
ob_start();
    
$content str_replace('<'.'?php','<'.'?',$content);
    eval(
'?'.'>'.trim($content).'<'.'?');
    
$content ob_get_contents();
    
ob_end_clean();
    return 
$content;


Or a function to echo a string and immediatly echo it without delay

PHP Code:
function _echo($echo) {
    echo 
$echo;
    
flush();
    
ob_flush();


This one transforms a filename into a clean string, to be used as a title or whatever (for example, go_go_gadget.exe becomes "Go go gadget"

PHP Code:
function get_filetotitle($title) {
    
$title strip_path($title);
    
$title str_replace('_',' ',$title);
    
$title substr($title0strrpos($title'.'));
    
$bits explode(' ',$title);
    foreach (
$bits AS $bit) {
        
$return .= capitalize_firstchar($bit);
    }
    return 
$return;
}

function 
capitalize_firstchar($string) {
    return 
strtoupper(substr($string,0,1)).substr($string,1);



It appears as though the PHP code above to transform a filename into a clean string is what I've been looking for. I'm on the ground floor with PHP, and without sounding like a complete idiot, I really need to know where this code goes and how to implement it on each of my web pages. I have a div for banner where I'd like the page title to appear. Do I simply place this code in the div?
  Reply With Quote
Old 22-10-2007, 05:01   #22 (permalink)
d*d
Senior Member
 
d*d's Avatar
 
Join Date: Oct 2004
Location: Bristol
Posts: 2,804
lets not pollute this thread with questions and answer sessions, they can be dealt with in a new thread
  Reply With Quote
Old 20-11-2007, 15:34   #23 (permalink)
3n1gm4
Registered User
 
Join Date: Mar 2006
Location: Colleyville, Tx
Posts: 43
heres my pagination link function which will out put something like

<< < 4 5 6 7 8 9 10 > >>

PHP Code:
function page_this($url$page$number_of_items$total_items$trail_length=3$append=false)
{        
    
$number_of_pages ceil($total_items/$number_of_items);        
    
$seperator = (($append)? "&" "?" ;
    
    
// << < 
    
if ( $page != ){
        
$pagination .= "<a href=\"".$url.$seperator."page=1&show=".$number_of_items."\"><<</a> ";
        
$pagination .= "<a href=\"".$url.$seperator."page=".($page-1)."&show=".$number_of_items."\"><</a> ";
    } else {        
        
$pagination .= "<< ";
        
$pagination .= "< ";
    }
    
    
// previous pages
    
$count $page-$trail_length;
    if ( 
$count <= )
        
$count 1;
    for ( ; 
$count $page$count++) {
        
$pagination .= "<a href=\"".$url.$seperator."page=".$count."&show=".$items_per_page."\">".$count."</a>";        
    }
    
    
// current page
    
$pagination .= $page " ";
    
    
// next pages
    
for ( $count $page$count $number_of_pages && $count $page+$trail_length$count++) {
        
$pagination .= "<a href=\"".$url.$seperator."page=".$count."&show=".$items_per_page."\">".$count."</a>  ";
    }
    
    
// > >>
    
if ( $page $number_of_pages ){
        
$pagination .= "<a href=\"".$url.$seperator."page=".($page+1)."&show=".$number_of_items."\">></a> ";
        
$pagination .= "<a href=\"".$url.$seperator."page=".$number_of_pages."&show=".$number_of_items."\">>></a> ";
    } else {
        
$pagination .= "> ";
        
$pagination .= ">> ";
    }
    return 
$pagination;



and a quick simple example

PHP Code:
$conn mysql_connect('localhost','root','');
mysql_select_db('phpnews');

if(isset(
$_GET['page']) && isset($_GET['show']))
{
    
$show $_GET['show'];
    
$limit = ($_GET['page']-1).",".$show;
    
$page $_GET['page'];
}
else
{
    
$show 10;
    
$limit "0,".$show;
    
$page 1;
}



$sql "SELECT * FROM phpnews_news LIMIT " $limit;
$news_rs mysql_query$sql );

$sql "SELECT COUNT(*) as total FROM phpnews_news";
$total_rs mysql_query$sql );
$total mysql_fetch_array($total_rs);

while ( 
$news mysql_fetch_array($news_rs) )
{
    echo 
$news['titletext'] . "<br><br>";
}

echo 
page_this("pagination.php?hello=2",$page,$show,$total['total'],2,1); 
  Reply With Quote
Old 24-11-2007, 16:04   #24 (permalink)
Cborrow
I like code.
 
Join Date: Dec 2004
Location: Chesapeake, VA
Posts: 175
Send a message via AIM to Cborrow
This isn't a function but a bunch of functions(methods) in a container(class)
I created a couple of classes that I use GDImage and GDDraw both in the same file.

I just attached the file because it is pretty big, but I will put a simple example here.

Note: This is still a work in progress, so there might be one or so things that might not work
exactly as planned but so far I have not had any problems what so ever.

PHP Code:
<?php
    header
("Content-type: image/gif");
    
    include 
"GDLibrary.php";
    
    
$image = new GDImage(nullnull"test.jpg");
    
$image->Pixelate(12);
    
$image->Render("gif");
?>

and one more example while using the GDDraw class

PHP Code:
<?php
    header
("Content-type: image/gif");
    
    include 
"GDLibrary.php";
    
    
$image = new GDImage(500400);
    
$image->FillColor("#fff");
    
    
$draw = new GDDraw($image->GetImageResource());
    
$draw->DrawRectangle(101010060"#ff0000");
    
    
$image->Render("gif");
?>

Each method is documented in the classes so it should be pretty easy to see
how everything will work and such.
Attached Files
File Type: zip GDLibrary.zip (3.7 KB, 6 views)
  Reply With Quote
Old 18-12-2007, 11:47   #25 (permalink)
pgo
Moderator
 
pgo's Avatar
 
Join Date: Jan 2005
Location: Brooklyn, NYC
Posts: 11,869
Something I recently wrote...

PHP Code:
function alphanumeric_underscores($string) {
    
// Converts a string into an underscores-instead-of-spaces, all-lower-case, alphanumeric string.
    // "This function isn't too complex" becomes "this_function_isnt_too_complex".
    
$string strtolower($string);
    
$string ereg_replace("[^A-Za-z0-9 ]"""$string);
    
$string str_replace(" ""_"$string);
    return 
$string;

__________________
  Reply With Quote
Old 18-12-2007, 12:45   #26 (permalink)
RaelRode
Designers are strange :)
 
RaelRode's Avatar
 
Join Date: Jan 2007
Location: Shrewsbury, UK
Posts: 1,559
Send a message via ICQ to RaelRode Send a message via AIM to RaelRode Send a message via MSN to RaelRode Send a message via Yahoo to RaelRode Send a message via Skype™ to RaelRode
PHP Code:
function make_safe($make_safe

    {

        if(
get_magic_quotes_gpc())// If magic quotes is enabled

                
{

                    
$string stripslashes($string);//Remove slashes from the string

                
}

                else 
//If not 
                    
{

                        
$make_safe addslashes(trim($make_safe));

                    }

            
$make_safe escapeshellcmd($make_safe); //Remove all SHELL commands

            
$make_safe escapeshellarg($make_safe); //Remove all SHELL commands to be run as an argument

            
$make_safe mysql_real_escape_string($make_safe); //Stop MOST MySQL injections

            
$make_safe stripslashes(strip_tags(htmlspecialchars($make_safeENT_QUOTES))); //Remove XHTML, remove slashes

        

        
return $make_safe// Return the safe string

    
// End make safe functions 

PHP Code:
// This function encrypts users passwords 3 times.

    
function encrypt($encrypt)

    {

        
$encrypt md5($encrypt); // Encrypt the string to MD5

        
$encrypt sha1($encrypt); // Encrypt the MD5 string to SHA1

        
$encrypt md5($encrypt); // Encrypt the SHA1 string to MD5 AGAIN!!

        
return $encrypt// Return the encrypted string.

    
// End encryption function 

PHP Code:
// This function check if a user has used a correct email, if not, it dies.

    
function check_email($check_email

    {

        
$_name "/^[-!#$%&'*+./0-9=?A-Z^_`{|}~]+"// Name check, bit before @

        
$_host "([-0-9A-Z]+.)+"// Host check, bit after @

        
$_tlds "([0-9A-Z]){2,4}$/i"// TLD check, bit after .

        

            
if(!preg_match($_name."@".$_host .$_tlds,$email)) // If the email isn't valid..

                
{

                    die(
"Please enter a valid email address"); // Kill the function

                
}

                else 
// if email is valid

                    
{

                    return 
$check_email// Return the email string

                    
}

    } 
// End check email function



These aren't too complex, but they work, so yeah. Happy XMAS!!!!!!

I love using die(); in my scripts. XD
__________________
If it works, it's valid.

Last edited by RaelRode : 18-12-2007 at 15:59.
  Reply With Quote
Old 18-12-2007, 15:50   #27 (permalink)
proc355
Trailer Trash™
 
proc355's Avatar
 
Join Date: Sep 2006
Posts: 851
rael: comments, meant to be constructive ok? and i've avoided php for ages now so really only general stuff

it's hashing not encryption; also, dont multi-hash things - it does nothing except chew resources - you want a salted hash

you're checking for magic quotes twice which is just a waste of resources - lose the elseif and just else it

surely a method that checks for the validity of something should return a boolean rather than a string? (check_email).

your naming sucks i.e. check_email - perhaps is_valid_format_email instead? slightly more verbose but it reads better, follows php conventions and allows for a consistent scheme e.g. is_valid_format_address etc.

naming your args the same as your methods is useless
__________________
meh.
  Reply With Quote
Old 18-12-2007, 15:59   #28 (permalink)
RaelRode
Designers are strange :)
 
RaelRode's Avatar
 
Join Date: Jan 2007
Location: Shrewsbury, UK
Posts: 1,559
Send a message via ICQ to RaelRode Send a message via AIM to RaelRode Send a message via MSN to RaelRode Send a message via Yahoo to RaelRode Send a message via Skype™ to RaelRode
I commented it because I wasn't the only developer, and I was giving it to my friend who wanted to learn PHP.

Naming convention, ok I see your point.

The make_safe function...well yeah it seemed logical before but maybe not...shit. Lol.

Oh and as for the mutiple encryption / encoding, I will write a new one later on.
__________________
If it works, it's valid.
  Reply With Quote
Old 18-12-2007, 16:31   #29 (permalink)
proc355
Trailer Trash™
 
proc355's Avatar
 
Join Date: Sep 2006
Posts: 851
lol i didnt mean your comments
__________________
meh.
  Reply With Quote
Old 02-01-2008, 14:34   #30 (permalink)
brucec
Podcaster on Web Design
 
Join Date: Jan 2008
Posts: 27
Send a message via AIM to brucec Send a message via Skype™ to brucec
Used for security redirects while users log in. It works well.

PHP Code:
function LoginRedirect($u,$p)
{
$users=fill with 2 dimensional array of users and passwords;
$error CREATE LOGIN ERROR HERE;
$url URL to redirect user to.

    
$enteredUsername $u
    $enteredPassword 
$p;

    for(
$r=0$r<sizeOf($users); $r++)
    {
        if(
$users[$r][0]==$enteredUsername)
        {
            if(
$users[$r][1]==$enteredPassword)
            {
                
$_SESSION['loggedin']="yes";
                
$_SESSION['username']=$enteredUsername;
                
$_SESSION['contact']=$users[$r][2];
                
header("Location:$url");
            } 

            break;
        }
    }

}
return 
$error;

  Reply With Quote
Old 08-01-2008, 07:29   #31 (permalink)
PoeT4eva41
rock n' roller
 
PoeT4eva41's Avatar
 
Join Date: Jul 2007
Location: Yerevan, Armenia
Posts: 37
Send a message via ICQ to PoeT4eva41 Send a message via MSN to PoeT4eva41 Send a message via Skype™ to PoeT4eva41
Wow awesome scripts, specially this one.

Quote:
Originally Posted by RaelRode
PHP Code:
// This function encrypts users passwords 3 times.

    
function encrypt($encrypt)

    {

        
$encrypt md5($encrypt); // Encrypt the string to MD5

        
$encrypt sha1($encrypt); // Encrypt the MD5 string to SHA1

        
$encrypt md5($encrypt); // Encrypt the SHA1 string to MD5 AGAIN!!

        
return $encrypt// Return the encrypted string.

    
// End encryption function 

And one from me.

PHP Code:
echo 'something'
To write something, on the page.
  Reply With Quote
Old 08-01-2008, 07:41   #32 (permalink)
Mesrop
www.mesrop.info
 
Mesrop's Avatar
 
Join Date: Jan 2008
Location: Armenia
Posts: 2
Send a message via ICQ to Mesrop Send a message via AIM to Mesrop Send a message via MSN to Mesrop Send a message via Yahoo to Mesrop Send a message via Skype™ to Mesrop
my simple and useful func.
PHP Code:
function querysingle($query$i=0){
$result=@mysql_query($query);
$row=@mysql_fetch_array($result);
return 
$row[$i];

Quote:
$string=querysingle("select `name` from `users` where `id`='1' ");
or
Quote:
$string=querysingle("select * from `users` where `id`='1' ", "name");
  Reply With Quote
Old 08-01-2008, 14:27   #33 (permalink)
Cborrow
I like code.
 
Join Date: Dec 2004
Location: Chesapeake, VA
Posts: 175
Send a message via AIM to Cborrow
Got a easy to use function for resizing images, while keeping the aspect ratio.

The function.

PHP Code:
<?php
    
/*
        ImageThumb - Creates a thumbnail image from another based on specified sizes
        
        SourceImage - The location of the image in which you want to resize
        DestImage - The location to save the thumb, use null if you want to just display to browser
        Width - The resized width of the image
        Height - The resized height of the image
        Type - The image type in which you want to save
        
        Note: The thumb is resized while keeping the aspect ratio, so width and height are not the
        absolute width and height.
    */
    
    
function ImageThumb($sourceImage$destImage$width$height$type "png") {
        
$imageSize getimagesize($sourceImage);
        
        if(
$imageSize[0] > $imageSize[1]) {
            
$newWidth $width;
            
$newHeight $imageSize[1] * ($newWidth $imageSize[0]);
        }