Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 497 total  RSS 

Simple PHP Math Image Captcha


// Simple PHP Math Image Captcha

<?

// captcha width
$captcha_w = 150;
// captcha height
$captcha_h = 50;
// minimum font size; each operation element changes size
$min_font_size = 12;
// maximum font size
$max_font_size = 18;
// rotation angle
$angle = 20;
// background grid size
$bg_size = 13;
// path to font - needed to display the operation elements
$font_path = 'fonts/courbd.ttf';
// array of possible operators
$operators=array('+','-','*');
// first number random value; keep it lower than $second_num
$first_num = rand(1,5);
// second number random value
$second_num = rand(6,11);

?>



Credits: 4Dlink Weblists and web4link.com dir

ZIP File PHP code script

// ZIP File PHP source code script credits devco.net

//download this function first - http://uk2.php.net/manual/en/ref.zip.php

<?
require ("incl/zipfile.inc.php");
$zipfile = new zipfile();
$filedata = implode("", file("incl/zipfile.inc.php"));
$zipfile->add_dir("incl/");
$zipfile->add_file($filedata, "incl/zipfile.inc.php");
header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=zipfile.zip");
echo $zipfile->file();
?>



Credits: 4DLink Web Lists and Web 4 link

Extracting Image With PHP

//Extracting Image With PHP

$contenttograbimagefrom = $youroriginalhtmlwithimage;
$firstImage = "";
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $contenttograbimagefrom, $ContentImages);
$firstImage = $ContentImages[1] [0]; // To grab the first image
echo $firstImage;



credits: 4DLink WebLists and web4link.com

Select Randomly Row Fast - PHP Mysql

PHP MySQL Select Row Randomly Fast

<?php

  //CODE FROM WWW.GREGGDEV.COM

  function random_row($table, $column) {

      $max_sql = "SELECT max(" . $column . ") 

                  AS max_id

                  FROM " . $table;

      $max_row = mysql_fetch_array(mysql_query($max_sql));

      $random_number = mt_rand(1, $max_row['max_id']);

      $random_sql = "SELECT * FROM " . $table . "

                     WHERE " . $column . " >= " . $random_number . " 

                     ORDER BY " . $column . " ASC

                     LIMIT 1";

      $random_row = mysql_fetch_row(mysql_query($random_sql));

      if (!is_array($random_row)) {

          $random_sql = "SELECT * FROM " . $table . "

                         WHERE " . $column . " < " . $random_number . " 

                         ORDER BY " . $column . " DESC

                         LIMIT 1";

          $random_row = mysql_fetch_row(mysql_query($random_sql));

      }

      return $random_row;

  }

  

  //USAGE

  echo '<pre>';

  print_r(random_row('YOUR_TABLE', 'YOUR_COLUMN'));

  echo '</pre>';

?>


Credits: 4dlink web lists and web4link.com

How To Make Files Downloadable with PHP

In some situations when you’re creating a web page with links to a file like pdf – xml – jpeg , or other external program file , you may want user’s browser prompt to download the file instead of opening it in the browser window or in an external program . There are a few different methods you can do this , my favorite is PHP-based . Start by creating a new file on your server or on your development computer called download.php and paste the below code into the file .
Complete article : http://tournasdimitrios1.wordpress.com/2012/01/10/how-to-make-files-downloadable-with-php/

// download.php
 if (isset($_GET['file'])) {
//$file = $_GET['file'];
$file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_ENCODED);
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-Description: File Transfer');
header('Content-type: application/pdf');
header("Content-Type: application/force-download");// some browsers need this
header("Content-Disposition: attachment; filename=\"$file\"");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file2));
ob_clean();
flush();
readfile($file);
    exit;
}else {
header("HTTP/1.0 404 Not Found");
echo "<h3>Error 404: File Not Found: <br /><em>$file</em></h3>";
header('Refresh: 5; url=http://localhost/zy3.php');
print '<i style="color:red">You will be redirected in 5 seconds';
exit ;
}
} else {
header('Refresh: 5; url=http://localhost/zy3.php');
print '<h1 style="text-align:center">You you shouldn\'t be here ......</pre>
<p style="color: red;"><strong>redirection in 5 seconds</strong></p>

<pre>';
exit;
}

//index.html
<a href="relative_path_to_this_file/download.php?file=example.pdf">Click here to download PDF</a>


How to use extract() Function in PHP

Syntax: extract(array,extract_rules,prefix)


Sample code:

<?php
$a = 'Original';
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "\$a = $a; \$b = $b; \$c = $c";
?>



OUTPUT:

$a = Cat; $b = Dog; $c = Horse


Credit: 4DLink Dir and W3Schools.com | Web4link

Saving objects in redis and php

// A fairly generic method to store arrays and also to add them to a pool to reverse lookup their ids based on values that they contain. This method extends my own redis client but will work for the better clients out there such as predis.

class storage extends redis {

  public function save($key, array $object, $timestamp=true){
    $timestamp && $object['timestamp'] = date('Ymdhis');
    $id = $this->incr('id:'.$key);
    
    foreach ($object as $k => $v) {
      $this->sadd(sprintf("%s:%s:%s", $key, $k, $v), $id);
    }

    $key = sprintf("%s:%s", $key, $id);
    $this->hmset($key, $object);
  }
}

PHP Class : Sending Email with Attachment Using mail()

// description of your code here

/*
The class
*/
<?php

class AttachmentEmail {
	private $from = 'yours@email.com';
	private $from_name = 'Your Name';
	private $reply_to = 'yours@email.com';
	private $to = '';
	private $subject = '';
	private $message = '';
	private $attachment = '';
	private $attachment_filename = '';

	public function __construct($to, $subject, $message, $attachment = '', $attachment_filename = '') {
		$this -> to = $to;
		$this -> subject = $subject;
		$this -> message = $message;
		$this -> attachment = $attachment;
		$this -> attachment_filename = $attachment_filename;
	}

	public function mail() {
		if (!empty($this -> attachment)) {
			$filename = empty($this -> attachment_filename) ? basename($this -> attachment) : $this -> attachment_filename ;
			$path = dirname($this -> attachment);
			$mailto = $this -> to;
			$from_mail = $this -> from;
			$from_name = $this -> from_name;
			$replyto = $this -> reply_to;
			$subject = $this -> subject;
			$message = $this -> message;

			$file = $path.'/'.$filename;
			$file_size = filesize($file);
			$handle = fopen($file, "r");
			$content = fread($handle, $file_size);
			fclose($handle);
			$content = chunk_split(base64_encode($content));
			$uid = md5(uniqid(time()));
			$name = basename($file);
			$header = "From: ".$from_name." <".$from_mail.">\r\n";
			$header .= "Reply-To: ".$replyto."\r\n";
			$header .= "MIME-Version: 1.0\r\n";
			$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
			$header .= "This is a multi-part message in MIME format.\r\n";
			$header .= "--".$uid."\r\n";
			$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
			$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
			$header .= $message."\r\n\r\n";
			$header .= "--".$uid."\r\n";
			$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use diff. tyoes here
			$header .= "Content-Transfer-Encoding: base64\r\n";
			$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
			$header .= $content."\r\n\r\n";
			$header .= "--".$uid."--";

			if (mail($mailto, $subject, "", $header)) {
				return true;
			} else {
				return false;
			}
		} else {
			$header = "From: ".($this -> from_name)." <".($this -> from).">\r\n";
			$header .= "Reply-To: ".($this -> reply_to)."\r\n";

			if (mail($this -> to, $this -> subject, $this -> message, $header)) {
				return true;
			} else {
				return false;
			}

		}
	}
}

/*
Practical example 
*/
$sendmail = new AttachmentEmail('johnDoe@gmail.com', 'Testing mail() class', 'Your message here ', '/home/images/img.jpg');
$sendmail -> mail();

Get birthday from timestamp field

//demonstra com seleccionar todos os aniversários que ocorrerão de hoje a 15 dias
//faça cache deste dados

SELECT SQL_CACHE /*??? prefira memcache, APC, etc..*/
  name,
  birthday,
  YEAR(birthday),
  YEAR(NOW()),
  (YEAR(NOW()) - YEAR(birthday)),
  DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR),
  DATE_ADD(NOW(), INTERVAL 15 DAY )

FROM customers

WHERE

DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) 
  BETWEEN 
    DATE( NOW() )
  AND 
    DATE_ADD(NOW(), INTERVAL 15 DAY )

A simple PHP Mysql Class

Simple to use :
http://tournasdimitrios1.wordpress.com/2011/11/05/a-simple-php-mysql-class/#more-6911
Note : This Class implements the old Mysql extension , use it only for learning PHP's OOP-concepts . A more robust (Mysqli )extension is available for production database transactions .
According to php.net
" If you are using MySQL versions 4.1.3 or later it is strongly recommended that you use this extension (Mysqli). "


<?php 

  
  //Simply include this file on your page 
  require_once("DbConnect.class.php"); 
   
  //Set up all yor paramaters for connection 
  $db = new DbConnect("localhost","user","password","database",$error_reporting=false,$persistent=false); 
   
   //Open the connection to your database 
       $db->open() or die($db->error()); 

      //Query the database now the connection has been made 
       $db->query("SELECT * FROM....") or die($db->error()); 
        
       //You have several options on ways of fetching the data 
       //as an example I shall use 
       while($row=$db->fetcharray()) { 
        
         //do some stuff 
          
       } 
        
       //close your connection 
       $db->close(); 

       
  #################################################################
Class DbConnect { 
             
                  var $host = ''; 
                  var $user = ''; 
                  var $password = ''; 
                  var $database = ''; 
                  var $persistent = false; 
                   
                  var $conn = NULL; 
                   
                  var $result= false; 
                  var $error_reporting = false; 
                   
      /*constructor function this will run when we call the class */ 
       
                  function DbConnect ($host, $user, $password, $database, $error_reporting=true, $persistent=false) { 
                       
                       $this->host = $host; 
                       $this->user = $user; 
                       $this->password = $password; 
                       $this->database = $database; 
                        $this->persistent = $persistent; 
                        $this->error_reporting = $error_reporting; 
                  } 
    
              function open() { 
                   
                  if ($this->persistent) { 
                             
                        $func = 'mysql_pconnect'; 
                   
                  } else { 
                       
                     $func = 'mysql_connect'; 
                      
                  }             
                   
                  /* Connect to the MySQl Server */ 
                   
                  $this->conn = $func($this->host, $this->user, $this->password); 
                   
                   if (!$this->conn) { 

                       return false; 
                   
                   } 
                   
                   /* Select the requested DB */ 
                   
                   if (@!mysql_select_db($this->database, $this->conn)) { 
                        
                       return false; 
                   } 
                     return true; 
              } 
    
              /*close the connection */ 
               
               function close() { 
                       
                   return (@mysql_close($this->conn)); 
               } 
    
                /* report error if error_reporting set to true */ 
                 
      function error() { 
             
          if ($this->error_reporting) { 
                 
              return (mysql_error()) ; 
          } 
           
      } 
      
       function query($sql) { 
                
             $this->result = @mysql_query($sql, $this->conn); 
         
        return($this->result != false); 
        
       } 
    function affectedrows() { 

        return(@mysql_affected_rows($this->conn)); 
    } 
     
    function numrows() { 
         
        return(@mysql_num_rows($this->result)); 
         
    } 
    function fetchobject() { 
         
         return(@mysql_fetch_object($this->result, MYSQL_ASSOC)); 
         
    } 
     function fetcharray() { 
          
          return(mysql_fetch_array($this->result)); 
          
     } 
      
     function fetchassoc() { 
          
         return(@mysql_fetch_assoc($this->result)); 
     } 
      
     function freeresult() { 
          
          return(@mysql_free_result($this->result)); 
          
     } 
         
   } 
?>
« Newer Snippets
Older Snippets »
Showing 1-10 of 497 total  RSS