Saturday, April 7, 2012

Unzip Files

Unzip Files

<?php
$zip = zip_open("zip.zip");
if (is_resource($zip)) {
  while ($zip_entry = zip_read($zip)) {
    $fp = fopen("zip/".zip_entry_name($zip_entry), "w");
    if (zip_entry_open($zip, $zip_entry, "r")) {
      $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
      fwrite($fp,"$buf");
      zip_entry_close($zip_entry);
      fclose($fp);
    }
  }
  zip_close($zip);
}
?>

 

URL Validation

URL Validation

$url = 'http://example.com';
$validation = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);

if ( $validation ) $output = 'proper URL';
else $output = 'wrong URL';

echo $output;

 

Update Values of Entire Table

Update Values of Entire Table

This code assumes you are connected to a MySQL database which has a table with Names and Emails. The idea is that it will output a table of every single value from that table, as text inputs. You can then alter the values of these inputs and re-submit, updating all the values in the database.

//get data from db
$sql = mysql_query("SELECT * FROM table");
$count=mysql_num_rows($sql);

//start a table
echo '<form name="form1" method="post" action="">
<table width="292" border="0" cellspacing="1" cellpadding="0">';

//start header of table
echo '<tr>
<th>&nbsp;</th>
<th>Name</th>
<th>Email</th>
</tr>';

//loop through all results
while($r=mysql_fetch_object($sql)){

//print out table contents and add id into an array and email into an array
echo '<tr>
<td><input type="hidden" name="id[]" value='.$r->id.' readonly></td>
<td>'.$r->name.'</td>
<td><input name="email[]" type="text" id="price" value="'.$r->email.'"></td>
</tr>';
}

//submit button
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';

// if form has been submitted, process it
if($_POST["Submit"])
{
       // get data from form
       $name = $_POST['name'];
       // loop through all array items
   foreach($_POST['id'] as $value)
       {
       // minus value by 1 since arrays start at 0
               $item = $value-1;
               //update table
       $sql1 = mysql_query("UPDATE table SET email='$email[$item]' WHERE id='$value'") or die(mysql_error());
   }

// redirect user
$_SESSION['success'] = 'Updated';
header("location:index.php");
}
Submitted values are not cleaned in this example, as it is assumed only an admin would have access to this type of powerful entry system.

Variable Variables

Variable Variables

<?php

  $var1 = 'nameOfVariable';

  $nameOfVariable = 'This is the value I want!';

  echo $$var1; 

?>

 

Zero Padded Numbers

Zero Padded Numbers

function getZeroPaddedNumber($value, $padding) {
       return str_pad($value, $padding, "0", STR_PAD_LEFT);
}

Usage

echo getZeroPaddedNumber(123, 4);
// outputs "0123"

POST Validation Loop

POST Validation Loop

Assumptions

You have an HTML form with a variety of inputs. The action attribute of the form points to a PHP file that contains the code below.

Notes about code

This code starts by creating an array that holds the name of various inputs being submitted via a POST. getFormData() is then called, where the required fields are passed in. Inside the function an array is created to hold various pieces of data related to the form. $formData['valid'] is a boolean referencing if all data was provided and valid, $formData['fields'] is an array keyed by the name of the input with their respective value from the POST data, $formData['notValidFields'] is an array that will contain the names of any inputs that were not passed or that had non-valid data.
This logic can be easily extended with regular expressions to check for stricter data, such as email addresses and urls.

<?php

$requiredFields = array('field1', 'field2', 'field3', 'field4');
$formData = getFormData($requiredFields);

function getFormData($requiredFields){
       $formData = array();
       $formData['valid'] = true;
       $formData['fields'] = array();
       $formData['notValidFields'] = array();

       for($a = 0; $a < count($requiredFields); $a++){
               $field = $requiredFields[$a];
               if(isset($_POST[$field])){
                       $value = $_POST[$field];
                       if(empty($value)){
                               $formData['valid'] = false;
                               $formData['notValidFields'][] = $field;
                       }else{
                               $formData['fields'][$field] = $value;
                       }
               }else{
                       $formData['valid'] = false;
                       $formData['notValidFields'][] = $field;
               }
       }
       return $formData;
}

PHP Redirect

PHP Redirect

<?php
  header( 'Location: http://www.yoursite.com/new_page.html' ) ;
?>

PHP Include

PHP Include

Can be used multiple times:

<?php include("navigation.php"); ?>

Once only:

<?php include_once("navigation.php"); ?>

Including from the root:

<?php
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/common/header.php";
   include_once($path);
?>

Intelligent PHP Cache Control

Intelligent PHP Cache Control

This code snippet checks if a page has been modified since it was last displayed. If so, it sends a "304 not modified" header and exits, otherwise the content is rendered. Prepend this snippet on top of every PHP file you want to apply this intelligent caching-mechanism. Especially useful if you (have to) serve static content via php and want it to be cached like ordinary HTML or CSS.

<?php
//get the last-modified-date of this very file
$lastModified=filemtime(__FILE__);
//get a unique hash of this file (etag)
$etagFile = md5_file(__FILE__);
//get the HTTP_IF_MODIFIED_SINCE header if set
$ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false);
//get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash)
$etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false);

//set last-modified header
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT");
//set etag-header
header("Etag: $etagFile");
//make sure caching is turned on
header('Cache-Control: public');

//check if page has changed. If not, send 304 and exit
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile)
{
       header("HTTP/1.1 304 Not Modified");
       exit;
}

//your normal code
echo "This page was last modified: ".date("d.m.Y H:i:s",time());

?>

Increase Maximum PHP Upload Size

Increase Maximum PHP Upload Size

 Many shared hosts put very low restrictions on the size of the files that can be uploaded through PHP. But, many hosts also allow you to create your own php.ini file in the root directory of your site. This file can override some of the servers default PHP settings. If not already done simply create a php.ini file and place in the public_html directory of your site. If the server is configured correctly, after inserting this snippet the servers default max upload will be overridden. For this example it was changed to 20 megabytes.

 

; Maximum file size of post data that PHP will accept.
post_max_size = 20M

; Maximum allowed file size for uploaded files.
upload_max_filesize = 20M
Or you may need to preface with php_value:
php_value upload_max_filesize 100M
php_value post_max_size 100M

Get Image Information

Get Image Information

/*
 * @param string $file Filepath
 * @param string $query Needed information (0 = width, 1 = height, 2 = mime-type)
 * @return string Fileinfo
 */

function getImageinfo($file, $query) {
       if (!realpath($file)) {
               $file = $_SERVER["DOCUMENT_ROOT"].$file;
       }
       $image = getimagesize($file);
       return $image[$query];
}

 

Get File Size PHP

Get File Size

/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function getFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
                       }
               return round($fileSize, $digits)." ".$sizes[$total];
       }
       return false;
}

 

Get File Last Updated Date

Get File Last Updated Date

/*
 * @param string $file Filepath
 * @param string $format dateformat
 * @link http://www.php.net/manual/de/function.date.php
 * @link http://www.php.net/manual/de/function.filemtime.php
 * @return string|bool Date or Boolean
 */

function getFiledate($file, $format) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
               $fileDate = filemtime($filePath);
               if ($fileDate) {
                       $fileDate = date("$format",$fileDate);
                       return $fileDate;
               }
               return false;
       }
       return false;
}

 

Get Current File Name PHP

Get Current File Name

<?php
    $pageName = basename($_SERVER[PHP_SELF]);
?>

Potential use:

<body id="body_<?php echo $pageName; ?>">
Append ID to body to do different CSS styles on different pages.

Find URLs in Text, Make Links

Find URLs in Text, Make Links

<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);

} else {

       // if no urls in the text just return the text
       echo $text;

}
?>
The basic function of this is to find any URLs in the block of text and turn them into hyperlinks. It will only find URLs if they are properly formatted, meaning they have a http, https, ftp or ftps.
Check out the comments below for more solutions.

 

Find File Extension PHP

Find File Extension

Method 1

function findexts ($filename) {

       $filename = strtolower($filename) ;

       $exts = split("[/\\.]", $filename) ;

       $n = count($exts)-1;

       $exts = $exts[$n];

       return $exts;

}

 

Method 2

$filename = 'mypic.gif';
$ext = pathinfo($filename, PATHINFO_EXTENSION);

Method 3

function getFileextension($file) {
       return end(explode(".", $file));
}

 


 

 

Count Script Excecution Time

Count Script Excecution Time

$execution_time = microtime(); # Start counting

# Your code

$execution_time = microtime() - $execution_time;
$execution_time = sprintf('It took %.5f sec', $execution_time);

 

Cleaning Variables

Cleaning Variables

Variables that are submitted via web forms always need to be cleaned/sanitized before use in any way, to prevent against all kinds of different malicious intent.

Technique #1

function clean($value) {

       // If magic quotes not turned on add slashes.
       if(!get_magic_quotes_gpc())

       // Adds the slashes.
       { $value = addslashes($value); }

       // Strip any tags from the value.
       $value = strip_tags($value);

       // Return the value out of the function.
       return $value;

}
$sample = "<a href='#'>test</a>";
$sample = clean($sample);
echo $sample;

 

Convert BR to Newline

Convert BR to Newline

Technique #1

 

function br2newline( $input ) {
     $out = str_replace( "<br>", "\n", $input );
     $out = str_replace( "<br/>", "\n", $out );
     $out = str_replace( "<br />", "\n", $out );
     $out = str_replace( "<BR>", "\n", $out );
     $out = str_replace( "<BR/>", "\n", $out );
     $out = str_replace( "<BR />", "\n", $out );
     return $out;
}
Converts a break tag to a newline - no matter what kind of HTML is being processed.

Technique #2

function br2nl( $input ) {
 return preg_replace('/<br(\s+)?\/?>/i', "\n", $input);
}

 


Check if Website is Available

Check if Website is Available

Performs a cURL-Request to check, if a website exists / is online

Technique #1

<?php

       if (isDomainAvailible('http://codingtrickz.blogspot.in/'))
       {
               echo "Up and running!";
       }
       else
       {
               echo "Woops, nothing found there.";
       }

       //returns true, if domain is availible, false if not
       function isDomainAvailible($domain)
       {
               //check, if a valid url is provided
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }

               //initialize curl
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

               //get answer
               $response = curl_exec($curlInit);

               curl_close($curlInit);

               if ($response) return true;

               return false;
       }
?>

Technique #2

<?php
function Visit($url){
       $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
       curl_setopt ($ch, CURLOPT_URL,$url );
       curl_setopt($ch, CURLOPT_USERAGENT, $agent);
       curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt ($ch,CURLOPT_VERBOSE,false);
       curl_setopt($ch, CURLOPT_TIMEOUT, 5);
       curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt($ch,CURLOPT_SSLVERSION,3);
       curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
       $page=curl_exec($ch);
       //echo curl_error($ch);
       $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
       curl_close($ch);
       if($httpcode>=200 && $httpcode<300) return true;
       else return false;
}
if (Visit("http://www.google.com"))
       echo "Website OK"."n";
else
       echo "Website DOWN";
?>

Technique #3

<?php
       ini_set("default_socket_timeout","05");
       set_time_limit(5);
       $f=fopen("http://codingtrickz.blogspot.in/","r");
       $r=fread($f,1000);
       fclose($f);
       if(strlen($r)>1) {
       echo("<span class='online'>Online</span>");
       }
       else {
       echo("<span class='offline'>Offline</span>");
       }
?>

 

 

 


 

Change Date from dd/mm/yyyy to yyyy-dd-mm PHP

Conversion

$date_array = explode("/",$date); // split the array
$var_day = $date_array[0]; //day seqment
$var_month = $date_array[1]; //month segment
$var_year = $date_array[2]; //year segment
$new_date_format = "$var_year-$var_day-$var_month"; // join them together
Possibly a more MySQL friendly format in some circumstances.

Change period-separated to slash-separated or vice versa (and reverse order)

Convert date from YYYY/MM/DD to DD.MM.YYYY (and from DD.MM.YYYY to YYYY/MM/DD)

/**
 * @param string $date (d.m.y, y-m-d, y/m/d)
 * @return string|bol
 */

function convertDate($date) {
       // EN-Date to GE-Date
       if (strstr($date, "-") || strstr($date, "/"))   {
               $date = preg_split("/[\/]|[-]+/", $date);
               $date = $date[2].".".$date[1].".".$date[0];
               return $date;
       }
       // GE-Date to EN-Date
       else if (strstr($date, ".")) {
               $date = preg_split("[.]", $date);
               $date = $date[2]."-".$date[1]."-".$date[0];
               return $date;
       }
       return false;
}

 

Backup Database

Backup Database

Class to back up entire databases and email them out, or individual tables.
<?php
   class Backup
       {
               /**
                * @var stores the options
                */
               var $config;

               /**
                * @var stores the final sql dump
                */
               var $dump;

               /**
                * @var stores the table structure + inserts for every table
                */
               var $struktur = array();

               /**
                * @var zip file name
                */
               var $datei;

               /**
                * this function is the constructor and phrase the options
                * and connect to the database
                * @return
                */
               public function Backup($options)
               {
                       // write options
                       foreach($options AS $name => $value)
                       {
                               $this->config[$name] = $value;
                       }

                       // check mysql connection
                       mysql_connect($this->config['mysql'][0], $this->config['mysql'][1], $this->config['mysql'][2]) or die(mysql_error());
                       mysql_select_db($this->config['mysql'][3]) or die(mysql_error());
               }

               /**
                * this function start the backup progress its the core function
                * @return
                */
               public function backupDB()
               {
                       // start backup
                       if(isset($_POST['backup']))
                       {
                               // check if tables are selected
                               if(empty($_POST['table']))
                               {
                                       die("Please select a table.");
                               }

                               /** start backup **/
                               $tables = array();
                               $insert = array();
                               $sql_statement = '';

                               // lock tables
                               foreach($_POST['table'] AS $table)
                               {
                                        mysql_query("LOCK TABLE $table WRITE");

                                       // Read table structure
                                       $res = mysql_query('SHOW CREATE TABLE '.$table.'');
                                       $createtable = mysql_result($res, 0, 1);
                                       $str = "\n\n".$createtable."\n\n";

                                       array_push($tables, $str);

                                       // Read table "inserts"
                           $sql = 'SELECT * FROM '.$table;
                           $query = mysql_query($sql) or die(mysql_error());
                           $feld_anzahl = mysql_num_fields($query);

                                       $sql_statement = '--
-- Data Table `$table`
--

                                               ';

                                       // start reading progress
                           while($ds = mysql_fetch_object($query)){
                               $sql_statement .= 'INSERT INTO `'.$table.'` (';

                               for ($i = 0;$i <$feld_anzahl;$i++){
                                   if ($i ==$feld_anzahl-1){
                                       $sql_statement .= mysql_field_name($query,$i);
                                   } else {
                                       $sql_statement .= mysql_field_name($query,$i).', ';
                                   }
                               }

                               $sql_statement .= ') VALUES (';

                               for ($i = 0;$i <$feld_anzahl;$i++){
                                   $name = mysql_field_name($query,$i);
                                   if (empty($ds->$name)){
                                       $ds->$name = 'NULL';
                                   }
                                   if ($i ==$feld_anzahl-1){
                                       $sql_statement .= '"'.$ds->$name.'"';
                                   } else {
                                       $sql_statement .= '"'.$ds->$name.'", ';
                                   }
                               }
                               $sql_statement .= ");\n";
                           }

                                       // insert "Inserts" into an array if not exists
                                       if(!in_array($sql_statement, $insert))
                                       {
                                               array_push($insert, $sql_statement);
                                               unset($sql_statement);
                                       }

                                       unset($sql_statement);

                               }

                               // put table structure and inserts together in one var
                               $this->struktur = array_combine($tables, $insert);

                               // create full dump
                               $this->createDUMP($this->struktur);

                               // create zip file
                               $this->createZIP();

                               /** end backup **/

                               // send an email with the sql dump
                               if(isset($this->config['email']) && !empty($this->config['email']))
                               {
                                       $this->sendEmail();
                               }

                               // output
                               echo '<h3 style="color:green;">Backup war erfolgreich</h3><a href="'.$this->datei.'">Download Backup</a>
                               <br />
                               <br />';
                       }
               }

               /**
                * this function generate an email with attachment
                * @return
                */
               protected function sendEmail()
               {
                               // start sending emails
                               foreach($this->config['email'] AS $email)
                               {
                                       $to = $email;

                                       $from = $this->config['email'][0];

                                       $message_body = "This email contains the database backup as a zip file.";

                                       $msep = strtoupper (md5 (uniqid (time ())));

                                       // set email header (only text)
                                       $header =
                                                 "From: $from\r\n" .
                                                 "MIME-Version: 1.0\r\n" .
                                                 "Content-Type: multipart/mixed; boundary="$msep"\r\n\r\n" .
                                                 "--$msep\r\n" .
                                                 "Content-Type: text/plain\r\n" .
                                                 "Content-Transfer-Encoding: 8bit\r\n\r\n" .
                                                 $message_body . "\r\n";

                                       // file name
                                       $dateiname = $this->datei;

                                       // get filesize of zip file
                                       $dateigroesse = filesize ($dateiname);

                                       // open file to read
                                       $f = fopen ($dateiname, "r");
                                       // save content
                                       $attached_file = fread ($f, $dateigroesse);
                                       // close file
                                       fclose ($f);

                                       // create attachment
                                       $attachment = chunk_split (base64_encode ($attached_file));

                                       // set attachment header
                                       $header .=
                                                  "--" . $msep . "\r\n" .
                                                  "Content-Type: application/zip; name='Backup'\r\n" .
                                                  "Content-Transfer-Encoding: base64\r\n" .
                                                  "Content-Disposition: attachment; filename='Backup.zip'\r\n" .
                                                  "Content-Description: Mysql Datenbank Backup im Anhang\r\n\r\n" .
                                                  $attachment . "\r\n";

                                       // mark end of attachment
                                       $header .= "--$msep--";

                                       // eMail Subject
                                       $subject = "Database Backup";

                                       // send email to emails^^
                                       if(mail($to, $subject, '', $header) == FALSE)
                                       {
                                               die("The email could not be sent. Please check the email address.");
                                       }

                                       echo "<p><small>Email was successfully sent.</small></p>";
                               }
               }

               /**
                * this function create the zip file with the database dump and save it on the ftp server
                * @return
                */
               protected function createZIP()
               {

                       // Set permissions to 777
                       chmod($this->config['folder'], 0777);

                       // create zip file
                       $zip = new ZipArchive();
                       // Create file name
                       $this->datei = $this->config['folder'].$this->config['mysql'][3]."_".date("j_F_Y_g:i_a").".zip";

                       // Checking if file could be created
                       if ($zip->open($this->datei, ZIPARCHIVE::CREATE)!==TRUE) {
                               exit("cannot open <".$this->datei.">\n");
                       }

                       // add mysql dump to zip file
                       $zip->addFromString("dump.sql", $this->dump);
                       // close file
                       $zip->close();

                       // Check whether file has been created
                       if(!file_exists($this->datei))
                       {
                               die("The ZIP file could not be created.");
                       }

                       echo "<p><small>The zip was created.</small></p>";
               }

               /**
                * this function create the full sql dump
                * @param object $dump
                * @return
                */
               protected function createDUMP($dump)
               {
                       $date = date("F j, Y, g:i a");

                       $header = <<<HEADER
-- SQL Dump
--
-- Host: {$_SERVER['HTTP_HOST']}
-- Erstellungszeit: {$date}

--
-- Datenbank: `{$this->config['mysql'][3]}`
--

-- --------------------------------------------------------

HEADER;
                       foreach($dump AS $name => $value)
                       {
                               $sql .= $name.$value;
                       }
                       $this->dump = $header.$sql;
               }

               /**
                * this function displays the output form to select tables
                * @return
                */
               public function outputForm()
               {
                       // select all tables from database
                       $result = mysql_list_tables($this->config['mysql'][3]);

                       $buffer = '
                       <fieldset>
                               <legend>Select some tables</legend>
                               <form method="post" action="">
                       <select name="table[]" multiple="multiple" size="30">';
                       while($row = mysql_fetch_row($result))
                       {
                               $buffer .= '<option value="'.$row[0].'">'.$row[0].'</option>';
                       }
                       $buffer .= '</select>
                       <br /><br />
                       <input type="submit" name="backup" value="Backup Tables" />
                       </form>
                       </fieldset>';

                       echo $buffer;
               }
       }
?>

Usage:

<?php

       //You can add as many email addresses as you like
       $options = array('email' => array('email1', 'email2'),
                                  'folder' => './backup/',
                                  'mysql' => array('localhost', 'root', '****', 'database'));

       $b = new Backup($options);

       // if submit form start backup
       if(isset($_POST['backup']))
       {
               // start backup
               $b->backupDB();
       }

       // display tables
       $b->outputForm();

?>