List of useful functions

Started on the old forum in September 2010 · view the original in the archive · old links redirect here

1 reply · 1,066 views · started 16 years ago · 2 min read

2 participants
robzky Developer · 205 posts #1

Get current date in isoformat

function isoDate()
{        
    return date("Y-m-d");
}

Open database connection

function open_connection($host, $username, $password, $database)
{
    $conn = mysql_connect($host, $username, $password) or trigger_error(mysql_error(), E_USER_ERROR);
    mysql_select_db($database), $this->conn);        
}

Execute a query

function query($query, $conn)
{
        $rSet = mysql_query($query, $conn)) or die("Query failed: ".mysql_error());
        return $rSet;
}

Remote IP address

function getRemoteIPAddress()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    return $ip;
}

Generate random string

function password($length)
{
    srand((double)microtime()*100);
    return substr(md5(uniqid(rand())),0,$length);
}

base64 url encrypt

function base64url_encode($plainText)
{
    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}

base64 url decrypt

function base64url_decode($plainText) {
    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

Send email

function mailMsg($to, $subject, $message, $headers)
{
    mail($to,$subject,$message,$headers);
}

Check if email is valid

function email_validate
{
    $email = $_POST['email'];
    if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email))
    {
        echo 'This is a valid email.';
    }
    else
    {
        echo 'This is an invalid email.';
    }
}

Censor word from a database

function censor($msg, $collumn, $table)
{
    // uses database
    global $db;
    $rSet = $db->query("select * from $table");

    while ($tRow = mysql_fetch_assoc($rSet))
    {
        $msg = str_replace($tRow[$collumn], "[Censored]", $msg);
    }

    return $msg;
}

Encode email

function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )
{
    $email = str_replace('@', '@', $email);
    $email = str_replace('.', '.', $email);
    $email = str_split($email, 5);

    $linkText = str_replace('@', '@', $linkText);
    $linkText = str_replace('.', '.', $linkText);
    $linkText = str_split($linkText, 5);

    $part1 = '<a href="ma';
    $part2 = 'ilto&#58;';
    $part3 = '" '. $attrs .' >';
    $part4 = '</a>';

    $encoded = '<script type="text/javascript">';
    $encoded .= "document.write('$part1');";
    $encoded .= "document.write('$part2');";
    foreach($email as $e)
    {
            $encoded .= "document.write('$e');";
    }
    $encoded .= "document.write('$part3');";
    foreach($linkText as $l)
    {
            $encoded .= "document.write('$l');";
    }
    $encoded .= "document.write('$part4');";
    $encoded .= '</script>';

    return $encoded;
}

Force download

function force_download($file)
{
    if ((isset($file))&&(file_exists($file)))
    {
          header("Content-length: ".filesize($file));
          header('Content-Type: application/octet-stream');
          header('Content-Disposition: attachment; filename="' . $file . '"');
          readfile("$file");
        }
    else
    {
          echo "No file selected";
        }
}

Inverse color

function color_inverse($color)
{
    $color = str_replace('#', '', $color);
    if (strlen($color) != 6){ return '00'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
  $c = 255 - hexdec(substr($color,(2*$x),2));
  $c = ($c < 0) ? 0 : dechex($c);
  $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
   }
    return '#'.$rgb;
}

Xor encryption

function XOREncryption($InputString, $KeyPhrase){

    $KeyPhraseLength = strlen($KeyPhrase);

    // Loop trough input string
    for ($i = 0; $i < strlen($InputString); $i++){

  // Get key phrase character position
  $rPos = $i % $KeyPhraseLength;

  // Magic happens here:
  $r = ord($InputString[$i]) ^ ord($KeyPhrase[$rPos]);

  // Replace characters
  $InputString[$i] = chr($r);
    }

    return $InputString;
}

Syntax Highlighting

function syntax_highlight($code){

    // this matches --> "foobar" <--
    $code = preg_replace(
  '/"(.*?)"/U',
  '"<span style="color: #007F00">$1</span>"', $code
    );

    // hightlight functions and other structures like --> function foobar() <---
    $code = preg_replace(
  '/(\s)\b(.*?)((\b|\s)\()/U',
  '$1<span style="color: #0000ff">$2</span>$3',
  $code
    );

    // Match comments (like /* */):
    $code = preg_replace(
  '/(\/\/)(.+)\s/',
  '<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>',
  $code
    );

    $code = preg_replace(
  '/(\/\*.*?\*\/)/s',
  '<span style="color: #660066; background-color: #FFFCB1;"><i>$0</i></span>',
  $code
    );

    // hightlight braces:
    $code = preg_replace('/(\(|\[|\{|\}|\]|\)|\->)/', '<strong>$1</strong>', $code);

    // hightlight variables $foobar
    $code = preg_replace(
  '/(\$[a-zA-Z0-9_]+)/', '<span style="color: #0000B3">$1</span>', $code
    );

    /* The \b in the pattern indicates a word boundary, so only the distinct
    ** word "web" is matched, and not a word partial like "webbing" or "cobweb"
    */

    // special words and functions
    $code = preg_replace(
  '/\b(print|echo|new|function)\b/',
  '<span style="color: #7F007F">$1</span>', $code
    );

    return $code;
}

Jpg to ASCII

function getext($filename) {
    $pos = strrpos($filename,'.');
    $str = substr($filename, $pos);
    return $str;
}
if(!isset($_POST['submit'])){
?>
<form action="<?echo $_SERVER['PHP_SELF'];?>" method="post">
    JPG img URL: <input type="text" name="image"><br>
    <input type="submit" name="submit" value="Create">
</form>
<?
}else{
    $image = $_POST['image'];
    $ext = getext($image);
    if($ext == ".jpg"){
  $img = ImageCreateFromJpeg($image);
    }
    else{
  echo'Wrong File Type';
    }
    $width = imagesx($img);
    $height = imagesy($img);

    for($h=0;$h<$height;$h++){
  for($w=0;$w<=$width;$w++){
    $rgb = ImageColorAt($img, $w, $h);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    if($w == $width){
    echo '<br>';
    }else{
    echo '<span style="color:rgb('.$r.','.$g.','.$b.');">#</span>';
    }
  }
    }
}

Generate random string

function randomString
{
    $string = "abcdefghijklmnopqrstuvwxyz0123456789";
    for($i=0;$i<25;$i++)
    {
            $pos = rand(0,36);
            $str .= $string{$pos};
    }
    echo $str;
}

Html to text

function html2txt($document)
{
  $search = array('@<script[^>]*?>.*?</script>@si', // Strip out javascript
  '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
  '@<[?]php[^>].*?[?]>@si', //scripts php
  '@<[?][^>].*?[?]>@si', //scripts php
  '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
  '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA
  );$text = preg_replace($search, '', $document);
  return $text;
}

Convert url to spam

function getTinyUrl($url)
{
    return file_get_contents("http://spam.com/api-create.php?url=".$url);
}

Get destination url of a spam

function untinyUrl($spam){
    if($fp = fsockopen ("spam.com", 80, $errno, $errstr, 30)){
        if ($fp) {
            fputs ($fp, "HEAD /$spam HTTP/1.0\r\nHost: spam.com\r\n\r\n");
            $headers = '';
            while (!feof($fp)) {
                $headers .= fgets ($fp,128);
            }
            fclose ($fp);
        }

        $arr1=explode("Location:",$headers);
        $arr=explode("\n",trim($arr1[1]));
        echo trim($arr[0]);
    }
}

NEXT TIME WHEN U POST CODES DO ADD IN IN [CODE FORMATS PLEASE

LESS TALK. LESS MISTAKE.

HTTP://APPSROB.COM - LIST OF MY FACEBOOK APPS!

Mysterio Lead · 630 posts #2
function extract_links($s) {
$res = array();
preg_match_all('@(<a .*</a>)@Uis', $s, $a);
foreach ($a[1] as $x) {
$gtpos = strpos($x, '>');
$y = substr($x, 0, $gtpos);
if ($hrefpos = strpos($x, 'href=')) {
$z = substr($y, $hrefpos+5);
$z = preg_replace('/^(\S+)\s.*$/U', '$1', $z);
if ($z[0] == '"' && substr($z, -1) == '"') $z = substr($z, 1, -1);
if ($z[0] == "'" && substr($z, -1) == "'") $z = substr($z, 1, -1);
$res[] = array(substr($x, $gtpos+1, -4), $z);
}
}
unset($a);
return $res;
}

Use the function with this code (or code like this):

$links = extract_links($s);
foreach ($links as $v) {
print "<a href='$v[1]'>$v[0]</a><br/>";
}

For the function, $s is some source code. You may grab some source code using file_get_contents.

mysterio.al - programming is a functional art

Write your reply now; next you create a free account (or sign in) and it is posted right away. Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close