Archive for 03/05/14

Tutorial Variable Variables

by in , 0

<?php

  $var1 = 'nameOfVariable';

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

  echo $$var1; 

?>

Reference URL

Tutorial URL Validation

by in , 0

$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;

Tutorial Update Values of Entire Table

by in , 0

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.

Tutorial Unzip Files

by in , 0

<?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);
}
?>

Reference URL

Tutorial Truncate String by Words

by in , 0

Technique #1

<?php
function trunc($phrase, $max_words) {
   $phrase_array = explode(' ',$phrase);
   if(count($phrase_array) > $max_words && $max_words > 0)
      $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';
   return $phrase;
}
?>

Technique #2

function limit_words($words, $limit, $append = ' &hellip;') {
       // Add 1 to the specified limit becuase arrays start at 0
       $limit = $limit+1;
       // Store each individual word as an array element
       // Up to the limit
       $words = explode(' ', $words, $limit);
       // Shorten the array by 1 because that final element will be the sum of all the words after the limit
       array_pop($words);
       // Implode the array for output, and append an ellipse
       $words = implode(' ', $words) . $append;
       // Return the result
       return $words;
}

Tutorial Truncate Long String Exactly In Middle

by in , 0

This will truncate a longer string to a smaller string of specified length (e.g. the "25" value in the code below) while replacing the middle portion with a separator exactly in the middle. Useful when you need to truncate a string but still show the beginning (e.g. for sorting and because it is most recognizable) and also show the end (perhaps to show a file name).

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"

?>

Tutorial Time Ago Function

by in , 0

This can be used for comments and other from of communication to tell the time ago instead of the exact time which might not be correct to some one in another time zone.

The function only uses unix time stamp like the result of time();

Technique #1

<?php
function ago($time)
{
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");

   $now = time();

       $difference     = $now - $time;
       $tense         = "ago";

   for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
       $difference /= $lengths[$j];
   }

   $difference = round($difference);

   if($difference != 1) {
       $periods[$j].= "s";
   }

   return "$difference $periods[$j] 'ago' ";
}
?>

Technique #2

function _ago($tm,$rcs = 0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
   return $x;
}

Needs a time() value, and it will tell you how many seconds/minutes/hours/days/years/decades ago.

Tutorial Simple Zipcode Range Tester

by in , 0

This regex below tests the provided zip code if it starts with the numbers 096 and that there are exactly 2 numbers after it. If it does, it echos Yes, if not, it echos No. In this test case, it would echo Yes.

<?php
$zipcode='09607';
echo 'Zipcode in range?<br />';
if(preg_match('/^096[0-9]{2}$/', $zipcode))
       echo "Yes";
else
       echo "No";
?>

Tutorial Server Side Image Resizer

by in , 0

The code uses PHP to resize an image (currently only jpeg). Using this method, the resized image is of much better quality than a browser-side resizing. The file size of the new downsized image is also smaller (quicker to download).

The code comes in two parts:

imageResizer() is used to process the image loadimage() inserts the image url in a simpler format
<?php

   function imageResizer($url, $width, $height) {

		header('Content-type: image/jpeg');

		list($width_orig, $height_orig) = getimagesize($url);

		$ratio_orig = $width_orig/$height_orig;

		if ($width/$height > $ratio_orig) {
		  $width = $height*$ratio_orig;
		} else {
		  $height = $width/$ratio_orig;
		}

		// This resamples the image
		$image_p = imagecreatetruecolor($width, $height);
		$image = imagecreatefromjpeg($url);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

		// Output the image
		imagejpeg($image_p, null, 100);
		
	}

	//works with both POST and GET
	$method = $_SERVER['REQUEST_METHOD'];
	
	if ($method == 'GET') {

		imageResize($_GET['url'], $_GET['w'], $_GET['h']);
		
	 } elseif ($method == 'POST') {

	    imageResize($_POST['url'], $_POST['w'], $_POST['h']);
	 }

	// makes the process simpler
	function loadImage($url, $width, $height){
         echo 'image.php?url=', urlencode($url) ,
         '&w=',$width,
         '&h=',$height;
	}

?>

Usage

Above code would be in a file called image.php.

Images would be displayed like this:

<img src="<?php loadImage('image.jpg', 50, 50) ?>"

Tutorial Separate First and Last Name

by in , 0

$name = "John S Smith";

list($fname, $lname) = split(' ', $name,2);

echo "First Name: $fname, Last Name: $lname";

Works with or without middle name.

Tutorial Send Email

by in , 0

1) HTML Form with Inputs

<form action="" method="post">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" />

  <label for="Email">Email:</label>
  <input type="text" name="email" id="email" />

  <label for="Message">Message:</label><br />
  <textarea name="message" rows="20" cols="20" id="message"></textarea>

  <input type="submit" name="submit" value="Submit" />
</form>

2) Process with PHP

This could be in a seperate file (e.g. sendemail.php) in which you'd set the action URL of the form to go there. Or, have the form submit to itself (leave action URL blank) and test for one of the values of the form being POSTed and process there.

<?php
       // from the form
       $name = trim(strip_tags($_POST['name']));
       $email = trim(strip_tags($_POST['email']));
       $message = htmlentities($_POST['message']);

       // set here
       $subject = "Contact form submitted!";
       $to = 'your@email.com';

       $body = <<<HTML
$message
HTML;

       $headers = "From: $email\r\n";
       $headers .= "Content-type: text/html\r\n";

       // send the email
       mail($to, $subject, $body, $headers);

       // redirect afterwords, if needed
       header('Location: thanks.html');
?>

3) Test it

And make sure to keep up with security news around the web.

Tutorial Send a Text Message

by in , 0

You'll need a TextMagic account and to download their PHP helper which they provide after signing up.

// Include the TextMagic PHP lib
require('textmagic-sms-api-php/TextMagicAPI.php');

// Set the username and password information
$username = 'myusername';
$password = 'mypassword';

// Create a new instance of TM
$router = new TextMagicAPI(array(
	'username' => $username,
	'password' => $password
));

// Send a text message to '999-123-4567'
$result = $router->send('Wake up!', array(9991234567), true);

// result:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

Reference URL

Tutorial Sanitize Database Inputs

by in , 0

1) Function for stripping out malicious bits

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

2) Sanitization function

Uses the function above, as well as adds slashes as to not screw up database functions.

<?php
function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}
?>

Usage

<?php
  $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);
?>

Reference URL

Tutorial Return Only One Variable from MySQL Query

by in , 0

Function

function mysql_get_var($query,$y=0){
       $res = mysql_query($query);
       $row = mysql_fetch_array($res);
       mysql_free_result($res);
       $rec = $row[$y];
       return $rec;
}

Usage

$name = mysql_get_var("SELECT name from people where email = 'roger@freekrai.net'");

Will return the name field, so what gets returned will be "Roger" (if that was my name in the database).

Reference URL

Tutorial Read/Write Files

by in , 0

Append to a file

function fileWrite($file, $message) {
  fwrite(fopen($file, 'a'), $message . "\n");
}

Read and display entire file

function fileRead($file){
   $lines = file($file);
   foreach ($lines as $line_num => $line) {
      echo  $line,  '</br>';
   }
}

Tutorial Randomize File Name

by in , 0

function randomizeFileName( $real_file_name ) {
               $name_parts = @explode( ".", $real_file_name );
               $ext = "";
               if ( count( $name_parts ) > 0 ) {
                       $ext = $name_parts[count( $name_parts ) - 1];
               }
               return substr(md5(uniqid(rand(),1)), -16) . "." . $ext;
}

Tutorial Randomize Background Image

by in , 0

1. Above the DOCTYPE

Set up and array of filenames, which correspond to the file names of the images you are trying to randomize.

<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames

  $i = rand(0, count($bg)-1); // generate random number size of the array
  $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

1. CSS in the <head>

Normally you'd want to keep CSS out of the HTML, but we'll just use it here to echo out the random file name we selected above.

<style type="text/css">
<!--
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
-->
</style>

Tutorial Random String from Pre-Determined Characters

by in , 0

<?php
$string = "abcdwxyz456789";
for($i=0;$i<25;$i++){
   $pos = rand(0,13);
   $str .= $string{$pos};
}
echo $str;
?>

Tutorial Random Slogan Displayer

by in , 0

Create a text file called slogans.txt with permissions that it can be read by the server. Put each slogan on a different line, e.g.:

Building websites since before there was a web.
The internet is for lovers.

<?php
       $f_contents = file ("slogans.txt");
       $line = $f_contents[array_rand ($f_contents)];
       print $line;
?>

Tutorial Random Hex Color

by in , 0

Technique #1

<?php 
    
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    
?>

Then echo out the $color value anywhere you need it. For example:

<body style="background: <?php echo $color; ?>;">

Technique #2

<?php printf( "#%06X\n", mt_rand( 0, 0xFFFFFF )); ?>

There is also a JavaScript version.

Reference URL

Tutorial Quick Alphabetic Navigation

by in , 0

Could be useful for an address book style navigation.

<?php
foreach (range('a', 'z') as $char) {
 print '<a href="#' . $char . '">' . $char . '</a> | ';
}
?>

Tutorial POST Validation Loop

by in , 0

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;
}

Tutorial PHP Zebra Striping a Table

by in , 0

Table row in a loop:

<!-- Before loop -->
<?php $c = 0; ?>

<!-- Start loop -->
<tr class="<?=($c++%2==1) ? 'odd' : 'even' ?>">
<!-- End loop -->

CSS:

.even { background-color:#FFF; }
.odd { background-color:#666; }

Tutorial PHP Redirect

by in , 0

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

Tutorial PHP Include

by in , 0

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);
?>

Reference URL

Tutorial PHP IE Detection

by in , 0

if ( eregi("MSIE", getenv( "HTTP_USER_AGENT" ) ) || eregi("Internet Explorer", getenv("HTTP_USER_AGENT" ) ) ) {
  // do something
}

Tutorial PHP Date Parameters

by in , 0

format
character Description Example returned values
Day --- ---
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
N ISO-8601 numeric representation of the day of the week (added in
PHP 5.1.0)
1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or
th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week --- ---
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Month --- ---
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year --- ---
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number. This has the same value as
Y, except that if the ISO week number
(W) belongs to the previous or next year, that year
is used instead. (added in PHP 5.1.0)
Examples: 1999 or 2003
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
u Microseconds (added in PHP 5.2.2) Example: 654321
Timezone --- ---
e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) in hours Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Example: +02:00
T Timezone abbreviation Examples: EST, MDT ...
Z Timezone offset in seconds. The offset for timezones west of UTC is always
negative, and for those east of UTC is always positive.
-43200 through 50400
Full Date/Time --- ---
c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
r » RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()

Tutorial PHP Array Contains

by in , 0

Check if value is in array and outputs Yes or No

<?php
$names = array( 'Bob', 'Jim', 'Mark' );
echo 'In Array? ';
if (in_array(‘foo’, $names))
   echo 'Yes';
else
   echo 'No';
?>

array_map Perform Function on Each Item of an Array

by in , 0

array_map() takes two arguments. The first argument is the function to perform on the second argument (which is an array). Returns a new array.

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('strip_tags', $original);

// $new is now array('Paragraph', 'Bold');

How to Parse JSON in php

by in , 0

<?php
   $json ='{"id":1,"name":"foo","interest":["wordpress","php"]} ';

   $obj=json_decode($json);

   echo $obj->interest[1]; //prints php
?>

Pagination Function PHP example

by in , 0

function pagination($item_count, $limit, $cur_page, $link)
{
       $page_count = ceil($item_count/$limit);
       $current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page+2 > $page_count ? $page_count : $cur_page+2));

       // First and Last pages
       $first_page = $cur_page > 3 ? '<a href="'.sprintf($link, '1').'">1</a>'.($cur_page < 5 ? ', ' : ' ... ') : null;
       $last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($link, $page_count).'">'.$page_count.'</a>' : null;

       // Previous and next page
       $previous_page = $cur_page > 1 ? '<a href="'.sprintf($link, ($cur_page-1)).'">Previous</a> | ' : null;
       $next_page = $cur_page < $page_count ? ' | <a href="'.sprintf($link, ($cur_page+1)).'">Next</a>' : null;

       // Display pages that are in range
       for ($x=$current_range[0];$x <= $current_range[1]; ++$x)
               $pages[] = '<a href="'.sprintf($link, $x).'">'.($x == $cur_page ? '<strong>'.$x.'</strong>' : $x).'</a>';

       if ($page_count > 1)
               return '<p class="pagination"><strong>Pages:</strong> '.$previous_page.$first_page.implode(', ', $pages).$last_page.$next_page.'</p>';
}

Usage:

pagination(
   total amount of item/rows/whatever,
   limit of items per page,
   current page number,
   url
);

Example:

pagination(45, 20, 1, 'http://example.com/userlist/%d.html');

Output HTML:

<p class="pagination">
   <strong>Pages:</strong>
   <a href="http://example.com/userlist/1.html"><strong>1</strong></a>,
   <a href="http://example.com/userlist/2.html">2</a>,
   <a href="http://example.com/userlist/3.html">3</a>
   | <a href="http://example.com/userlist/2.html">Next</a>
</p>

Tutorial Output Buffering

by in , 0

<?php
 
  // Start buffering
  ob_start();

  // Output stuff (probably not this simple, might be custom CMS functions...
  echo 'Print to the screen!!!';

  // Get value of buffering so far
  $getContent = ob_get_contents();

  // Stop buffering
  ob_end_clean();

  // Do stuff to $getContent as needed

  // Use it
  echo 'Now: ' . $getContent;

?>

Tutorial Options to Truncate Strings

by in , 0

Technique #1: Simple

function myTruncate($string, $limit, $break=".", $pad="...") {
        if(strlen($string) <= $limit) return $string; 
        if(false !== ($breakpoint = strpos($string, $break, $limit))) { 
            if($breakpoint < strlen($string) - 1) { 
                $string = substr($string, 0, $breakpoint) . $pad; } 
            } return $string; 
}

Technique #2: Simple

function ellipsis($text, $max=100, $append='&hellip;') {
       if (strlen($text) <= $max) return $text;
       $out = substr($text,0,$max);
       if (strpos($text,' ') === FALSE) return $out.$append;
       return preg_replace('/\w+$/','',$out).$append;
}

Usage:

<?php
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.";
echo ellipsis($text,100);
?>

Technique #3: More Options

Options to use PHP's php_tidy to fix up broken HTML, or to strip HTML entirely.

function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
               if ( strlen( $input ) >= $limit ) {
                       $breakpoint = strpos( $input, $break, $limit );
                       $input = substr( $input, 0, $breakpoint ) . $end_text;
               }
               if ( $tidy_html == 1 ) {
                       ob_start(  );
                       $tidy = new tidy;
                       $config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
                       $tidy->parseString( $input, $config, 'utf8' );
                       $tidy->cleanRepair(  );
                       $input = $tidy;
               }
               if ( $strip_html == 1 ) {
                       $input = strip_tags( $input );
               }
               return $input;
}

Technique #4: Without a function

<?php

$long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$max_length = 40; // we want to show only 40 characters.

if (strlen($long_text) > $max_length)
{
 $short_text = (substr($long_text,0,$max_length-1)); // make it $max_length chars long
 $short_text .= "..."; // add an ellipses ... at the end
 $short_text .= "<a href='http://example.com/page.html'>Read more</a>"; // add a link
 echo $short_text;
}
else
{
// string is already less than $max_length, so display the string as is
echo $long_text;
}

?>

Reference URL

Tutorial MySQL Restore Class

by in , 0

<?php

define('MSR_VERSION', '1.0.0');
define('__SEP__', "/*sep*/" );

define('MSR_STRING', 0);
define('MSR_FILE', 1);
set_time_limit( 600 );


class MySQL_Restore {

 var $server           = 'localhost';
 var $port             = 3306;
 var $username         = 'root';
 var $password         = '';
 var $database         = '';
 var $link_id          = -1;
 var $connected        = false;
 var $queries          = array();
 var $error            = '';

 var $debug            = false;
 var $log_folder       = "";
 var $log_file_name    = "";

   function MySQL_Restore() {
       $this->log_file_name = "restore_" . date( "Ymd_his" ) . ".log";
   }

   function Execute( $param, $mode = MSR_STRING, $is_compressed = false, $split_only = false ) {
       if ( $this->debug ) {
               $this->saveLog( "[start reading file]" );
       }
           if ( $mode == MSR_FILE ) {
               if (!($sql = $this->_ReadFromFile($param, $is_compressed))) {
                   $this->error = 'Can\'t read backup file.';
                   return false;
               }
           } else {
               $sql = ($is_compressed ? gzuncompress($param) : $param);
           }
       if ( $this->debug ) {
           $this->saveLog( "[file readed]" );
       }

           return $this->_Restore( $sql, $split_only );
   }


   function _Connect() {
           $value = false;
           if ( !$this->connected ) {
               $host = $this->server . ':' . $this->port;
               $this->link_id = mysql_pconnect( $host, $this->username, $this->password );
           }
           if ( $this->link_id ) {
               if ( empty( $this->database ) ) {
                   $value = true;
               } elseif ( $this->link_id !== -1 ) {
                   $value = mysql_select_db($this->database, $this->link_id);
               } else {
                   $value = mysql_select_db($this->database);
               }
           }
           if (!$value) {
               $this->error = mysql_error();
           }
           return $value;
   }

   function _Disconnect() {
       if ( $this->link_id ) {
               mysql_close( $this->link_id );
       }
   }

   function _Query( $sql ) {
       if ( $this->link_id !== -1 ) {
           $result = mysql_query( $sql, $this->link_id );
       } else {
           $result = mysql_query( $sql );
       }
       if ( !$result ) {
           $this->error = mysql_error();
       }
       return $result;
   }


// The logic from phpMyAdmin source
   function _Decompose( &$ret, $sql ) {
       $sql = rtrim( $sql, "\n\r" );
       $sql_len = strlen( $sql );
       $char = '';
       $string_start = '';
       $in_string = false;
       $nothing = true;
       $time0 = time();
       for ( $i = 0; $i < $sql_len; ++$i ) {
           $char = $sql[$i];
           if ( $in_string ) {
               for (;;) {
                   $i = strpos( $sql, $string_start, $i );
                   if ( !$i ) {
                       $ret[] = $sql;
                       return true;
                   } elseif ( $string_start == '`' || $sql[$i - 1] != '\\' ) {
                       $string_start = '';
                       $in_string = false;
                       break;
                   } else {
                       $j = 2;
                       $escaped_backslash = false;
                       while ( $i - $j > 0 && $sql[$i - $j] == '\\' ) {
                           $escaped_backslash = !$escaped_backslash;
                           $j++;
                       }
                       if ( $escaped_backslash ) {
                           $string_start = '';
                           $in_string = false;
                           break;
                       } else {
                           $i++;
                       }
                   }
               }
           } else if ( ($char == '-' && $sql_len > $i + 2 && $sql[$i + 1] == '-' && $sql[$i + 2] <= ' ') || $char == '#' || ($char == '/' && $sql_len > $i + 1 && $sql[$i + 1] == '*') ) {
               $comm_end = ($char == '/' ? '*/' : "\n");
               $i = strpos($sql, $comm_end, $i);
               if ( $i === false ) {
                   break;
               }
               if ($char == '/') {
                   $i++;
               }
           } else if ($char == ';') {
               $ret[] = array( 'query' => substr( $sql, 0, $i ), 'empty' => $nothing );
               $nothing = true;
               $sql = ltrim(substr($sql, min($i + 1, $sql_len)));
               $sql_len = strlen($sql);
               if ( $sql_len ) {
                   $i = -1;
               } else {
                   return true;
               }
           } else if (($char == '"') || ($char == '\'') || ($char == '`')) {
               $in_string = true;
               $nothing = false;
               $string_start = $char;
           } elseif ($nothing) {
               $nothing = false;
           }
           $time1 = time();
           if ($time1 >= $time0 + 30) {
               $time0 = $time1;
               @header('X-pmaPing: Pong');
           }
       }
       if (!empty($sql) && preg_match('@[^[:space:]]+@', $sql)) {
           $ret[] = array('query' => $sql, 'empty' => $nothing);
       }
       return true;
   }


   function _Restore($sql, $split_only) {
       if ( $this->debug ) {
           $this->saveLog( "[start restoring]" );
       }
       if ( $this->debug ) {
           $this->saveLog( "[connecting to DB...]" );
       }

       if (!$this->_Connect()) {
           return false;
       }
       if ( $this->debug ) {
           $this->saveLog( "[connected to DB]" );
       }
       if ( $this->debug ) {
           $this->saveLog( "[decomposing...]" );
       }
       $queries = array();
       $errors = '';

// check if is this our backup
       if ( strpos( $sql, __SEP__ ) !== false ) {
               if ( $this->debug ) {
                   $this->saveLog( "[founding our backup file]" );
               }
           $queries = explode( __SEP__, $sql );
           if ( count( $queries ) ) {
                   if ( $this->debug ) {
                       $this->saveLog( "[decomposed]" );
                   }
                   if (!$split_only) {
                       foreach ($queries as $query) {
                               $query = trim( $query );
                               if ( !empty( $query ) ) {
                                   if (!$this->_Query( $query ) ) {
                                       $errors .= $this->error . '<br />';
                                   }
                                       if ( $this->debug ) {
                                  $this->saveLog( $query );
                           }
                               }
                       }
                   }
           }
       } else {
           if ( $this->debug ) {
               $this->saveLog( "[common sql file founded]" );
           }
               if (!$this->_Decompose( $queries, $sql ) ) {
                   return false;
               }
               if ( $this->debug ) {
                   $this->saveLog( "[decomposed]" );
               }
               foreach ($queries as $query) {
                   if (!$split_only) {
                       if (!$this->_Query( trim( $query['query'] ) ) ) {
                           $errors .= $this->error . '<br /><br />';
                       }
                   }
                   if ( $this->debug ) {
                       $this->saveLog( $query['query'] );
                   }
               }
       }
       if ( $this->debug ) {
           $this->saveLog( "[finished restoring]" );
       }
       $this->_Disconnect();

       if ( !empty( $errors ) ) {
           $this->error = $errors;
           return false;
       }
       return true;
   }


   function _ReadFromFile($fname, $is_compressed) {
          if ($is_compressed) {
              $sql = gzfile($fname);
          } else {
              $sql = file($fname);
          }
          if ($sql === false) {
             return false;
          }
          return implode('', $sql);
       }

       function saveLog( $str ) {
       $f = @fopen( $this->log_folder . $this->log_file_name, "a" );
       @fwrite( $f, "[" . date( "H:i:s" ). "] " . $str . "\n" );
               @fclose( $f );
       }
}

?>

Tutorial MySQL Database Access Class

by in , 0

<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */


class dbAccess {

       var $db_connect_id;
       var $query_result;
       var $row = array();
       var $rowset = array();
       var $num_queries = 0;

       //
       // Constructor
       //
       function dbAccess($sqlserver, $sqluser, $sqlpassword, $database, $persistency = true) {

               $this->persistency = $persistency;
               $this->user = $sqluser;
               $this->password = $sqlpassword;
               $this->server = $sqlserver;
               $this->dbname = $database;

               if($this->persistency) {
                       $this->db_connect_id = @mysql_pconnect($this->server, $this->user, $this->password);
               } else {
                       $this->db_connect_id = @mysql_connect($this->server, $this->user, $this->password);
               }
               if($this->db_connect_id) {
                       if($database != "")     {
                               $this->dbname = $database;
                               $dbselect = @mysql_select_db($this->dbname);
                               if(!$dbselect) {
                                       @mysql_close($this->db_connect_id);
                                       $this->db_connect_id = $dbselect;
                               }
                       }
                       return $this->db_connect_id;
               } else {
                       return false;
               }
       }

       //
       // Other base methods
       //
       function destroy() {
               if($this->db_connect_id) {
                       if($this->query_result) {
                               @mysql_free_result($this->query_result);
                       }
                       $result = @mysql_close($this->db_connect_id);
                       return $result;
               } else {
                       return false;
               }
       }

       //
       // Base query method
       //
       function query($query = "", $transaction = FALSE) {
               // Remove any pre-existing queries
               unset($this->query_result);
               if($query != "") {
                       $this->num_queries++;
                       $this->query_result = @mysql_query($query, $this->db_connect_id);
               }
               if($this->query_result) {
                       unset($this->row[$this->query_result]);
                       unset($this->rowset[$this->query_result]);
                       return $this->query_result;
               } else {
                       return ( $transaction == END_TRANSACTION ) ? true : false;
               }
       }

       //
       // Other query methods
       //
       function numrows($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_num_rows($query_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function affectedrows() {
               if($this->db_connect_id) {
                       $result = @mysql_affected_rows($this->db_connect_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function numfields($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_num_fields($query_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function fieldname($offset, $query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_field_name($query_id, $offset);
                       return $result;
               } else {
                       return false;
               }
       }
       function fieldtype($offset, $query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_field_type($query_id, $offset);
                       return $result;
               } else {
                       return false;
               }
       }
       function fetchrow($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $this->row[$query_id] = @mysql_fetch_array($query_id);
                       return $this->row[$query_id];
               } else {
                       return false;
               }
       }
       function fetchrowset($query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                   $result = array();
                       unset($this->rowset[$query_id]);
                       unset($this->row[$query_id]);
                       while($this->rowset[$query_id] = @mysql_fetch_array($query_id)) {
                               $result[] = $this->rowset[$query_id];
                       }
                       return $result;
               } else {
                       return false;
               }
       }
       function fetchfield($field, $rownum = -1, $query_id = 0) {
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       if($rownum > -1) {
                               $result = @mysql_result($query_id, $rownum, $field);
                       } else {
                               if(empty($this->row[$query_id]) && empty($this->rowset[$query_id])) {
                                       if($this->fetchrow()) {
                                               $result = $this->row[$query_id][$field];
                                       }
                               } else {
                                       if($this->rowset[$query_id]) {
                                               $result = $this->rowset[$query_id][$field];
                                       } else if($this->row[$query_id]) {
                                               $result = $this->row[$query_id][$field];
                                       }
                               }
                       }
                       return $result;
               } else {
                       return false;
               }
       }
       function rowseek($rownum, $query_id = 0){
               if(!$query_id) {
                       $query_id = $this->query_result;
               }
               if($query_id) {
                       $result = @mysql_data_seek($query_id, $rownum);
                       return $result;
               } else {
                       return false;
               }
       }
       function nextid(){
               if($this->db_connect_id) {
                       $result = @mysql_insert_id($this->db_connect_id);
                       return $result;
               } else {
                       return false;
               }
       }
       function freeresult($query_id = 0){
               if(!$query_id) {
                       $query_id = $this->query_result;
               }

               if ( $query_id ) {
                       unset($this->row[$query_id]);
                       unset($this->rowset[$query_id]);

                       @mysql_free_result($query_id);

                       return true;
               } else {
                       return false;
               }
       }
       function error($query_id = 0) {
               $result["message"] = @mysql_error($this->db_connect_id);
               $result["code"] = @mysql_errno($this->db_connect_id);

               return $result;
       }
}
?>

Tutorial MySQL Backup Class

by in , 0

<?php

define('MSB_VERSION', '1.0.0');

define('MSB_NL', "\r\n");

define('MSB_STRING', 0);
define('MSB_DOWNLOAD', 1);
define('MSB_SAVE', 2);
define('__SEP__', "/*sep*/" );

set_time_limit( 600 );

class MySQL_Backup {
   var $server = 'localhost';
   var $port = 3306;
       var $username = 'root';
       var $password = '';
       var $database = '';
       var $link_id = -1;
       var $connected = false;
       var $tables = array();
       var $drop_tables = true;
       var $struct_only = false;
       var $comments = true;
       var $backup_dir = '';
       var $fname_format = 'd_m_y__H_i_s';
       var $error = '';

       var $complete_inserts  = false;
       var $inserts_block     = 200;

   function Execute($task = MSB_STRING, $fname = '', $compress = false) {
       if ( !( $sql = $this->_Retrieve() ) ) {
           return false;
       }
       if ( $task == MSB_SAVE ) {
           if (empty($fname)) {
               $fname = $this->backup_dir;
               $fname .= date($this->fname_format);
               $fname .= ($compress ? '.sql.gz' : '.sql');
           }
           return $this->_SaveToFile($fname, $sql, $compress);
       } elseif ($task == MSB_DOWNLOAD) {
           if ( empty( $fname ) ) {
               $fname = date($this->fname_format);
               $fname .= ($compress ? '.sql.gz' : '.sql');
           }
           return $this->_DownloadFile($fname, $sql, $compress);
       } else {
           return $sql;
       }
   }

   function _Connect() {
       $value = false;
       if (!$this->connected) {
           $host = $this->server . ':' . $this->port;
           $this->link_id = mysql_connect($host, $this->username, $this->password);
       }
       if ($this->link_id) {
           if (empty($this->database)) {
               $value = true;
           } elseif ($this->link_id !== -1) {
               $value = mysql_select_db($this->database, $this->link_id);
           } else {
               $value = mysql_select_db($this->database);
           }
       }
       if (!$value) {
           $this->error = mysql_error();
       }
       return $value;
   }


   function _Query($sql) {
       if ($this->link_id !== -1) {
           $result = mysql_query($sql, $this->link_id);
       } else {
           $result = mysql_query($sql);
       }
       if (!$result) {
           $this->error = mysql_error();
       }
       return $result;
   }


   function _GetTables() {
       $value = array();
       if ( !( $result = $this->_Query('SHOW TABLES') ) ) {
           return false;
       }
       while ( $row = mysql_fetch_row( $result ) ) {
           if ( empty( $this->tables) || in_array( $row[0], $this->tables ) ) {
               $value[] = $row[0];
           }
       }
       if (!sizeof($value)) {
           $this->error = 'No tables found in database.';
           return false;
       }
       return $value;
   }


   function _DumpTable( $table ) {
       $value = '';
       $this->_Query( 'LOCK TABLES ' . $table . ' WRITE' );
       if ( $this->comments ) {
           $value .= '#' . MSB_NL;
                   $value .= '# Table structure for table `' . $table . '`' . MSB_NL;
                   $value .= '#' . MSB_NL . MSB_NL;
       }
       if ( $this->drop_tables ) {
           $value .= 'DROP TABLE IF EXISTS `' . $table . '`;' . __SEP__ . MSB_NL;
       }
       if ( !( $result = $this->_Query('SHOW CREATE TABLE ' . $table) ) ) {
           return false;
       }
       $row = mysql_fetch_assoc($result);
       $value .= str_replace("\n", MSB_NL, $row['Create Table']) . ';' . __SEP__;
       $value .= MSB_NL . MSB_NL;
       if (!$this->struct_only) {
               if ($this->comments) {
                   $value .= '#' . MSB_NL;
                   $value .= '# Dumping data for table `' . $table . '`' . MSB_NL;
                   $value .= '#' . MSB_NL . MSB_NL;
               }
               $value .= $this->_GetInserts($table);
       }
       $value .= MSB_NL . MSB_NL;
       $this->_Query('UNLOCK TABLES');
       return $value;
   }

   function _GetInserts($table) {
       $value = '';
       if (!($result = $this->_Query('SELECT * FROM ' . $table))) {
           return false;
       }
       if ( $this->complete_inserts ) {
               while ($row = mysql_fetch_row($result)) {
                   $values = '';
                   foreach ($row as $data) {
                       $values .= '\'' . addslashes($data) . '\', ';
                   }
                   $values = substr($values, 0, -2);
                   $value .= 'INSERT INTO ' . $table . ' VALUES (' . $values . ');' . __SEP__ . MSB_NL;
               }
       } else {
               $blocks_counter = 0;
           $blocks = array();
           while ($row = mysql_fetch_row($result)) {
               $values = array();
               foreach ($row as $data) {
                   $values[] = '\'' . addslashes($data) . '\'';
               }
               $blocks[] = '(' . implode( ',', $values ) . ')';

               if ( $blocks_counter < $this->inserts_block ) {
                   $blocks_counter++;
               } else {
                       $value .= 'INSERT INTO ' . $table . ' VALUES ' . implode( ',', $blocks ) . ";" . __SEP__ . MSB_NL;
                       $blocks = array();
                       $blocks_counter = 0;
               }
           }
               if ( count( $blocks ) ) {
               $value .= 'INSERT INTO ' . $table . ' VALUES ' . implode( ',', $blocks ) . ";" . __SEP__ . MSB_NL;
               }
       }
       return $value;
   }


   function _Retrieve() {
       $value = '';
       if (!$this->_Connect()) {
           return false;
       }
       if ($this->comments) {
           $value .= '#' . MSB_NL;
           $value .= '# MySQL database dump' . MSB_NL;
           $value .= '# Created by MySQL_Backup class, ver. ' . MSB_VERSION . MSB_NL;
           $value .= '#' . MSB_NL;
           $value .= '# Host: ' . $this->server . MSB_NL;
           $value .= '# Generated: ' . date('M j, Y') . ' at ' . date('H:i') . MSB_NL;
           $value .= '# MySQL version: ' . mysql_get_server_info() . MSB_NL;
           $value .= '# PHP version: ' . phpversion() . MSB_NL;
           if (!empty($this->database)) {
               $value .= '#' . MSB_NL;
               $value .= '# Database: `' . $this->database . '`' . MSB_NL;
           }
           $value .= '#' . MSB_NL . MSB_NL . MSB_NL;
       }
       if (!($tables = $this->_GetTables())) {
           return false;
       }
       foreach ($tables as $table) {
           if (!($table_dump = $this->_DumpTable($table))) {
               $this->error = mysql_error();
               return false;
           }
           $value .= $table_dump;
       }
       return $value;
   }


   function _SaveToFile($fname, $sql, $compress) {
       if ($compress) {
           if (!($zf = gzopen($fname, 'w9'))) {
               $this->error = 'Can\'t create the output file.';
               return false;
           }
           gzwrite($zf, $sql);
           gzclose($zf);
       } else {
               if (!($f = fopen($fname, 'w'))) {
                   $this->error = 'Can\'t create the output file.';
                   return false;
               }
               fwrite($f, $sql);
               fclose($f);
       }
       return true;
   }

   function _DownloadFile($fname, $sql, $compress) {
       header('Content-disposition: filename=' . $fname);
       header('Content-type: application/octetstream');
       header('Pragma: no-cache');
       header('Expires: 0');
       echo ($compress ? gzencode($sql) : $sql);
       return true;
   }
}

?>

Tutorial Make Random Number

by in , 0

function getRandomId($min = NULL, $max = NULL) {
       if (is_numeric($min) && is_numeric($max)) {
               return mt_rand($min, $max);
       }
       else {
               return mt_rand();
       }
}

Tutorial Login Function

by in , 0

These functions will log in a user based on a username and password being matched in a MySQL database.

// function to escape data and strip tags
function safestrip($string){
       $string = strip_tags($string);
       $string = mysql_real_escape_string($string);
       return $string;
}

//function to show any messages
function messages() {
   $message = '';
   if($_SESSION['success'] != '') {
       $message = '<span class="success" id="message">'.$_SESSION['success'].'</span>';
       $_SESSION['success'] = '';
   }
   if($_SESSION['error'] != '') {
       $message = '<span class="error" id="message">'.$_SESSION['error'].'</span>';
       $_SESSION['error'] = '';
   }
   return $message;
}

// log user in function
function login($username, $password){

 //call safestrip function
 $user = safestrip($username);
 $pass = safestrip($password);

 //convert password to md5
 $pass = md5($pass);

  // check if the user id and password combination exist in database
  $sql = mysql_query("SELECT * FROM table WHERE username = '$user' AND password = '$pass'")or die(mysql_error());

  //if match is equal to 1 there is a match
  if (mysql_num_rows($sql) == 1) {

                          //set session
                          $_SESSION['authorized'] = true;

                          // reload the page
                         $_SESSION['success'] = 'Login Successful';
                         header('Location: ./index.php');
                         exit;


   } else {
               // login failed save error to a session
               $_SESSION['error'] = 'Sorry, wrong username or password';
  }
}

Usage

Values would be captured from a form and then passed to the main function:

login($username, $password);

All pages involved would have the messages function somewhere so proper use feedback is given:

messages();

Tutorial Insert Element Every nth Loop

by in , 0

When inside of a loop, you can keep track of the iteration number of the loop (shown below is a simple for loop). Using that iteration number, you can calculate it's modulus of some number (number left over after an even division). If that modulus is zero, you are at an even division of whatever that number was.

So in this simple loop below, it will output something every third time through the loop:

<?php
   for ($counter = 1; $counter < 100; $counter++ ) {
     if ($counter % 3 == 0) {
            echo "<p>Every third!</p>";
     }  
   }
?>

Tutorial Increase Maximum PHP Upload Size

by in , 0

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

Tutorial Import CSV into MySQL

by in , 0

<?php

$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername ="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "filename.csv";

/********************************/
/* Would you like to add an ampty field at the beginning of these records?
/* This is useful if you have a table with the first field being an auto_increment integer
/* and the csv file does not have such as empty field before the records.
/* Set 1 for yes and 0 for no. ATTENTION: don't set to 1 if you are not sure.
/* This can dump data in the wrong fields if this extra field does not exist in the table
/********************************/
$addauto = 0;
/********************************/

/* Would you like to save the mysql queries in a file? If yes set $save to 1.
/* Permission on the file should be set to 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
/********************************/
$save = 1;
$outputfile = "output.sql";
/********************************/

if (!file_exists($csvfile)) {
        echo "File not found. Make sure you specified the correct path.\n";
        exit;
}

$file = fopen($csvfile,"r");

if (!$file) {
        echo "Error opening data file.\n";
        exit;
}

$size = filesize($csvfile);

if (!$size) {
        echo "File is empty.\n";
        exit;
}

$csvcontent = fread($file,$size);

fclose($file);

$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());

$lines = 0;
$queries = "";
$linearray = array();

foreach(split($lineseparator,$csvcontent) as $line) {

        $lines++;

        $line = trim($line," \t");

        $line = str_replace("\r","",$line);

        /************************************
        This line escapes the special character. remove it if entries are already escaped in the csv file
        ************************************/
        $line = str_replace("'","\'",$line);
        /*************************************/

        $linearray = explode($fieldseparator,$line);

        $linemysql = implode("','",$linearray);

        if($addauto)
                $query = "insert into $databasetable values('','$linemysql');";
        else
                $query = "insert into $databasetable values('$linemysql');";

        $queries .= $query . "\n";

        @mysql_query($query);
}

@mysql_close($con);

if ($save) {

        if (!is_writable($outputfile)) {
                echo "File is not writable, check permissions.\n";
        }

        else {
                $file2 = fopen($outputfile,"w");

                if(!$file2) {
                        echo "Error writing to the output file.\n";
                }
                else {
                        fwrite($file2,$queries);
                        fclose($file2);
                }
        }

}

echo "Found a total of $lines records in this csv file.\n";

?>

Reference URL

Tutorial HTTP or HTTPS

by in , 0

if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'
    || $_SERVER['SERVER_PORT'] == 443) {

  // HTTPS

} else {

  // HTTP

}

Tutorial HTML Tidy

by in , 0

function html_tidy( $input_html, $indent = "true", $no_body_tags = "true", $fix = "true" ) {
   ob_start(  );
   $tidy = new tidy;
   $config = array( 'indent' => $indent, 'output-xhtml' => true, 'wrap' => 200, 'clean' => $fix, 'show-body-only' => $no_body_tags );
   $tidy->parseString( $input_html, $config, 'utf8' );
   $tidy->cleanRepair(  );
   $input = $tidy;
   return $input;
}

Tutorial Highlight a Substring

by in , 0

<?php
       $text='Would you be so kind to highlight css-tricks.com in this string?';
       $search='css-tricks.com';

       echo textHighlight($text,$search);

       //Performs a regex-texthighlight
       function textHighlight($text,$search,$highlightColor='#0000FF',$casesensitive=false)
       {
               $modifier=($casesensitive) ? 'i' : '';
               //quote search-string, cause preg_replace wouldn't work correctly if chars like $?. were in search-string
               $quotedSearch=preg_quote($search,'/');
               //generate regex-search-pattern
               $checkPattern='/'.$quotedSearch.'/'.$modifier;
               //generate regex-replace-pattern
               $strReplacement='$0';
               return preg_replace($checkPattern,$strReplacement,$text);
       }
?>

This code performs a regular-expression-replace to add a span-tag with a definable color. Can be used either for case-sensitive and case-insensitive replacements.

Tutorial Get Width/Height of Image

by in , 0

If all you have for an image is the URL, you can still find the dimensions:

<?php

  list($width, $height, $type, $attr) = getimagesize("url/to/image.jpg");

  echo "Image width " . $width;
  echo "Image height " . $height;
  echo "Image type " . $type;
  echo "Attribute " . $attr;

?>

Reference URL