Pages

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

PHP SMTP Mail - [Resolved]

<?php

function authgMail($from, $namefrom, $to, $nameto, $subject, $message) {

$smtpServer = "smtpout.secureserver.net";   //ip address of the mail server.  This can also be the local domain name
$port = "25";                     // should be 25 by default, but needs to be whichever port the mail server will be using for smtp
$timeout = "45";                 // typical timeout. try 45 for slow servers
$username = "admin@dmin.com"; // the login for your smtp
$password = "password";            // the password for your smtp
$localhost = "localhost";       // Defined for the web server.  Since this is where we are gathering the details for the email
$newLine = "\r\n";             // aka, carrage return line feed. var just for newlines in MS
$secure = 0;                  // change to 1 if your server is running under SSL

$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 4096);
if(empty($smtpConnect)) {
   $output = "Failed to connect: $smtpResponse";
   echo $output;
   return $output;
}
else {
   $logArray['connection'] = "<p>Connected to: $smtpResponse";
   echo "<p />connection accepted<br>".$smtpResponse."<p />Continuing<p />";
}

//you have to say HELO again after TLS is started
fputs($smtpConnect, "HELO $localhost". $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['heloresponse2'] = "$smtpResponse";

//request for auth login
fputs($smtpConnect,"AUTH LOGIN" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authrequest'] = "$smtpResponse";

//send the username
fputs($smtpConnect, base64_encode($username) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authusername'] = "$smtpResponse";

//send the password
fputs($smtpConnect, base64_encode($password) . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['authpassword'] = "$smtpResponse";

//email from
fputs($smtpConnect, "MAIL FROM: <$from>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailfromresponse'] = "$smtpResponse";

//email to
fputs($smtpConnect, "RCPT TO: <$to>" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['mailtoresponse'] = "$smtpResponse";

//the email
fputs($smtpConnect, "DATA" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data1response'] = "$smtpResponse";

//construct headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;

//observe the . after the newline, it signals the end of message
fputs($smtpConnect, "To: $to\r\nFrom: $from\r\nSubject: $subject\r\n$headers\r\n\r\n$message\r\n.\r\n");
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['data2response'] = "$smtpResponse";

// say goodbye
fputs($smtpConnect,"QUIT" . $newLine);
$smtpResponse = fgets($smtpConnect, 4096);
$logArray['quitresponse'] = "$smtpResponse";
$logArray['quitcode'] = substr($smtpResponse,0,3);
fclose($smtpConnect);
//a return value of 221 in $retVal["quitcode"] is a success
return($logArray);
}

  $from="admin@admin.com";
  $namefrom="Internal Sales Dept. of mydomain.com";
  $to = "tomail@admin.com";
  $nameto = "internal_user";
  $subject = "Email from My Domain";
  $message = "Email from My Domain";
  // this is it, lets send that email!
  authgMail($from, $namefrom, $to, $nameto, $subject, $message);


?>

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 21, 2012

Find All Links on Web Page

$html = file_get_contents('http://www.TestDomain.com');

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

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

$list_urls = array();
for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);    
       $list_urls[] = $href->getAttribute('href');
       //echo $url.'<br />';
}
echo '<pre>';
print_r(array_unique($list_urls));
echo '<pre>';

Saturday, December 15, 2012

Increase media library upload file size limit


Add this code in htaccess:

php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200

You can increase the file upload limit according to your requirement.

 OR

Save this code in any php file and update it in the plugins directory and activate that plugin:

ini_set('upload_max_size','256M');
ini_set('post_max_size','256M');
ini_set('max_Execution_time','600');

OR

So here are the proper steps:

1) Use FTP to download a copy of your php.ini file
2) modify that file to have the following lines:
memory_limit = 100M
upload_max_filesize = 192M
post_max_size = 100M
file_uploads = On

Tuesday, December 11, 2012

MSVCR100.dll missing when wampserver install - [resolved]


For Windows 32 : Be sure that you have installed the Visual C++ 2010 SP1 Redistributable Package x86
: VC10 SP1 vcredist_x86.exe >>
http://www.microsoft.com/download/en/details.aspx?id=8328


For Windows 64 : Be sure that you have installed the Visual C++ 2010 SP1 Redistributable Package x64
: VC10 SP1 vcredist_x64.exe >>
http://www.microsoft.com/download/en/details.aspx?id=13523

Error HTTP 403 - forbidden in wampserver-[resolved]


Putting server online in contect menu did not help me. If you are using wampserver you will find the lines in your httpd.conf file

#   onlineoffline tag - don't remove
Require local
 
Change it to

#   onlineoffline tag - don't remove
Require all granted
 

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

Thursday, December 6, 2012

How to show a hierarchical terms list?

<ul>
    <?php $hiterms = get_terms("prod_cat", array("orderby" => "count", "parent" => 0, "hide_empty" => 0)); ?>
    <?php foreach($hiterms as $key => $hiterm) : ?>
        <li>
            <?php echo $hiterm->name; ?>
            <?php $loterms = get_terms("prod_cat", array("orderby" => "slug", "parent" => $hiterm->term_id, "hide_empty" => 0)); ?>
            <?php if($loterms) : ?>
                <ul>
                    <?php foreach($loterms as $key => $loterm) : ?>
                        <li> - <?php echo $loterm->name; ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </li>
    <?php endforeach; ?>
</ul>

Thursday, November 29, 2012

How to get thumbnail of YouTube video link using YouTube Video ID?

Each YouTube video has 4 generated images. They are predictably formatted as follows:

http://img.youtube.com/vi/<insert-youtube-video-id>/0.jpg
http://img.youtube.com/vi/<insert-youtube-video-id>/1.jpg
http://img.youtube.com/vi/<insert-youtube-video-id>/2.jpg
http://img.youtube.com/vi/<insert-youtube-video-id>/3.jpg

The first one in the list is a full size image and others are thumbnail images. The default thumbnail image (ie. one of 1.jpg, 2.jpg, 3.jpg) is:

http://img.youtube.com/vi/<insert-youtube-video-id>/default.jpg

For the high quality version of the thumbnail use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id>/hqdefault.jpg

There is also a medium quality version of the thumbnail, using a url similar to the HQ:

http://img.youtube.com/vi/<insert-youtube-video-id>/mqdefault.jpg

For the maximum resolution version of the thumbnail use a url similar to this:

http://img.youtube.com/vi/<insert-youtube-video-id>/maxresdefault.jpg

Saturday, November 3, 2012

How to fix z-index in YouTube videos

Add a parameter to force YouTube iframe to set a low z-index.

If you have any element you’ll like to show above a YouTube iframe you just have to add a parameter to the iFrame URL.

wmode=transparent

Add the wmode parameter in the src URL.

<iframe class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/asfdsafsdfWSDF?wmode=transparent" frameborder="0"></iframe>

If you have YouTube videos that appear infront of your other website content and giving it a lower z-index does not seem to do the trick then try adding the wmode parameter to the embedded movie.


<object width='425' height='344'> 
    <param name='movie' value='http://www.youtube.com/v/Wj_JNwNbETA&hl=en&fs=1'> 
    <param name='type' value='application/x-shockwave-flash'> 
    <param name='allowfullscreen' value='true'> 
    <param name='allowscriptaccess' value='always'> 
    <param name="wmode" value="transparent" />
    <embed width='425' height='344'
            src='http://www.youtube.com/v/Wj_JNwNbETA&hl=en&fs=1'
            type='application/x-shockwave-flash'
            allowfullscreen='true'
            allowscriptaccess='always'
            wmode="opaque"
    ></embed> 
    </object>



Thursday, October 11, 2012

Wordpress Create Plugin with sortcode

/*Sortcode Display*/
    function Test_Plugin_name($content) {
        if (strpos($content, '[JayMap]') !== FALSE) {
            $qaform = "jaydeep";
            /*
                if you want to replace it with html entites than use below code
                $content = preg_replace('/<p>\s*<!–(.*)–>\s*<\/p>/i', "<!–$1–>", $content);
            */
            $content = str_replace('[JayMap]', $qaform, $content);
        }
        return $content;
    }
    add_filter('the_content', 'Test_Plugin_name');
    add_filter('widget_text', 'Test_Plugin_name');
    /*Sortcode Display*/

Saturday, October 6, 2012

Create Extra Menu in wordpress


Please write below code in "function.php"

// create custom plugin settings menu
add_action('admin_menu', 'social_create_menu');
function social_create_menu() {
    add_menu_page('Theme Settings', 'Theme Settings', 'administrator', __FILE__, 'social_settings_page','../images/social_windows_button.png');
    add_action( 'admin_init', 'register_mysettings' );
}
function register_mysettings() {
    register_setting( 'social-settings-group', 'facebook_link' );
}
function social_settings_page() {    ?>
<div class="wrap"><br>
<fieldset style="border: 1px solid #cccccc; padding: 10px; margin: 10px 0;">
<legend style="font-size:18px;">Social Links</legend>
<form method="post" action="options.php">
    <?php settings_fields( 'social-settings-group' ); ?>
    <table class="form-table">
        <tr valign="top"><td style="width:125px;"><img src="../images/social_facebook.png" style="vertical-align: middle;" title="Facebook" alt="Facebook">&nbsp;Facebook</td><td><input type="text" name="facebook_link" value="<?php echo get_option('facebook_link'); ?>" style="width:300px;"></td></tr>          
    </table>
</fieldset>
 <p class="submit">
    <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
    </p>
</form>
</div>
<?php }

/* Create admin menu Ends */

Wednesday, September 19, 2012

Get first video or Image from post [resolved]

<?php

function show_thumb() {
    global $post, $posts;
    $thumb = '';
    ob_start();
    ob_end_clean();
    // filter video
    $output = preg_match_all('/(\<object.*\<\/object\>)/is', $post->post_content, $matches);
    if($output == ''){    $output = preg_match_all('/(\<iframe.*\<\/iframe\>)/is', $post->post_content, $matches);    }
    if($matches[1][0] != '')    {    $thumb = '<div style="float:left; margin-right:10px;border: 1px solid #cccccc; padding: 2px;">'.$matches[1][0].'</div>';} else { $thumb = ''; }
    if(empty($thumb)) { // no video tags found, filter wordtube tag instead
        $output = preg_match_all('/\[media id=(.*?)]/i', $post->post_content, $matches);
        $thumb = $matches[1][0];
        if (empty($thumb)) { // no wordtube tags, search for images instead
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
            $thumb = $matches[1][0];
            if(empty($thumb)) { // no images found, use a default image
                $postlist_id = $post->ID;
                    $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $postlist_id ), "medium");
                    $myimage = $imgsrc[0];
                    if($myimage != '')
                    {
                        $thumb = '<div style="float:left; margin-right:10px;"><img src="'.$myimage.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" style="width:150px; border: 1px solid #cccccc; padding: 2px;"/></div>';
                    }
            } else {  // image found, return image
                $thumb = '<div style="float:left; margin-right:10px;"><img src="'.$thumb.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" style="width:150px; border: 1px solid #cccccc; padding: 2px;"/></div>';
            }
        }else { //  wordTube tag found, execute shortcode
            $thumb = '[media id=' . $thumb . ']';
            $thumb = apply_filters('the_content', $thumb );
        }
    }
    return $thumb;
}

?>
<?php    echo $myimage_name = show_thumb();    ?>


Wordpress create new Post type [resolved]

<?php


function codex_custom_init() {
  $labels = array(
    'name' => _x('Specials', 'post type general name'),
    'singular_name' => _x('Special', 'post type singular name'),
    'add_new' => _x('Add New', 'special'),
    'add_new_item' => __('Add New Special'),
    'edit_item' => __('Edit Special'),
    'new_item' => __('New Special'),
    'all_items' => __('All Specials'),
    'view_item' => __('View Special'),
    'search_items' => __('Search Specials'),
    'not_found' =>  __('No specials found'),
    'not_found_in_trash' => __('No specials found in Trash'),
    'parent_item_colon' => '',
    'menu_name' => __('Specials')

  );
  $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'page',
    'has_archive' => true,
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments','page-attributes' )
  );
  register_post_type('special',$args);
}
add_action( 'init', 'codex_custom_init' );

?>

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, September 4, 2012

Add New Options To Wordpress General Settings


add_filter('admin_init', 'general_settings_register_fields');

function general_settings_register_fields()
{
    register_setting('general', 'test_field', 'esc_attr');
    add_settings_field('test_field', '<label for="test_field">'.__('Test Field' , 'test_field' ).'</label>' , 'general_settings_fields_html', 'general');
}

function general_settings_fields_html()
{
    $value = get_option( 'test_field', '' );
    echo '<input type="text" id="test_field" name="test_field" value="' . $value . '" />';
}

Get the first image or video from a post - [resolved]


The function returns an image/video and must be called inside the loop.

function show_thumb() {
    global $post, $posts;
    $thumb = '';
    ob_start();
    ob_end_clean();
    // filter video
    $output = preg_match_all('/(\<object.*\<\/object\>)/is', $post->post_content, $matches);
    if($output == ''){    $output = preg_match_all('/(\<iframe.*\<\/iframe\>)/is', $post->post_content, $matches);    }
    if($matches[1][0] != '')    {    $thumb = $matches[1][0];} else { $thumb = ''; }
    if(empty($thumb)) { // no video tags found, filter wordtube tag instead
        $output = preg_match_all('/\[media id=(.*?)]/i', $post->post_content, $matches);
        $thumb = $matches[1][0];
        if (empty($thumb)) { // no wordtube tags, search for images instead
            $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
            $thumb = $matches[1][0];
            if(empty($thumb)) { // no images found, use a default image
                $postlist_id = $post->ID;
                    $imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $postlist_id ), "medium");
                    $myimage = $imgsrc[0];
                    if($myimage != '')
                    {
                        $thumb = '<img src="'.$myimage.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" style="width:150px; border: 1px solid #cccccc; padding: 2px;"/>';
                    }
            } else {  // image found, return image
                $thumb = '<img src="'.$thumb.'" alt="'.$post->post_title.'" title="'.$post->post_title.'" style="width:150px; border: 1px solid #cccccc; padding: 2px;"/>';
            }
        }else { //  wordTube tag found, execute shortcode
            $thumb = '[media id=' . $thumb . ']';
            $thumb = apply_filters('the_content', $thumb );
        }
    }
    return $thumb;
}

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, July 25, 2012

Detecting Mobile Browser PHP

<?php

$agent = $_SERVER['HTTP_USER_AGENT'];

if(preg_match('/iPhone|Android|Blackberry/i', $agent)){
    header("Location: mobile.html");
    exit;
}

?>


<?php

$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))

//Redirect URL
header('Location: mobile.html');

?>

Tuesday, July 24, 2012

Creating RSS feed from XML sitemap

Please open below url

Link http://pipes.yahoo.com/rarst/sitemap2rss

than

Go to pipe > type in site URL > Run Pipe > get preview of RSS > More Options > Get as RSS

 Put you sitemap link into text box than click on Run Pipe

Redirect using web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Imported Rule 1" stopProcessing="true">
                    <match url="^(.*)$" ignoreCase="false" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^DomainName\.com$" />
                    </conditions>
                    <action type="Redirect" redirectType="Permanent" url="http://www.DomainName.com/{R:1}" />
                </rule>
                <rule name="CanonicalHostNameRule1" stopProcessing="true">
                    <match url="index\.asp(?:l)?" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="DomainName\.com$" />
                    </conditions>
                    <action type="Redirect" url="http://www.DomainName.com/" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

Monday, June 4, 2012

Listing Multiple Twitter Accounts On Website

<style>
.tweet_feed{color:#333; font-family: sans-serif; margin-top:15px;}
.tweet_feed p{margin: 0;}
.tweettitle{font-size:12px;}
.tweettitle a{color:#992626; font-size:12px;}
.tweet_feed a{color:#992626; font-size:10px;}
</style>       
           
<?php

// Pull from which accounts? Separated by a space, for example: Username Username Username
$usernames = "Username1 Username2 Username3";
// Number of tweets to pull in, total.
$limit = "4";
// Show username? 0 = No, 1 = Yes.
$show = 1;

// REMEBER: When using HTML, escape double-quotations like this: \"

// This comes before the entire block of tweets.
$prefix = "";
// This comes before each tweet on the feed.
$prefix_sub = "";
// This comes after the username but before the tweet content.
$wedge = "";
// This comes after each tweet on the feed.
$suffix_sub = "";
// This comes after the entire block of tweets.
$suffix = "";

// It is recommended that you do not modify below this point without PHP knowledge.

function parse_feed($usernames, $limit, $show, $prefix_sub, $wedge, $suffix_sub) {

$usernames = str_replace(" ", "+OR+from%3A", $usernames);
$feed = "http://search.twitter.com/search.atom?q=from%3A" . $usernames . "&rpp=" . $limit;
$feed = file_get_contents($feed);
$x = new SimpleXmlElement($feed);

    for($i=0;$i<$limit;$i++)
    {
        $autor_name = $x->entry[$i]->author->name;
        $autor_name = explode(" (",$autor_name);
        $autor_name = $autor_name[0];
        $autor_uri = $x->entry[$i]->author->uri;
       
        $title = $x->entry[$i]->title;
        $updated = date("Y-m-d",strtotime($x->entry[$i]->updated));
       
        $now = strtotime(date("Y-m-d")); // or your date as well
        $your_date = strtotime($updated);
        $datediff = $now - $your_date;
        $days_count = floor($datediff/(60*60*24));

        if($days_count > 0)
        {
            $days_count = 'a';
        }
        else
        {
            $days_count = $days_count;
        }
       
        $tweet_url = $x->entry[$i]->link[0]['href'];
        $tweet_id = $x->entry[$i]->id;
        $tweet_id = explode(":",$tweet_id);
        $tweet_id = end($tweet_id);
       
        echo '<div class="tweet_feed">
    <p class="tweettitle"><a href="'.$autor_uri.'" target="_blank">'.$autor_name.'</a>&nbsp;&nbsp;'.$x->entry[$i]->title.'</p>
    <p class="otherinfo"><a href="'.$tweet_url.'" target="_blank">'.$days_count.' days ago</a> - <a href="https://twitter.com/intent/tweet?in_reply_to='.$tweet_id.'" target="_blank">reply</a> - <a href="https://twitter.com/intent/retweet?tweet_id='.$tweet_id.'" target="_blank">retweet</a> - <a href="https://twitter.com/intent/favorite?tweet_id='.$tweet_id.'" target="_blank">favourite</a></p>
</div>';
    }

}

echo '<div style="background: url(twitterbox.png) no-repeat scroll 0 0 transparent;height: 352px;margin-top: 0;padding-left: 5px;padding-right: 5px;padding-top: 65px;width: 210px;">';
parse_feed($usernames, $limit, $show, $prefix_sub, $wedge, $suffix_sub);
echo '</div>';

?>

Saturday, June 2, 2012

[resolved] Fatal error: Allowed memory size of 33554432 bytes exhausted

1. Try adding this line to your wp-config.php file:
define('WP_MEMORY_LIMIT', '64M');

2. If you have access to your PHP.ini file, change the line in PHP.ini
If your line shows 32M try 64M:
memory_limit = 64M ; Maximum amount of memory a script may consume (64MB)

3. If you don't have access to PHP.ini try adding this to an .htaccess file:
php_value memory_limit 64M

4. Talk to your host.

Tuesday, May 22, 2012

Add new page at adminpanel in zencart 1.5.0

   
1. If want to add new parent menu than insert manually menu in "admin_menus" table
   
2. create new file into admin folder "YourPageName.php"

3. Create new file into "adminpanel/includes/extra_datafiles" with below code:
   
    if (!defined('IS_ADMIN_FLAG')) {
        die('Illegal Access');
    }
    /**
     * Database name defines
     *
     */
    define('TABLE_YOUR_TABLE_NAME', DB_PREFIX . 'table_name'); /* If you want to create new table */
    define('FILENAME_YOUR_PAGE_NAME', 'YourPageName');

    define('BOX_CATALOG_ADDITIONAL_IMAGES', 'Your Page Name'); /* Its for navigation menu. Using BOX_CATALOG_YOUR_PAGE_NAME you can add this menu below "Catalog" section . Or you can choose different bos from "admin_menus" table */
   
4. Create new file at "adminpanel/includes/languages/english" and its name like "YourPageName.php"

5. Now register admin page from "Admin Page Registration" under "admin access management menu"
    Here, you can set your page.

Thursday, May 10, 2012

Status Code Definitions

400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfied
417 Expectation Failed
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

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

?>

Tuesday, March 13, 2012

Redirect Using .htaccess

RewriteEngine On

rewritecond %{http_host} ^mydomain.com [nc]
rewriterule ^(.*)$ http://www.mydomain.com/$1 [r=301,nc]


RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\ HTTP/
RewriteRule ^index\.php$ http://www.mydomain.com/ [R=301,L]


ErrorDocument 404 http://www.mydomain.com/404.htm

Monday, March 12, 2012

Mysql Date Format Using MySQL DATE_FORMAT()

MySQL DATE_FORMAT() Example

copyDATE_FORMAT(NOW(),'%W, %M %e, %Y %h:%i %p')
#yields 'Sunday, March 12, 2012 10:35 AM'

MySQL DATE_FORMAT() Representations

Specifier    Description
%a            Abbreviated weekday name (Sun..Sat)
%b            Abbreviated month name (Jan..Dec)
%c            Month, numeric (0..12)
%D            Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%d            Day of the month, numeric (00..31)
%e            Day of the month, numeric (0..31)
%f            Microseconds (000000..999999)
%H            Hour (00..23)
%h            Hour (01..12)
%I            Hour (01..12)
%i            Minutes, numeric (00..59)
%j            Day of year (001..366)
%k            Hour (0..23)
%l            Hour (1..12)
%M            Month name (January..December)
%m            Month, numeric (00..12)
%p            AM or PM
%r            Time, 12-hour (hh:mm:ss followed by AM or PM)
%S            Seconds (00..59)
%s            Seconds (00..59)
%T            Time, 24-hour (hh:mm:ss)
%U            Week (00..53), where Sunday is the first day of the week
%u            Week (00..53), where Monday is the first day of the week
%V            Week (01..53), where Sunday is the first day of the week; used with %X
%v            Week (01..53), where Monday is the first day of the week; used with %x
%W            Weekday name (Sunday..Saturday)
%w            Day of the week (0=Sunday..6=Saturday)
%X            Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x            Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y            Year, numeric, four digits
%y            Year, numeric (two digits)
%%            A literal “%” character
%x            x, for any “x” not listed above


$sql = " select * from TABLE_NAME where DATE_FORMAT(date_registered,'%W') = 'Monday' and date_registered BETWEEN '2011-12-15 06:21:53' AND '2011-12-21 06:21:53' ";
    $res = mysql_query($sql);
    while($row = mysql_fetch_array($res))
    {
        echo $row['DATE_FORMAT(date_registered,\'%W\')'];
    }