Showing posts with label php. Show all posts

Convert html code to image PNG, JPG

by in 0

You can use this code to convert html code into images.
Switch imagepng to imagegif, imagejpg as your purpose.

$html_code = "this is the body";

$my_img = imagecreate( 200, 80 );
$background = imagecolorallocate( $my_img, 0, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
//$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, "$html_code",$text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );

header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );

Create a phpFox module

by in , 0

This tutorial help you get the basic concept & knowledge about phpFox module structure and how it communicate with others.


Read more »

Convert a utf-8 string to a utf-16 string in PHP

by in 0

- You could also use iconv.
It's native in PHP, but require that all your text is one charset. Else it could discard characters.

- In other way, mbstring supports UTF-16, so you can use mb_convert_encoding.


PDO query to fetch all tables

by in , 0

Execute the query with PDO::query():
If you fetch an associative array, the name of the column will be:
Note: this will list both tables and views. If you must get only tables, use this instead:
FROM information_schema.TABLES 
  AND TABLE_SCHEMA='yourdatabasename';

PHP Fix errors if mbstring is not loaded

by in 0

My script work good on shared hosting until hosting disable mbstring

Now my script can't run.
Many functions MB_  mb_strrpos mb_get_info .... get undefined errors.

Read more »

Htaccess show no_found picture if picture is not exist

by in , 0

RewriteEngine On
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .*$ /no_picture.png [L]
Let's break it down as to what each line means.
RewriteCond %{REQUEST_URI} \.(jpg|jpeg|gif|png)$ [NC]
Check to see if the requested file is of a file extension in the parentheses (). In this case, we're testing to see if the file name ends in either .jpg, .jpeg, .gif or .png
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Check that the file is not there and it's also not a directory.
RewriteRule .*$ /no_picture.png [L]
If a requested resource/file passes all those tests, then it's an image that does not exist. So serve back the image of no_picture.png to the browser. This will keep the filename. If you want to redirect to the no_picture.png filename, change [L] to [R]

CSS parser in PHP

by in 0


$css = new cssparser();
$css->ParseStr("b {font-weight: bold; color: #777777;} b.test{text-decoration: underline;}");
echo $css->Get("b","color");     // returns #777777
echo $css->Get("b.test","color");// returns #777777
echo $css->Get(".test","color"); // returns an empty string

You can Parser Css code in php easily

PHP function detect utf8 string

by in 0

It's working on PHP4, PHP5

function is_utf8($str) {
    $c=0; $b=0;
    for($i=0; $i<$len; $i++){
        if($c > 128){
            if(($c >= 254)) return false;
            elseif($c >= 252) $bits=6;
            elseif($c >= 248) $bits=5;
            elseif($c >= 240) $bits=4;
            elseif($c >= 224) $bits=3;
            elseif($c >= 192) $bits=2;
            else return false;
            if(($i+$bits) > $len) return false;
            while($bits > 1){
                if($b < 128 || $b > 191) return false;
    return true;

Function php convert string to UTF-8

by in 0

conver string to Utf8 if String is not equals to 'UTF-8'

*QQ: 290359552
* conver to Utf8 if $str is not equals to 'UTF-8'
function convToUtf8($str)
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )

return  iconv("gbk","utf-8",$str);

return $str;


function detect Unicode UTF-8 string PHP

by in 0

Based upon that snippet below using preg_match() I needed something faster and less specific.  That function works and is brilliant but it scans the entire strings and checks that it conforms to UTF-8

function detectUTF8($string)
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);

Prevent multiple inserts when submitting a form in PHP

by in 0

Sometimes the user may press Enter twice, and the post is inserted twice.

Is there a solution to prevent this other than check if there is already a post with the same title and content?

1- Use JavaScript to stop it from sending

2 - disable the submit button once the user has submitted the form, using JavaScript. That is what, for example
3 - Include a unique token on each POST worked for me. However, my form still submits when a user refreshes the page (F5). I managed to solve this by adding a reset:
            // reset session token
            $_SESSION['token'] = md5( $_POST['token'] . time() );
my final scripts goes like:
if (isset($_SESSION['token'])) {
    if (isset($_POST['token'])) {
        if ($_POST['token'] != $_SESSION['token']) {
            echo '<h3>Oops! You already submitted this request.</h3>';
        } else {
            // process form
            // reset session token
            $_SESSION['token'] = md5( $_POST['token'] . time() );
    } else {
        echo 'post token not set';
        $_SESSION['token'] = md5( $somevariable . time() );
oh! don't forget to add session_start(); before <!DOCTYPE>
I am a PHP newbie so please correct me if you find irregularities.

How to prevent multiple inserts when submitting a form in PHP?

Remove URL from string PHP

by in 0

f I have a string that contains a url (for examples sake, we'll call it $url) such as;

$url = "Here is a funny site";
How do i remove the URL from the string? Difficulty is, urls might also show up without the http://, such as ;
$url = "Here is another funny site";

There is no HTML present. How would i start a search if http or www exists, then remove the text/numbers/symbols until the first space?


function containsTLD($string) {
  $has_tld = (count($M) > 0) ? true : false;
  return $has_tld;

function cleaner($url) {
  $U = explode(' ',$url);

  $W =array();
  foreach ($U as $k => $u) {
    if (stristr($u,".")) { //only preg_match if there is a dot    
      if (containsTLD($u) === true) {
      return cleaner( implode(' ',$U));
  return implode(' ',$U);

$url = "Here is another funny site badurl.badone but this and and";
echo "Cleaned: " . cleaner($url);

Cleaned: Here is another funny site badurl.badone but this and and

PHP Detect URL Protocol - http vs https

by in 0

I've written a little function to establish the current site url protocol but I don't have SSL and don't know how to test if it works under https. Can you tell me if this is correct?

function siteURL()
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
define( 'SITE_URL', siteURL() );
Is it necessary to do it like above or can I just do it like?:
function siteURL()
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
define( 'SITE_URL', siteURL() );
Under SSL, doesn't the server automatically convert the url to https even if the anchor tag url is using http? Is it necessary to check for the protocol?

Thank you!

Read more »

Download image with PHP CURL

by in 0

If you have allow_url_fopen set to true:

$url = '';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));

Else use cURL:

$ch = curl_init('');
$fp = fopen('/my/folder/flower.gif', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

Source: Saving image from PHP URL using PHP

Tutorial Zero Padded Numbers

by in , 0

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


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

Tutorial Variable Variables

by in , 0


  $var1 = 'nameOfVariable';

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

  echo $$var1; 


Reference URL

Tutorial URL Validation

by in , 0

$url = '';
$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");

//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>

//loop through all results

//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><input name="email[]" type="text" id="price" value="'.$r->email.'"></td>

//submit button
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>

// if form has been submitted, process it
       // 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';

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

$zip = zip_open("");
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));

Reference URL

Tutorial Truncate String by Words

by in , 0

Technique #1

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
       // Implode the array for output, and append an ellipse
       $words = implode(' ', $words) . $append;
       // Return the result
       return $words;