Use PHP To Check Whether Remote URL, Email Or Image Link Exist

In PHP, we have a built-in function file_exist that can help us to verify whether a particular file exist in our directory. However, do you ever have the need to check whether a particular URL, email or image link exist? We can use regular express to validate that the syntax of an email is correct but won't it be nice to reduce the amount of spam mail received? How about those images you have on your site? Won't you want to check whether there is a broken image or url link? Well, i have! Its always good to be informed in advance than meeting dissatisfy visitors. Anyway, in this article you will get to find and learn some of the more efficient and quicker ways to verify whether a particular link exist to use on your web application.

Check Remote Image Link Exist

There are many ways to check whether a particular image link exist after the introduce of PHP 5, GetImageSize. GetImageSize allows us to take in a remote link to retrieve the size of the image. Hence, we can do a simple check such as the one shown below,

$external_link = 'http://www.example.com/example.jpg';
if (@GetImageSize($external_link)) {
echo  "image exists ";
} else {
echo  "image does not exist ";
}

The above work well for any server that had GD installed. But there are more problem than just the one mention. This method is actually inefficient as it will download the entire image into your server before checking it. Thus, making the process very long. There might also be security risk as mention on Secure File Upload Check List that many image format allow comment to be embedded within the image and these comment might just be some PHP code that hacker has written. In short, this method download file from remote server to your server and take the risk of hacker using it to run malicious code after it has been downloaded on your server. BOMB! So if you are using the above method i advice you to change it and if you insist to use this, you can provide more validation checking for it. Just drop it.

So how do we check Image link in a more secure and quick environment? If you are using curl, you can try the following script:

function checkRemoteFile($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    // don't download content
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if(curl_exec($ch)!==FALSE)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Like i said, this will depend on curl. However, it is secure and quick! How about the rest of us? Lucky, PHP also provides another method called file_get_contents. file_get_contents returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE. With these in mind we can create a function to check that the file downloaded is valid by taking only 1 bytes of information from the file. Hence, whatever evil things exist on the file will only be able to run 1 byte and furthermore the function returns a string where code cannot be run. Thus, this will gives us a simple solution such as the one below,

function url_exists($url) {
if(@file_get_contents($url,0,NULL,0,1))
{return 1;}
else
{ return 0;}
}

The above one is more secure than the initial one that we have and it has no dependency. The speed for this method is also faster than the initial one. But is there a faster one than the curl version?

Check For Remote URL Link

There are many ways to check whether a remote url link exist. However, checking Remote URL required the page to return certain header code to indicate that the page is successfully loaded (200). Hence, you might not want to use the method for checking image link for url link. Furthermore, For different cases you might be interested with different solution. Assuming you are just checking whether an existing domain exist, you can use the following code

function url_exists($url){
    if(strstr($url,  "http:// ")) $url = str_replace( "http:// ",  " ", $url);
    $fp = @fsockopen($url, 80);
    if($fp === false) return false;
    return true;
}

which is written by adam at darkhousemedia dot com. The above method definitely run faster than fopen but for https and domain names but for path url such as 'http://example.com?p=231', the above won't work although the speed is definitely one of the fastest.

Nonetheless, there are still better alternative than the one presented. We can just tried to check the header with the following code:

function url_exists($url){
     if ((strpos($url,  "http ")) === false) $url =  "http:// " . $url;
     if (is_array(@get_headers($url)))
          return true;
     else
          return false;
}

The above work perfectly without the need to worry about complex code. However, the above method only work for HTTP and PHP 5 and above, other lower version of PHP will not. Therefore, we will need some modification on the above method to cater for lower PHP version.

function is_valid_url($url)
{
    $url = @parse_url($url);
    if (!$url)
    {
        return false;
    }
    $url = array_map('trim', $url);
    $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
    $path = (isset($url['path'])) ? $url['path'] : '';
    if ($path == '')
    {
        $path = '/';
    }
    $path .= (isset($url['query'])) ?  "?$url[query] " : '';
    if (isset($url['host']) AND $url['host'] != gethostbyname($url['host']))
    {
        if (PHP_VERSION  >= 5)
        {
            $headers = get_headers( "$url[scheme]://$url[host]:$url[port]$path ");
        }
        else
        {
            $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
            if (!$fp)
            {
                return false;
            }
            fputs($fp,  "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n ");
            $headers = fread($fp, 4096);
            fclose($fp);
        }
        $headers = (is_array($headers)) ? implode( "\n ", $headers) : $headers;
        return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
    }
    return false;
}

The code here is the more detail version of the previous one which is created by SecondV on forums Dot digitalpoint Dot com. The above code cater for lower PHP version while still using the same approach of getting the return header value. Furthermore, it also validate the URL by using the parse_url method. f_open can also be used to check remote URL link.

function image_exist($url) {
	if (@fclose(@fopen( $url,  "r "))) {
	 // true;
	} else {
	 // false;
	}
}

However, this method required allow_url_fopen to be enabled on your php.ini file or else it will fail. Furthermore, i will not prefer this method over the previous one as it seems more sense that the page return success due to header code to indicate a success.

Check Email Exist

We can't actually check whether a given email exist or not as it really depend on how the SMTP is being setup for each respective mail server. Nonetheless, we are still able to check whether a given domain exist to reduce the number of invalid ones. PHP has a function checkdnsrr which does the work nicely.

function email_exist($email) {
	list($userid, $domain) = split( "@ ", $email);
	if (checkdnsrr($domain,  "MX ")) { return true;} else { return false;}
}

Using the function above will help us to verify whether a particular domain exist to trick user that you have an email checker if they really intend to fake one. However, Windows doesn't support such function yet. Hence, we will need to create such function just for Windows server.

if(!function_exists('checkdnsrr'))
function checkdnsrr($hostName, $recType = '')
{
 if(!empty($hostName)) {
   if( $recType == '' ) $recType =  "MX ";
   exec( "nslookup -type=$recType $hostName ", $result);
   // check each line to find the one that starts with the host
   // name. If it exists then the function succeeded.
   foreach ($result as $line) {
     if(eregi( "^$hostName ",$line)) {
       return true;
     }
   }
   // otherwise there was no mail handler for the domain
   return false;
 }
 return false;
}

Once you have cater for both Linux and Windows server, you may want to create a full flag function to check on email such as the one shown below:

function check_email($email)
{
	$email_error = false;
	$Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
	if ($Email ==  " ") { email_error = true; }
	elseif (!eregi( "^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+ ", $Email)) { email_error = true; }
	else {
	list($Email, $domain) = split( "@ ", $Email, 2);
		if (! checkdnsrr($domain,  "MX ")) { email_error = true; }
		else {
		$array = array($Email, $domain);
		$Email = implode( "@ ", $array);
		}
	} 
	if (email_error) { return false; } else{return true;}
}

Now we know why we need to verify our email after we sign up for any particular services online! Since we cannot check whether a particular email exist, we will force to send out verification email to our user before they are able to access our portal. However, if you are interested to check through PHP forcefully, you may want to visit webdigi. They create a mail class to verify an email through checking the port of mail SMTP 25 but like i said previously it really depend on how each mail server is being design. This might not work. But we can still force user to verify their email through a simple script shown below,

function check_email($email)
{
	$email_error = false;
	$Email = htmlspecialchars(stripslashes(strip_tags(trim($email)))); //parse unnecessary characters to prevent exploits
	if ($Email ==  " ") { email_error = true; }
	elseif (!eregi( "^([a-zA-Z0-9._-])+@([a-zA-Z0-9._-])+\.([a-zA-Z0-9._-])([a-zA-Z0-9._-])+ ", $Email)) { email_error = true; }
	else {
	list($Email, $domain) = split( "@ ", $Email, 2);
		if (! checkdnsrr($domain,  "MX ")) { email_error = true; }
		else {
		$array = array($Email, $domain);
		$Email = implode( "@ ", $array);
		}
	} 
	if (email_error) { return false; } else{return true;}
}
function EmailValidation($email) {
    if (check_email($email)) {
    $domain = explode(  "@ ", $email );
        if ( @fsockopen ($domain[1],80,$errno,$errstr,3)) {
			$code =  "here we place a secret key  with the email address: $email ";
			mail($email,  "Your Verification Code ",  "Please click the following URL to verify your email:\n\n  ". $_SERVER['PHP_SELF']. "/?v=$code amp;email=$email ", "From: \ "example\ "  <[email protected] > ");
			echo  "Your account needs to be verify. We have send you an email, click the link provided and you are verified. ";
			return true;
		} else {
            return false; //if a connection cannot be established return false
        }
    } else {
        return false; //if email address is an invalid format return false
    }
} 
function EmailForm(){
    if(empty($_POST['email'])){
        echo  " <form action= ".$_SERVER['PHP_SELF']. " method='post' >
         <table border='0' >
         <tr >
         <td >Email </td >
         <td > <input name='email' type='text' id='email' / > </td >
         </tr >
         <tr >
         <td > amp;nbsp; </td >
         <td > <input type='submit' name='Submit' value='Validate' / > </td >
         </tr >
         </table >
         </form > ";
    } elseif(isset($_POST['email'])) { 
        if(EmailValidation($_POST['email'])) {
            echo  "An email has been sent to you. Please follow the instructions to activate your account. ";
        } else {
            echo  "Your email address appears to be invalid. Please try again. ";
        }
    }else elseif(isset($_GET['v'])  amp; amp; isset($_GET['email'])) {
		$clean['emai'] = $_GET['email']; //need to filter these data to be clean
		$clean['v'] = $_GET['v']; //need to filter these data to be clean
		$code =  "here we place a secret key  with the email address: $email ";
		$code = md5($code);
		if ($clean['v'] != $code) {
			echo  "The Verification Code is invalid. Please Try Again. ";
			exit(0);
		}else
		echo  "The email  ".$clean['emai']. " has been verified ";
	}else { 
        echo  "An error has occured, please contact the administrator. "; 
    }
} 
EmailForm();

Might be a bit confusing but i believe you will get the above code since its quite simple. Instead of breaking them into different pages, i sum them up on a single one.

Quick check whether link is broken

Here is another tips to check whether a link is broken.

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}

And the same version on a curl version

function url_exists($url) {
    if (!$fp = curl_init($url)) return false;
    return true;
}

credit goes to havran @ http://www.php.net/manual/en/function.file-exists.php#74469

Summary

The above solution can help many people to verify the content that the user has entered. Remember it is not safe to trust user input and such verification can come in handle. On the other hand, this can also help us to check broken and invalid links so that we get the information we need from our users. The information above might not be solid but it is good enough for me and hoping it will work for you.

Guarantee Make WordPress Flash Uploader Work

Hungred Dot Com has always had its flash uploader disabled due to many reason which i personally have no idea why. Many people said it was due to WordPress 2.7 update which caused the incompatibility of flash 10 with the flash uploader, swfupload. And here goes the big discussion on how to make WordPress flash uploader WORK. Of course, i was just a pass by reader and tried some mention methods by the public which still fail. The flash uploader that i have is shown below,

browser-uploader

After WordPress 2.8 was launched which was said that the flash uploader will be back kicking, but it doesn't! And slowly, it seems like my WordPress is getting bit and pieces of errors from firebug whenever I'm on WordPress. Furthermore, it gets really lag on Firefox when I'm on writing post. Very soon, some of the features failed such as the auto draft when you are adding post. But that doesn't bother me! Until i finished update my WordPress theme and fixed many stuff within this blog that i finally decided to solve my WordPress problem (back to topic, haha).

WordPress Flash Uploader Solutions

So i went to Google and perform a simple search which lead me to a lot of duplicate solution mention in the WordPress forum. Hence, i started my journey to resolve all these weird issues here and there in WordPress admin. Here are the solutions mention:

  • You'll have to go back to version 9 of Flash Player
    . Tried that, failed.
  • Check the permissions on the swfupload file. oh boy! moderator speaks up! but still not working.
  • Reuploading wp-includes and wp-admin fixed it. This must be it! still fail.
  • fix it by reuploading:
    /wp-includes/js/swfupload/
    And then clearing my browser cache.

    While everyone said 'it work!' in the forum, i still fail!
  • check swfupload.swf is in the folder of /wp-includes/js/swfupload/. YA! but it still not working!
  • issue was mod_security it was working previously! So i skipped this smartly 😀
  • I don't find that this works. The button is there, but clicking on it does absolutely nothing. It just sits there. God, you are lucky. Mine doesn't even exist.
  • The version of the swfupload in 2.6.5 did not work with Flash 10. 2.7 has the workaround for that. The moderator is back. Man he is one helpful guy! Updated to the latest version. But still fail.
  • Folks, make sure you're uploading the entire swfupload folder from WordPress 2.7, not just the swfupload.swf file.I uploaded the whole cow in and nothing happen!

That's it! Here are all the solution presented by the forum, other site are just copying each other work which still doesn't work for me. Hence, if you are like me then you should read on.

Guarantee Awake The Sleeping WordPress Flash Uploader

From here on, its a personal tried and error thing that will assure Hungred Dot Com safety at the same time guarantee that this flash uploader will work. Please backup both databases and your WordPress files before doing this. The situtation is that I had a few WordPress blog that i either setup for myself or for others after Hungred Dot Com. All other WordPress blog flash uploader work like charm but not this. Therefore, i can conclude something is wrong with this blog and not others (obvious).

According to the forum written above, it seems like everything is surrounding the folder of swfupload in /wp-includes/js/swfupload/. However, replacing it still doesn't work. May be its not that problem. Something else is being modified without me knowing. May be some plugin that i tired on Hungred Dot Com. Hence, i tried to remove the folder on /wp-includes/js/ which means every single JavaScript in WordPress is being removed, the admin site only of course. The removable really doesn't affect the main site. I upload the one in WordPress 2.8 that i downloaded from WordPress but it still doesn't work. The next try were to copy the whole folder /wp-includes/ and /wp-admin/ replacing the one stored on the server. This does takes a while but the site wasn't being affected. After the upload had complete, i tried the flash uploader but it still doesn't work. The folder /wp-content/ shouldn't had affected the admin page so i shouldn't touch that folder.

If my theory is correct, everything should have been replaced by the latest file that i have just uploaded. This means that i am actually performing a re-installation already. However, why is it still not working? My next though is that there exist a file that run in the previous version that wasn't replaced or removed by this sort of re-installation. Therefore, i decide to delete the folder /wp-includes/ and /wp-admin/ and replace with the latest one that i downloaded from WordPress. However, doing that will definitely killed my blog for a while since /wp-includes/ exist files that required for the site to function. My solution was to do it within the file manager provided by my host that allows me to directly interact with the server that is 100x faster than using FTP. Here is a screen shot of it.

file-manager

I upload the zip file through this file manager given by Hostgator and unzip into a folder. Deleting the folder of both /wp-includes/ and /wp-admin/ takes around 1 second and copying the new folder to Hungred Dot Com also takes around 1-2 second. This should be it! The fash uploader should work now! Unfortunately, it still doesn't work. DAMMIT!

However, i can assure that my WordPress is clean and definitely should have the flash uploader i set out for (the clean here refer to any files that might killed my flash uploader that wasn't being deleted previously). The next culprit will be the plugin i have used in WordPress! Some WordPress developers must have done something that caused all this problem! I went over to my WordPress plugin page and deactivate all my WordPress plugin immediately, went to upload a file, and..

flash-uploader

Damn! It was some plugin exist in my WordPress all along (may be not?)! So i hand picked those plugin that associate with WordPress add post page that could caused this. After i enabled most of it, i left the last one plugin that might just be the criminal that does all these. Guess what? None of them were. It seems like after i enabled and disabled all plugin, the flash uploader were enabled again. Other functionality such as auto save draft and stuff were also back online. Confused.

Conclusion

The above method will surely assure that your WordPress is clean again but it might caused you some problem. Depending on how desperate you are (HELL YEAH I WAS!), you might just tried some of the things above or just skipped more of it. Nonetheless, i am just trying to reinstall the whole WordPress and minimize the damage that will caused to the problem. In my case, nothing was missing and everything sail smoothly again. Hope this help! (man, this is one whole story. To the point damnit! *slap myself*)

WordPress Text Formatting Problem – Solved!

In Hungred Dot Com, we have been having problem with text formatting in WordPress for all our codes due to WordPress smart quotes functionality. Most of us who write code for the public usually uses those smart plugin such as 'SyntaxHighlighter Evolved' to present it nicely to our users. The problem with using external plugins such as this is that WordPress smart quotes doesn't see the tag for the plugin in this case,


,
as one of excluding formatting tag. Tag such as 'pre', 'code', 'kbd', 'style', 'script', 'tt' are excluded from smart quotes which you can personally view it on the source code of WordPress located at wp-includes/formatting.php. Hence, your WordPress codes article will not be showing '"' instead of the normal '"' symbol. However, there are ways to solve such problem and here we will present them to you to eliminate all these trouble once and for all!

Include Tag In WordPress Text Formatting Function

One way to solve this problem is to add the plugin tag into the core function wptexturize which locate at wp-includes/formatting.php. In that file you will notice the following function,

/**
 * Replaces common plain text characters into formatted entities
 *
 * As an example,
 * <code>
 * 'cause today's effort makes it worth tomorrow's "holiday"...
 * </code>
 * Becomes:
 * <code>
 * ’cause today’s effort makes it worth tomorrow’s “holiday”…
 * </code>
 * Code within certain html blocks are skipped.
 *
 * @since 0.71
 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
 *
 * @param string $text The text to be formatted
 * @return string The string replaced with html entities
 */
function wptexturize($text) {
	global $wp_cockneyreplace;
	$output = '';
	$curl = '';
	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	$stop = count($textarr);
	
	/* translators: opening curly quote */
	$opening_quote = _x('“', 'opening curly quote');
	/* translators: closing curly quote */
	$closing_quote = _x('”', 'closing curly quote');
	
	$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));
	$no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
	$no_texturize_tags_stack = array();
	$no_texturize_shortcodes_stack = array();

	// if a plugin has provided an autocorrect array, use it
	if ( isset($wp_cockneyreplace) ) {
		$cockney = array_keys($wp_cockneyreplace);
		$cockneyreplace = array_values($wp_cockneyreplace);
	} else {
		$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
		$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
	}

	$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
	$static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);

	$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
	$dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');

	for ( $i = 0; $i < $stop; $i++ ) {
		$curl = $textarr[$i];

		if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
				&& empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
			// static strings
			$curl = str_replace($static_characters, $static_replacements, $curl);
			// regular expressions
			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
		} else {
			wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
			wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
		}

		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
		$output .= $curl;
	}

	return $output;
}

You can add your tag into the function on this link,

$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt'));

for our example we will add [\php\]

$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt', ''));

Although this solved your problem but this solution also required you to edit the codes in the WordPress which will be replaced with every new release of WordPress.

Remove WordPress Text Formatting

The most efficient way is to remove the root of the problem! Unless you desperately want WordPress text formatting to be made available, you will want to remove this. Otto42 who is one of the moderator suggested a good way to eliminate such problem. We will add the following two code to remove the function wptexturize in WordPress which perform the formatting in our theme function.php file.

remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

This way all your text and code will be safe from formatting on that theme. You can also create a very small plugin that do this by placing the above three links to ANY WordPress plugin (may be you don't even have to create any plugin for this).

Replace WordPress Default Text Formatting

For those who want WordPress smart quote to be enabled but doesn't want it to format your codes, you can try to replace the function wptexturize. You can do this on your theme or any plugin available for you. Basically, you can remove the default function wptexturize through the following code,

remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

After that on the same page, you can copy the following code and add the action hook for your new wptexturize solution that cater to your personal need.

function my_wptexturize($text) {
	global $wp_cockneyreplace;
	$output = '';
	$curl = '';
	$textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
	$stop = count($textarr);
	
	/* translators: opening curly quote */
	$opening_quote = _x('“', 'opening curly quote');
	/* translators: closing curly quote */
	$closing_quote = _x('”', 'closing curly quote');
	
	$no_texturize_tags = apply_filters('no_texturize_tags', array('pre', 'code', 'kbd', 'style', 'script', 'tt', ''));
	$no_texturize_shortcodes = apply_filters('no_texturize_shortcodes', array('code'));
	$no_texturize_tags_stack = array();
	$no_texturize_shortcodes_stack = array();

	// if a plugin has provided an autocorrect array, use it
	if ( isset($wp_cockneyreplace) ) {
		$cockney = array_keys($wp_cockneyreplace);
		$cockneyreplace = array_values($wp_cockneyreplace);
	} else {
		$cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
		$cockneyreplace = array("’tain’t","’twere","’twas","’tis","’twill","’til","’bout","’nuff","’round","’cause");
	}

	$static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn–', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
	$static_replacements = array_merge(array('—', ' — ', '–', ' – ', 'xn--', '…', $opening_quote, '’s', $closing_quote, ' ™'), $cockneyreplace);

	$dynamic_characters = array('/\'(\d\d(?:’|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
	$dynamic_replacements = array('’$1','$1‘', '$1″', '$1′', '$1’$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '’$1', '$1×$2');

	for ( $i = 0; $i < $stop; $i++ ) {
		$curl = $textarr[$i];

		if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0}
				&& empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack)) { // If it's not a tag
			// static strings
			$curl = str_replace($static_characters, $static_replacements, $curl);
			// regular expressions
			$curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
		} else {
			wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
			wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
		}

		$curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&$1', $curl);
		$output .= $curl;
	}

	return $output;
}
remove_filter('comment_text', 'wptexturize');
remove_filter('the_excerpt', 'wptexturize');
remove_filter('the_content', 'wptexturize');
remove_filter('the_rss_content', 'wptexturize');

add_filter('comment_text', 'my_wptexturize');
add_filter('the_excerpt', 'my_wptexturize');
add_filter('the_content', 'my_wptexturize');
add_filter('the_rss_content', 'my_wptexturize');

This way you will solved your problem of code being wrongly formatted and at the meantime have the capability of smart quote. The only fall back of this method is that you might need to maintain this code in the future if WordPress ever update this function so that you will always have the latest version of smart quote.

Article Formatted Solution

If your post have many articles and you haven't had this problem solved at the beginning, your visitors will still be seeing formatted code in your article and might just drive your visitors away! Hence, you might want to consider reversing the function of wptexturize to return the format for you. You can do this by adding the reversed version of wptexturize and placed in on either a plugin or your theme.

We used hungred smart quotes to solve our issue on the above mention matters.

Summary

Smart quote in WordPress can be annoying and troublesome. Nonetheless, it also benefits those who truly wanted such function built within WordPress as it might just destroy your layout due to the unencoded tag by other writers. Hence, for those who are troubled by this, hopefully the solutions above help!

WordPress Plugin: Hungred Smart Quotes

Hungred Dot Com is a web development site. We have many code that was encoded automatically by WordPress for no good reason. Hence, it makes most of our code ugly and unreadable. This is very frustrating as i will have to go through each and every post in Hungred Dot Com to search for any problem on the post! Hence, i created this plugin that will replace WordPress smart quotes function with another function that can take in the tag of my WordPress syntax plugin. For those post that are currently suffering from code formatting, i have also implemented a decoding mechanism in this plugin to prevent special tag within the syntax plugin from being misunderstood as PHP start tag such as

<?php

will not be interpreted as code but plain text on the screen! I will display a screen shot of what it does at the end of this article.

Description

This is a small plugin that replace the smart quotes function in WordPress that format/encode the code in WordPress. Hence, most symbols will be formatted/encoded by WordPress texturize function.

Example,

'&' (ampersand) becomes '&amp'
'"' (double quote) becomes '&quot' 
''' (single quote) becomes ''' 
'< ' (less than) becomes '&lt'
'>' (greater than) becomes '&gt'

The plugin will help solve the above problem and produce the result below,

Example,

'&amp' (ampersand) becomes '&'
'&quot' (double quote) becomes '"' 
''' (single quote) becomes ''' 
'&lt' (less than) becomes '< '
'&gt' (greater than) becomes '>'

A control panel is also provided in this plugin to add in special tag for your code or disable smart quote in WordPress.
This problem is due to external code format plugin that required special tag such as


in syntaxhigher evolved.
Upon, activate, all existing article that was previously formatted will be decoded by this plugin while future article will be protected by the replaced texturize function for WordPress (so that the plugin tells WordPress texturize function to include your special tag from encode/format).

Hence, this plugin still provides you with the functionality of smart quote with the additional add on features to ease your life.

Screen shot of the plugin

Here are the control panel of Hungred Smart Quote. Simple and clear.

hungred-smart-quotes-setting

How to use this plugin

Do the following and you can ignore it for the rest of your life!

  1. Install it into your wordpress site
  2. Activate Hungred Smart Quotes
  3. On setting, go to the control panel of Hungred Smart Quotes and decide whether to allow wordpress smart quote and what are the tag you used for your code plugin. I used syntaxhighlighter evolved which required
    
    

    to prevent WordPress from formatting my code

  4. DONE!

That's it!

Plugin

You can search for this plugin on WordPress repository by typing 'hungred' as search criteria. If you want to manually install this, the link is here

Example

We are all visualize people. This is what the plugin can do if you just leave it alone and regardless if you enable or disabled WordPress smart quotes, the decoding mechanism will still run!

Before
hungred-smart-quote-before-one

After
hungred-smart-quote-after-one

Before
hungred-smart-quote-before-two

After
hungred-smart-quote-after-two