AUS/NZ
PC PS XBOX GIRL TV STORE
Login:
? Sign Up!
Powered by AMD
E-Sports Communities & Competitions

PHP Code Snippets

Started by Hytek on 9:23am 26/8/11. 641 views and 15 posts, 0 users reading, last post by tixx.

Currently reading (0 users):
OP
Joined: 16/2/09
Posts: 971
Defaults: AU - PC: Counter-Strike Source
using Firefox 12.0
Rep:
46%
Moderator
I will be posting a variety of small PHP code snippets and functions which can easily be modified and integrated into your existing PHP code.

If you would like me to explain any snippet in this thread or assist you with using them in your code then please let me know. Feel free to request a snippet.


#1 Get a users IP address

Function
Add this function to your config/settings file or at the top of the file where it is going to be used.
CODE:
<?php
function get_ip(){
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return trim($ip);
}
?>
Usage
This code will store the users IP address in a variable and display it on the page.
CODE:
<?php
$ip_address = get_ip();
echo $ip_address;
?>


#2 Generate a random string

Function
Add this function to your config/settings file or at the top of the file where it is going to be used.
CODE:
<?php
function rand_string($length){
$str = '';
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for ($i = 0; $i < $length; $i++) {
$str .= $chars[rand(0, $size - 1)];
}
return $str;
}
?>
Usage
This code will generate a 32 character string and display it on the page.
CODE:
<?php
$string = rand_string(32);
echo $string;
?>


#3 Filter user input

Function
Add this function to your config/settings file or at the top of the file where it is going to be used.
CODE:
<?php
function filter($data){
$data = trim(htmlentities(strip_tags($data)));
if(get_magic_quotes_gpc()){
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
}
return $data;
}
?>
Usage
This code will filter user input ($_POST) from a form using and store the clean input in a variable. (Please note: A MySQL connection must be opened before using this function)
CODE:
<?php
foreach($_POST as $key => $value){
$data[$key] = filter($value);
}
$username = $data['username'];
?>


#4 Check if key exists in an array

Function
Add this function to your config/settings file or at the top of the file where it is going to be used.
CODE:
<?php
function safeOutput($arr,$index) {
if (isset ($arr[$index]) ) {
return $arr[$index];
} else {
return 'N/A';
}
}
?>
Usage
This code will check the an array (variable $array) for the specified key words.
CODE:
<?php
$array = array('php'=>'yes');
$tick = safeOutput($array, 'php');
$tack = safeOutput($array, 'other');

echo $tick;
echo '<br/>';
echo $tack;
?>

Returns
yes
N/A


#5 Console debugging log

Function
Add this function to your config/settings file or at the top of the file where it is going to be used.
CODE:
<?php
function debug(str, isFunction) {
//----------------------------------------------
$prefix = "";
if (isFunction) {
prefix = "* ";
} else {
prefix = " - ";
}
try {
console.log(prefix + str);
} catch (e) {

}
}

debug("Document ready", true);
debug(currentPos, false);
?>
Usage
Check your console.
CODE:
Easy way to track what's running what.
Should output functions with * and non functions with -


#6 Check string/variable for data

Function
CODE:
<?php
function isEmpty($str) {
//----------------------------------------------
if (($str === null) || ($str === undefined) || ($str === "" )) {
return true;
} else {
return false;
}
}
?>
Usage
CODE:
<?php
$queryOne = "";
$queryTwo = "input";

if(!isEmpty($queryOne)){
echo "isn't empty <br/>";
} else {
echo "is empty <br/>";
}

if(!isEmpty($queryTwo)){
echo "isn't empty <br/>";
} else {
echo "is empty <br/>";
}
?>

Returns
is empty
isn't empty


Edited twice, last edited 31/8/11 - 9:16am.
Posted on Friday, 26th August 2011
Joined: 24/11/10
Posts: 607
Defaults: AU - PC: Call of Duty
using Firefox 11.0
Rep:
35%
Thanks for the snippets
Will come in use for someone, might post a few up of my own at some point.

Edited once, 2/3/12 - 7:38am by #striker.
Posted on Friday, 26th August 2011
There's no shortage of competition. DICE are standing in the sidelines ready to take the crown.
OP
Joined: 16/2/09
Posts: 971
Defaults: AU - PC: Counter-Strike Source
using Firefox 12.0
Rep:
46%
Moderator
Thanks Bankzy. Feel free to post your own and I'll add them to the first post.
Posted on Friday, 26th August 2011
Joined: 3/9/09
Posts: 3,578
Defaults: AU - PC: Call of Duty
using Firefox 12.0
Rep:
55%
Moderator
Who's this Hytek guy, haven't seen him around in a while! Nice work mate, you've been a great help in this area since the start.

Edited once, 2/3/12 - 7:38am.
Posted on Friday, 26th August 2011
Imitation: The greatest form of flattery. But seriously, piss off.
Joined: 24/11/10
Posts: 607
Defaults: AU - PC: Call of Duty
using Firefox 11.0
Rep:
35%
If key exists in array
CODE:

<?php
function safeOutput($arr,$index) {
if (isset ($arr[$index]) ) {
return $arr[$index];
} else {
return 'N/A';
}
}
$array = array('php'=>'yes');
$tick = safeOutput($array, 'php');
$tack = safeOutput($array, 'other');

echo $tick;
echo '<br/>';
echo $tack;
?>

returns
yes
N/A


Console debug tracking log
CODE:

<?php
function debug(str, isFunction) {
//----------------------------------------------
$prefix = "";
if (isFunction) {
prefix = "* ";
} else {
prefix = " - ";
}
try {
console.log(prefix + str);
} catch (e) {

}
}

debug("Document ready", true);
debug(currentPos, false);
?>

Easy way to track whats running what. (outputs in console)
Should output functions with * and non functions with -

If nothing available
CODE:

<?php
function isEmpty($str) {
//----------------------------------------------
if (($str === null) || ($str === undefined) || ($str === "" )) {
return true;
} else {
return false;
}
}

$queryOne = "";
$queryTwo = "input";

if(!isEmpty($queryOne)){
echo "isn't empty <br/>";
} else {
echo "is empty <br/>";
}

if(!isEmpty($queryTwo)){
echo "isn't empty <br/>";
} else {
echo "is empty <br/>";
}
?>

returns
is empty
isn't empty



Edited 4 times, last edited 26/8/11 - 1:40pm.
Posted on Friday, 26th August 2011
There's no shortage of competition. DICE are standing in the sidelines ready to take the crown.
OP
Joined: 16/2/09
Posts: 971
Defaults: AU - PC: Counter-Strike Source
using Firefox 12.0
Rep:
46%
Moderator
Hey striker, long time no see buddy. I've been MIA for a while.. but I'm back!

Thanks Bankzy, I'll add them shortly.
Posted on Friday, 26th August 2011
Joined: 8/7/09
Posts: 2,374
Defaults: AU - PC: Counter-Strike Source
using Chrome 19.0
Rep:
58%
Game Administrator
Great idea Hytek

Just some amateur things:

(Very) Simple Password Protected Page

Great for learning how to use PHP, I don't recommend for anything overly secure (perhaps a hidden forum would be suitable etc).

CODE:
<?php
$password = "lol"; //Set to whatever you want
// If password is valid let the user get access
if (isset($_POST['edt_password']) && ($_POST['edt_password']=="$password") { ?>
<!-- HTML CODE GOES HERE -->
<?php
}
else
{
// Wrong password or password not yet entered display this message
if (isset($_POST['password']) || $password == "" {
print "<p align=\"center\"><font color=\"red\"><b>Incorrect Password</b><br>Please enter the correct password</font></p>";} ?>
<? } ?>
<form method="post"><p align="center">Please enter your password for access<br>
<input name="edt_password" type="password" size="25" maxlength="10"><input value="Login" type="submit"></p></form>


Input Sanitize Function

CODE:
function clean($string) {
$string = @trim($string);
if(get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return mysql_real_escape_string($string);
}

edit: I see you have the exact same thing, never mind.

Edited once, 26/8/11 - 7:16pm.
Posted on Friday, 26th August 2011
No longer a CSS admin, please stop PMing me.
Joined: 17/12/07
Posts: 547
Defaults: AU - PC: World of Warcraft
using Chrome 19.0
Rep:
65%
Game Administrator
Just let it be known that mysql_real_escape_string can only be used when sql is open.

so for example:

function addUser($input) {

mysql open

$input = clean($input)

insert $input

mysql close

(I'm sure you all know this. Just bringing it up in case somebody new decides to test that clean function)
Posted on Monday, 29th August 2011
Joined: 8/7/09
Posts: 2,374
Defaults: AU - PC: Counter-Strike Source
using Chrome 19.0
Rep:
58%
Game Administrator
READ THIS
Quote from nimr0d17 on the 29th of August 2011:
Just let it be known that mysql_real_escape_string can only be used when sql is open.

so for example:

function addUser($input) {

mysql open

$input = clean($input)

insert $input

mysql close

(I'm sure you all know this. Just bringing it up in case somebody new decides to test that clean function)

Very true, I should have taken that into consideration...thanks (and on behalf of anyone who reads this) for the heads up!
Posted on Tuesday, 30th August 2011
No longer a CSS admin, please stop PMing me.
Joined: 8/7/09
Posts: 2,374
Defaults: AU - PC: Counter-Strike Source
using Chrome 19.0
Rep:
58%
Game Administrator
Found this on php.net - it's really nifty.

Multiple Explode function
CODE:
<?php
function multipleExplode($delimiters = array(), $string = ''){

$mainDelim=$delimiters[count($delimiters)-1]; // dernier

array_pop($delimiters);

foreach($delimiters as $delimiter){

$string= str_replace($delimiter, $mainDelim, $string);

}

$result= explode($mainDelim, $string);
return $result;

}
?>
Posted on Wednesday, 28th September 2011
No longer a CSS admin, please stop PMing me.
Joined: 8/7/09
Posts: 2,374
Defaults: AU - PC: Counter-Strike Source
using Chrome 19.0
Rep:
58%
Game Administrator
BUMP

Incremental Rounder:
<?php
function round_to($number, $increments) {
$increments = 1 / $increments;
return (round($number * $increments) / $increments);
}
?>


Usage - you want to round a number to halves.

<?php
$n = 5.3;
echo round_to($n, 0.5); // 5.5
?>
Posted on Saturday, 15th October 2011
No longer a CSS admin, please stop PMing me.
Joined: 23/6/08
Posts: 5,117
using Chrome 1337
Rep:
52%
It's probably faster just to use the function on it's own, rather than putting a function inside a function.

http://php.net/manual/en/function.round.php
Posted on Thursday, 20th October 2011
Joined: 8/7/09
Posts: 2,374
Defaults: AU - PC: Counter-Strike Source
using Chrome 19.0
Rep:
58%
Game Administrator
bump
Posted on Wednesday, 29th February 2012
No longer a CSS admin, please stop PMing me.
Joined: 2/3/10
Posts: 3,504
Defaults: AU - PC: Call of Duty: MW3
using Chrome 19.0
Rep:
46%
nice job
Posted on Friday, 2nd March 2012
Need A Website or GFX? http://pureenvee.com | Need To Upload Images? http://miscupload.com
Joined: 9/10/08
Posts: 349
Defaults: AU - PC: Battlefield
using Chrome 19.0
Rep:
33%
some multidimensional array code for a pugbot i am making ( decided against serialized arrays after all )

CODE:


public function AddtoTeam($pid,$name,$team){
$p = $this->connection->get('pugs','Players','PID='.$pid);
$p = unserialize($p); //
if ($this->TeamSizeChk($p,$team) < 4 && $this->in_array_r($name,$p) == 0){ // CHECK T SIZE
array_push($p[$team],$name); // PUSH NAME INTO SPECIFIC TEAM
$s = serialize($p);
$d = array('Players' => array($s)); // BUILD SQL DATA UPDATE ARRAY
$q = $this->connection->update('pugs',$d,'PID='.$pid); // PUSH AND UPDATE DB
}
var_dump($p);
}

public function RemPlayer($pid,$name){
$p = $this->connection->get('pugs','Players','PID='.$pid);
$p = unserialize($p);
if ($this->in_array_r($name,$p) == 1){
$p = $this->remove_element_by_value($p,$name);
$s = serialize($p);
$d = array('Players' => array($s)); // BUILD SQL DATA UPDATE ARRAY
$q = $this->connection->update('pugs',$d,'PID='.$pid); // PUSH AND UPDATE DB
}
var_dump($p);
}

////////////////////////////////////////////////////
// WORKER FUNCS //
////////////////////////////////////////////////////

public function in_array_r($needle, $haystack, $strict = true) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && $this->in_array_r($needle, $item, $strict))) {
return true;
}
}

return false;
}


function remove_element_by_value($arr, $val) {
$return = array();
foreach($arr as $k => $v) {
if(is_array($v)) {
$return[$k] = $this->remove_element_by_value($v, $val); //recursion
continue;
}
if($v == $val) continue;
$return[$k] = $v;
}
return $return;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\




Posted on Sunday, 4th March 2012
"Alpha, Bravo, Charlie . . . . This is command"
 

PHP Code Snippets