Pages

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Sunday, May 18, 2014

Check XSS script when form submit - PHP

If you want to check XSS script than please write below code:

checkMagicQuotes();
checkXssScript();

function checkMagicQuotes()
{
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
function stripslashes_deep($value)
   {
       return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
   }
   $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
}

function checkXssScript()
{
function stripXss($value)
{
$tags = array(
    '@<script[^>]*?>.*?</script>@si',
    '@&#(\d+);@e',
    '@\[\[(.*?)\]\]@si',
    '@\[!(.*?)!\]@si',
    '@\[\~(.*?)\~\]@si',
    '@\[\((.*?)\)\]@si',
    '@{{(.*?)}}@si',
    '@\[\*(.*?)\*\]@si'
   );
   return is_array($value) ? array_map('stripXss', $value) : preg_replace($tags, '', $value);
}
$_POST    = array_map('stripXss', $_POST);
$_GET     = array_map('stripXss', $_GET);
$_COOKIE  = array_map('stripXss', $_COOKIE);
$_REQUEST = array_map('stripXss', $_REQUEST);
}

Wednesday, March 26, 2014

file_get_contents not working with utf8 - [resolved]

If you want to encode special characters from "file_get_contents" than please write below code:

$stringCnt = file_get_contents("URL");
$stringCnt = mb_convert_encoding($stringCnt, 'UTF-8', mb_detect_encoding($stringCnt, 'UTF-8, ISO-8859-1', true));

You can encode "¡ÅѺ˹éÒáá¾ÃФÑÁÀÕÃìÀÒÉÒä·Â©ºÑº" characters.

And If you are using other language than you have to use other encoding method.

Monday, October 21, 2013

United Kingdom postal code validation - PHP [resolved]

<?php

function check_uk_postcode($string){
// Start config
$valid_value = 'true';
$invalid_value = 'false';
$exceptions = array('BS981TL', 'BX11LT', 'BX21LB', 'BX32BB', 'BX55AT', 'CF101BH', 'CF991NA', 'DE993GG', 'DH981BT', 'DH991NS', 'E161XL', 'E202AQ', 'E202BB', 'E202ST', 'E203BS', 'E203EL', 'E203ET', 'E203HB', 'E203HY', 'E981SN', 'E981ST', 'E981TT', 'EC2N2DB', 'EC4Y0HQ', 'EH991SP', 'G581SB', 'GIR0AA', 'IV212LR', 'L304GB', 'LS981FD', 'N19GU', 'N811ER', 'NG801EH', 'NG801LH', 'NG801RH', 'NG801TH', 'SE18UJ', 'SN381NW', 'SW1A0AA', 'SW1A0PW', 'SW1A1AA', 'SW1A2AA', 'SW1P3EU', 'SW1W0DT', 'TW89GS', 'W1A1AA', 'W1D4FA', 'W1N4DJ');
// Add Overseas territories ?
array_push($exceptions, 'AI-2640', 'ASCN1ZZ', 'STHL1ZZ', 'TDCU1ZZ', 'BBND1ZZ', 'BIQQ1ZZ', 'FIQQ1ZZ', 'GX111AA', 'PCRN1ZZ', 'SIQQ1ZZ', 'TKCA1ZZ');
// End config


$string = strtoupper(preg_replace('/\s/', '', $string)); // Remove the spaces and convert to uppercase.
$exceptions = array_flip($exceptions);
if(isset($exceptions[$string])){return $valid_value;} // Check for true exception
$length = strlen($string);
if($length < 5 || $length > 7){return $invalid_value;} // Check for false length
$letters = array_flip(range('A', 'Z')); // An array of letters as keys
$numbers = array_flip(range(0, 9)); // An array of numbers as keys

switch($length){
case 7:
if(!isset($letters[$string[0]], $letters[$string[1]], $numbers[$string[2]], $numbers[$string[4]], $letters[$string[5]], $letters[$string[6]])){break;}
if(isset($letters[$string[3]]) || isset($numbers[$string[3]])){
return $valid_value;
}
break;
case 6:
if(!isset($letters[$string[0]], $numbers[$string[3]], $letters[$string[4]], $letters[$string[5]])){break;}
if(isset($letters[$string[1]], $numbers[$string[2]]) || isset($numbers[$string[1]], $letters[$string[2]]) || isset($numbers[$string[1]], $numbers[$string[2]])){
return $valid_value;
}
break;
case 5:
if(isset($letters[$string[0]], $numbers[$string[1]], $numbers[$string[2]], $letters[$string[3]], $letters[$string[4]])){
return $valid_value;
}
break;
}

return $invalid_value;
}
?>

Tuesday, August 13, 2013

PHP get week number from date



function get_week_number_by_date($date) {

$today = $date;
$currentDay = date("w", strtotime($date));
$todate = date('Y-m-d', strtotime($date));
$myTime = $todate." 18:00:00";

$weekNumber = date("W", strtotime("0 day", strtotime($date)));

if($currentDay == 0){
if(strtotime($today) > strtotime($myTime)){
$weekNumber = date("W", strtotime("1 day", strtotime($date)));
}
}
return $weekNumber;
}

In this example I have setup "sunday 6:00 PM" as a week start day.

Monday, July 15, 2013

PHP code to add st, nd, rd or th to a number



function wp_get_ordinal($input_number)
{
  $number            = (string) $input_number;
  $last_digit        = substr($number, -1);
  $second_last_digit = substr($number, -2, 1);
  $suffix            = 'th';
  if ($second_last_digit != '1')
  {
    switch ($last_digit)
    {
      case '1':
        $suffix = 'st';
        break;
      case '2':
        $suffix = 'nd';
        break;
      case '3':
        $suffix = 'rd';
        break;
      default:
        break;
    }
  }
  if ((string) $number === '1') $suffix = 'st';
  return $number.$suffix;
}

Friday, July 12, 2013

PHP Cron setup




/usr/local/bin/php /home/ABC/public_html/plonk/cron.php>/home/ABC/public_html/cron/cronlog_`date "+\%Y-\%m-\%d_\%H-\%M"`.txt

Thursday, July 11, 2013

How to get youtube video duration from id - PHP



function parseVideoEntry($video_id) {    
    $obj= new stdClass;

$url = 'http://gdata.youtube.com/feeds/api/videos/'.$video_id;
$categoriesArray = array();
$xml = simplexml_load_file($url);


    $media = $xml->children('http://search.yahoo.com/mrss/');
    $obj->title = $media->group->title;
    $obj->description = $media->group->description;
     
    $yt = $media->children('http://gdata.youtube.com/schemas/2007');
    $attrs = $yt->duration->attributes();

    $obj->length = $attrs['seconds'];
    $VideoSeconds = $obj->length;
    return $VideoSeconds;    
}

echo $video = parseVideoEntry("nVhM3IYMF8o");

Convert seconds to hours, minutes and seconds - PHP


function secondsToWords($seconds)
{
    /*** return value ***/
    $ret = "";

    /*** get the hours ***/
    $hours = intval(intval($seconds) / 3600);
    if($hours > 0)   {
        if($hours <= 9) { $ret .= "0".$hours.":";}
else {       $ret .= $hours.":";}
    }
    /*** get the minutes ***/
    $minutes = bcmod((intval($seconds) / 60),60);
    if($hours > 0 || $minutes > 0)
    {
if($minutes <= 9) { $ret .= "0".$minutes.":";}
else {       $ret .= $minutes.":";}
    }
 
    /*** get the seconds ***/
    $seconds = bcmod(intval($seconds),60);
if($seconds <= 9) { $ret .= "0".$seconds;}
else {       $ret .= $seconds;}

    return $ret;
}

echo secondsToWords(3725);

Monday, July 8, 2013

Get Youtube video id from embaded code - PHP

function parse_youtube($link){

    $regexstr = '~
        # Match Youtube link and embed code
        (?:                             # Group to match embed codes
            (?:<iframe [^>]*src=")?       # If iframe match up to first quote of src
            |(?:                        # Group to match if older embed
                (?:<object .*>)?      # Match opening Object tag
                (?:<param .*</param>)*  # Match all param tags
                (?:<embed [^>]*src=")?  # Match embed tag to the first quote of src
            )?                          # End older embed code group
        )?                              # End embed code groups
        (?:                             # Group youtube url
            https?:\/\/                 # Either http or https
            (?:[\w]+\.)*                # Optional subdomains
            (?:                         # Group host alternatives.
            youtu\.be/                  # Either youtu.be,
            | youtube\.com              # or youtube.com
            | youtube-nocookie\.com     # or youtube-nocookie.com
            )                           # End Host Group
            (?:\S*[^\w\-\s])?           # Extra stuff up to VIDEO_ID
            ([\w\-]{11})                # $1: VIDEO_ID is numeric
            [^\s]*                      # Not a space
        )                               # End group
        "?                              # Match end quote if part of src
        (?:[^>]*>)?                       # Match any extra stuff up to close brace
        (?:                             # Group to match last embed code
            </iframe>                 # Match the end of the iframe
            |</embed></object>          # or Match the end of the older embed
        )?                              # End Group of last bit of embed code
        ~ix';

    preg_match($regexstr, $link, $matches);
    return $matches[1];
}

function get_youtube_id($embadedcode){
 if(strpos($embadedcode,'iframe') !== false){
  return parse_youtube($embadedcode);
 } else if(strpos($embadedcode,'object') !== false){
  preg_match('#(?<=youtube\.com/v/)\w+#', $embadedcode, $matches);
  return $matches[0];
 }
}

Friday, March 8, 2013

woocommerce redirect user to cart page after click on add to cart



Please write this code in functions.php file in wordpress theme

add_filter('add_to_cart_redirect', 'custom_add_to_cart_redirect');

function custom_add_to_cart_redirect() {
     return get_permalink(get_option('woocommerce_cart_page_id')); // Replace with the url of your choosing
}

Wednesday, March 6, 2013

Add wordpress post from front-end with featured images and send mail [resolved]


/*Create Form*/

<form class="story" name="share_story" action="" method="POST"  id="story_form" enctype="multipart/form-data">
    <label>Name</label><br />
    <input type="text" class="flat_input_box" name="share_name" id="share_name" /><br />  
    <label>Email address</label><br />
    <input type="text" class="flat_input_box" name="share_email_address" id="email_address" /><br />  
    <label>Upload Image</label><br />
    <input type="file" name="story_image" class="flat_input_box" id="featured_image" /><br />
    <label>Story Title</label><br />
    <input type="text" class="flat_input_box" name="story_title" id="story_title" /><br />
    <textarea class="flat_input_box" name="story_content" id="story_content"></textarea><br />  
    <div class="right">
        <a href="#">Cancel</a>
     <input class="blue_btn" type="submit" value="Submit" onclick="return CheckStoryForm();" name="submit" />
    </div>
</form>

/*Create Form */

/*Javascript validation Starts*/

<script>
function CheckStoryForm(){
var result = true;
var emailcheck = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var emailval = document.share_story.email_address.value;
if(document.share_story.name.value==''){
alert("Please enter name");
return false;
}
if(document.share_story.email_address.value==''){
alert("Please enter email address");
return false;
}
else if(!emailcheck.test(emailval))
{
alert('Please enter valid email address');
return false;
}

var fup = document.getElementById('featured_image');
var fileName = fup.value;
if(fileName != ''){
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "png" || ext == "PNG")
{
return true;
}
else{
alert("Please upload image with jpg, png, gif, jpeg formate.");
fup.focus();
return false;
}
}
if(document.share_story.story_title.value==''){
alert("Please enter title of story");
return false;
}

return true;
}
</script>

/*Javascript validation Ends*/


/*Post Submission Starts*/
if(isset($_POST['submit'])){

$name = $_POST['share_name'];
$email_address = $_POST['share_email_address'];
$story_title = $_POST['story_title'];
$story_content = $_POST['story_content'];
$admin_email = get_settings('admin_email');

/*custom post type*/
$new_post = array(
'post_title' => $story_title,
'post_content' => $story_content,
'post_status' => 'private',           // Choose: publish, preview, future, draft, etc.
'post_type' => 'share_your_story'  //'post',page' or use a custom post type if you want to
);
$pid = wp_insert_post($new_post);
/*custom post type*/

/*create and upload featured image with multiple resolution*/
$MyImage = '';
if(!empty($_FILES['story_image']['name'])){

include("simpleImage.php");  // please check http://ewebsurf.blogspot.in/2013/03/simpleimagephp.html from here you can copy the code of this file

$uploaddir = wp_upload_dir(); // get wordpress upload directory
$myDirPath = $uploaddir['path'];
$myDirUrl = $uploaddir['url'];

$MyImage = rand(0,5000).$_FILES['story_image']['name'];
$image_path = $myDirPath.'/'.$MyImage;
copy($_FILES['story_image']['tmp_name'],$image_path);

list($width, $height, $type, $attr) = getimagesize($myDirUrl.'/'.$MyImage); // get image property

$image = new SimpleImage();

$large_width = get_option('large_size_w');    // get large image resolution set as admin panel
$large_height = get_option('large_size_h');
if($width > $large_width || $height > $large_height){

$dimensions = fw_get_dimension_new($image_path, $large_width, $large_height);
$largeimage = $image_path;
$info = pathinfo($largeimage);
$image_name =  basename($largeimage,'.'.$info['extension']);
$ext = end(explode('.', $largeimage));
$newlargeimg = $myDirPath.'/'.$image_name.'-'.$dimensions['width'].'x'.$dimensions['height'].'.'.$ext;
copy($image_path,$newlargeimg);

            $image->load($newlargeimg);
            $image->resize($dimensions['width'],$dimensions['height']);
            $image->save($newlargeimg);
}

$medium_width = get_option('medium_size_w');
$medium_height = get_option('medium_size_h');

if($width > $medium_width || $height > $medium_height){

$dimensions = fw_get_dimension_new($image_path, $medium_width, $medium_height);
$mediumimage = $image_path;
$info = pathinfo($mediumimage);
$image_name =  basename($mediumimage,'.'.$info['extension']);
$ext = end(explode('.', $mediumimage));
$newmediumimg = $myDirPath.'/'.$image_name.'-'.$dimensions['width'].'x'.$dimensions['height'].'.'.$ext;
copy($image_path,$newmediumimg);

            $image->load($newmediumimg);
            $image->resize($dimensions['width'],$dimensions['height']);
            $image->save($newmediumimg);
}

$thumb_width = get_option('thumbnail_size_w');
$thumb_height = get_option('thumbnail_size_h');

if($width > $thumb_width || $height > $thumb_height){

$dimensions = fw_get_dimension_new($image_path, $thumb_width, $thumb_height);
$thumbimage = $image_path;
$info = pathinfo($thumbimage);
$image_name =  basename($thumbimage,'.'.$info['extension']);
$ext = end(explode('.', $thumbimage));
           
$ImageCrop = get_option('thumbnail_crop');
if($ImageCrop == 1){
$newthumbimg = $myDirPath.'/'.$image_name.'-150x150.'.$ext;
copy($image_path,$newthumbimg);

$image->load($newthumbimg);
$image->resize($thumb_width,$thumb_height);
} else {
$newthumbimg = $myDirPath.'/'.$image_name.'-'.$dimensions['width'].'x'.$dimensions['height'].'.'.$ext;
copy($image_path,$newthumbimg);

$image->load($newthumbimg);
$image->resize($dimensions['width'],$dimensions['height']);
}
            $image->save($newthumbimg);
}


$file = $MyImage;
$uploadfile = $myDirPath.'/' . basename( $file );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $pid
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );

require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploadfile );
wp_update_attachment_metadata( $attach_id,  $attach_data );

set_post_thumbnail( $pid, $attach_id );

}

$to = "Your Email Address";
$subject = " New Story ";
$headers = "From: $name <$email_address>\r\n";
$headers .= "MIME-Version: 1.0\r\n"."Content-Type: multipart/mixed; boundary=\"1a2a3a\"";

$message .= "If you can see this MIME than your client doesn't accept MIME types!\r\n"."--1a2a3a\r\n";

$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
."Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= '<table>';
$message .= '<tr><td><b>Name</b></td><td>'.$name.'</td></tr>';
$message .= '<tr><td><b>Email</b></td><td>'.$email_address.'</td></tr>';
$message .= '<tr><td><b>Story Title</b></td><td>'.$story_title.'</td></tr>';
$message .= '<tr><td colspan="2"><b>Content</b></td></tr>';
$message .= '<tr><td colspan="2">'.nl2br($story_content).'</td></tr>';
$message .= '</table>';
$message .= "\r\n"."--1a2a3a\r\n";

if($image != ''){
$file = file_get_contents($image_path);

$message .= "Content-Type: image/jpg; name=\"featuredimage.jpg\"\r\n"
  ."Content-Transfer-Encoding: base64\r\n"
  ."Content-disposition: attachment; file=\"$MyImage\"\r\n"
  ."\r\n"
  .chunk_split(base64_encode($file))
  ."--1a2a3a--";
}

if (mail($to, $subject, $message, $headers)) {
echo '<script>document.location="'.get_permalink().'/?msg=1";</script>';
} else {
echo '<script>document.location="'.get_permalink().'/?msg=2";</script>';
}


}

/*Post Submission Ends*/



Monday, February 25, 2013

How to get all the children of a specific nav menu item?


$menu_items = wp_get_nav_menu_items('MenuName');
echo '<ul>';
foreach($menu_items as $key => $val){
if($menu_items[$key]->menu_item_parent == 0){
echo '<li>';
echo $menu_items[$key]->title;
$submenuitem = get_nav_menu_item_children($menu_items[$key]->ID, $menu_items);
if(!empty($submenuitem)){
echo '<ul>';
foreach($submenuitem as $skey => $sval){
echo '<li id="post-'.$submenuitem[$skey]->object_id.'">';
echo $submenuitem[$skey]->title;
echo '</li>';
}
echo '</ul>';
}
echo '</li>';
}
}
echo '</ul>';

Sunday, February 3, 2013

Image Upload with multiple resolution


           
                $additional_image_name = rand(0,5000).$_FILES['additional_image']['name'];
                $additional_image_name_path = "images/".$additional_image_name;
                copy($_FILES['additional_image']['tmp_name'],$additional_image_name_path);
              
                $file = $additional_image_name_path;
                $img_dbname = $additional_image_name;
               

                require_once(simpleImage.php');
           
                $image = new SimpleImage();

                $dimensions = zen_get_dimension_new($file,'800','800');
                $image->load($file);
                $image->resize($dimensions['width'],$dimensions['height']);
                $image->save($file);

                $dimensions = zen_get_dimension_new($file,'400','400');
                $image->resize($dimensions['width'],$dimensions['height']);
                $filename_medium = 'medium/' . $img_dbname;
                $image->save($filename_medium);

                $dimensions = zen_get_dimension_new($file,'100','100');
                $image->resize($dimensions['width'],$dimensions['height']);
                $filename_medium = 'icons/' . $img_dbname;
                $image->save($filename_medium);

And you can download image file from "http://www.thewebsdevelopment.com/test/simpleImage.zip"


Thursday, January 3, 2013

N level Category Tree using php and mysql - [resolved]

First Method

function get_categories($parent = 0)
{
    $html = '<ul>';
    $query = mysql_query("SELECT * FROM `categories` WHERE `category_parent` = '$parent'");
    while($row = mysql_fetch_assoc($query))
    {
        $current_id = $row['category_id'];
        $html .= '<li>' . $row['category_name'];
        $has_sub = NULL;
        $has_sub = mysql_num_rows(mysql_query("SELECT COUNT(`category_parent`) FROM `categories` WHERE `category_parent` = '$current_id'"));
        if($has_sub)
        {
            $html .= get_categories($current_id);
        }
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}

print get_categories();


Monday, December 31, 2012

Error types in PHP

PHP has a number of possible errors that it might return, all of which mean something different and are treated differently. Here is the complete list:
E_ERROR Fatal run-time error. Script execution is terminated because the error cannot be recovered from.
E_WARNING Run-time warning. Execution of the script is not terminated because the situation can be recovered from.
E_PARSE Compile-time parse errors. Only generated by the PHP parser.
E_NOTICE Run-time notice. Execution of the script is not terminated, but it is possible there is an error in your code.
E_CORE_ERROR Fatal error in PHP’s internals. Indicates a serious problem with your PHP installation.
E_CORE_WARNING Compile-time warning. Generally indicates a problem with your PHP installation.
E_COMPILE_ERROR Fatal compile-time error. This indicates a syntax error in your script that could not be recovered from.
E_COMPILE_WARNING This indicates a non-fatal syntax error in your script
E_USER_ERROR User-generated error message. This is generated from inside PHP scripts to halt execution with an appropriate message.
E_USER_WARNING User-generated warning message. This is generated from inside PHP scripts to flag up a serious warning message without halting execution.
E_USER_NOTICE User-generated notice message. This is generated from inside PHP scripts to print a minor notice to the screen, usually regarding potential problems with scripts.
E_ALL This is a catch-all error type, which means “all errors combined”.
All warnings and notices can usually be recovered from without too much problem, however errors are critical and usually mean “you would not want to recover from this”.
User errors, user warnings, and user notices are all generated using the trigger_error() function, and you should use them in your own code to handle possible errors that others (or indeed you) might make when calling your own functions.
Notices are generally very minor things – using an uninitialized variable, for example – that may be a sign that you have got a hidden bug lurking in there, but it may also be there by design, as notices are generally quite strict.

Wednesday, December 26, 2012

How to implement a link scraper in PHP? - [resolved]


$html = file_get_contents("http://example.com");

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

$list_urls = array();
$list_urlval = array();
for ($i = 0; $i < $hrefs->length; $i++) {
        $nValue = $hrefs->item($i);   
        $href = $nValue->getAttribute('href');
        $value = $nValue->nodeValue;
       
        if($href != '' && (!preg_match("/#/", $href)) && $href != '/' && (!preg_match("/javascript/", $href)) && (!preg_match("/mailto/", $href)) && (!preg_match("/plus.google/", $href))){
       
            if((!preg_match("/http/", $href)))
                $href = $urlname.'/'.$href;
               
            $list_urls[] = $href;
            $list_urlval[] = $value;
        }
}

print_r(array_unique($list_urls));


Friday, December 7, 2012

PHP resize an image without losing quality - [resolved]

PHP resize an image without losing quality, we will explain how we can resize an image through PHP, with only 3 lines of code. And most importantly, without the result is a pixelated image.

We begin:

To do this we will use the Imagick PHP Library (Image magic), which is included in PHP itself from version 5.1.3. As a second step we must ensure that the hosting site where we stored the library have this enabled, some do not bring it and this causes many errors. If we are running with WAMP or XAMP the web, it would not hurt to look for a tutorial on how to activate services and libraries for PHP in these local systems.

* A requirement before proceeding with the process is that the image should be resized before being uploaded to our server before.

We start by instantiating the class constructor, which receives as parameter the full path to the image hosted on our server (including extension):

$image = new Imagick('Imagename');

In the variable $image keep our Imagick object for treatment, after this, simply call the method cropThumbnailImage, whose parameters are width and height (in order):

$image->cropThumbnailImage(width[type int],high[type int]); //this function is used for croping image

OR

$image->resizeImage('500','691', imagick::FILTER_LANCZOS, 0.3); // this function is used for imageResize


As a last step we can only save the image you just cut, for it has the method Imagick writeImage whose expected parameter is the path where you want to save the image but the name of this. (please add the suffix _thumb the name of the image):

$image->writeImage( 'target_folder' );

This done, get our cropped image with PHP, without loss of quality, and without the result is a pixelated Thumbnail

For more information about this library, you can visit the PHP API: Image Magic PHP

Tuesday, September 18, 2012

Install MSSQL to wamp server [Resolved]


Install lower version of wamp server (Like 5.2.2)

After installing wamp server

Open php.ini file than activate below extension
from ;extension=php_mssql.dll to extension=php_mssql.dll


and than restart wamp server


now create one testmassql.php file in www directory
and
write blow code

<?php

    if (function_exists('mssql_connect'))
    {
        echo "Okay, fn is there";
    }
    else
    {
        echo "Hmmm .. fn is not even there";
    }

?>





Tuesday, August 14, 2012

Change PHP.ini settings for file upload


php_flag file_uploads on

php_value post_max_size "8M"

php_value upload_max_filesize "8M"

php_value max_input_time "60"

Wednesday, March 21, 2012

MySQL search and replace in whole database

<?php

function generate_queries($database, $user, $password, $host, $search, $replace) {

    $conn = mysql_connect($host, $user, $password);
    if (!$conn) {
        die('Unable to connect ' . mysql_error());
    }
  
    if (!mysql_select_db('INFORMATION_SCHEMA', $conn)) {
        die('Cannot use INFORMATION_SCHEMA');
    }
  
    $database_sql = mysql_real_escape_string($database, $conn);
    $query_tables = "select TABLE_NAME from TABLES where TABLE_SCHEMA = '$database_sql'";
    $tables_res = mysql_query($query_tables);
  
    $queries = '';
    $search_sql = mysql_real_escape_string($search, $conn);
    $replace_sql = mysql_real_escape_string($replace, $conn);
   echo '<pre>';
   
    while($tables_row = mysql_fetch_assoc($tables_res)) {
   
        $table_sql = mysql_real_escape_string($tables_row['TABLE_NAME'], $conn);
      
        $query_columns = "select COLUMN_NAME from COLUMNS where TABLE_SCHEMA = '$database_sql' and TABLE_NAME = '$table_sql' and DATA_TYPE in ('varchar', 'text', 'longtext')";
        $columns_res = mysql_query($query_columns);
        $columns = array();
        while ($column_row = mysql_fetch_assoc($columns_res)) {
            $columns[] = $column_row['COLUMN_NAME'];
        }
       
        if (!empty($columns)) {
            $queries .= "update `{$tables_row['TABLE_NAME']}` set ";
            foreach ($columns as $i => $column) {
                if ($i) {
                    $queries .= ", ";
                }
                $queries .= "`$column` = replace(`$column`, '$search_sql', '$replace_sql')";
            }
            $queries .= ";\n";
        }
    }
  
    return $queries;
}

echo $res = generate_queries('aus_sqt','root','','localhost','softqube','sqt');die();

?>