<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Webmaster-Source &#187; PHP</title>
	<atom:link href="https://www.webmaster-source.com/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.webmaster-source.com</link>
	<description>Useful Resources For Webmasters</description>
	<lastBuildDate>Thu, 24 Aug 2017 02:01:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.42</generator>
	<item>
		<title>Method Chaining in PHP</title>
		<link>https://www.webmaster-source.com/2013/03/13/method-chaining-in-php/</link>
		<comments>https://www.webmaster-source.com/2013/03/13/method-chaining-in-php/#comments</comments>
		<pubDate>Wed, 13 Mar 2013 10:40:50 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=5027</guid>
		<description><![CDATA[Have you ever come across a PHP class that connects methods together in a single line to achieve some goal? (If you haven&#8217;t, Guzzle and SwiftMail are a couple of examples.) jQuery also operates in a similar manner, using the same principle. The technique is called method chaining, and is quite useful in cases where [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Have you ever come across a PHP class that connects methods together in a single line to achieve some goal? (If you haven&#8217;t, <a href="http://guzzlephp.org/">Guzzle</a> and <a href="http://swiftmailer.org/docs/messages.html">SwiftMail</a> are a couple of examples.)</p>
<pre class="brush: php; title: ; notranslate">
//Example from http://guzzlephp.org/
$client = new Client($url);
$request = $client-&gt;get('/user')-&gt;setAuth('user', 'pass');
$response = $request-&gt;send();
</pre>
<p>jQuery also operates in a similar manner, using the same principle. The technique is called <em>method chaining</em>, and is quite useful in cases where a class has many public methods that could be called upon with each others&#8217; output.</p>
<p>If you wanted, the above example could conceivably be rewritten like this:</p>
<pre class="brush: php; title: ; notranslate">
$client = new Client($url);
$path = $client-&gt;get('/user');
$request = $path-&gt;setAuth('user', 'pass');
$response = $request-&gt;send();
</pre>
<p>This works because of the way chainable methods are set up. The secret to making it work is that <strong>every method must return the entire object.</strong> What you&#8217;re doing when you chain Method A with Method B (<code>$object->methodA()->methodB</code>) is calling Method B from the object returned by Method A, which it returned from the object that called it to begin with.</p>
<p>Here&#8217;s an example class that permits chaining, since there&#8217;s no way that code could be more syntactically awkward than that sentence:</p>
<pre class="brush: php; title: ; notranslate">
class MyClass {

	function __construct() {
		$this-&gt;thing = &quot;a&quot;;
	}

	function addB() {
		$this-&gt;thing .= &quot;b&quot;;
		return $this;
	}

	function addC() {
		$this-&gt;thing .= &quot;c&quot;;
		return $this;
	}

	function __tostring() {
		return $this-&gt;thing;
	}

}

$obj = new MyClass();
echo $obj-&gt;addB()-&gt;addC(); //outputs &quot;abc&quot;
echo $obj-&gt;addB(); //outputs &quot;ab&quot;
echo $obj-&gt;addC(); //outputs &quot;ac&quot;
echo $obj; //outputs &quot;a&quot;
</pre>
<p>When you initialize the object, the constructor sets the <code>thing</code> property to be <code>a</code>. Each one of the methods returns <code>$this</code>, which of course is the entire object. So if you call <code>addB()</code>, it adds <code>b</code> to the string and then returns <code>$this</code>. So you can chain the <code>addC()</code> method, which is basically calling it on the <code>$this</code> that <code>addB()</code> returned.</p>
<p>I hope this helps you understand method chaining. It took me a little while to figure it out, and explaining it clearly is about as easy as reading this probably is. <img src="https://www.webmaster-source.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" /></p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2013/03/13/method-chaining-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Generating a Software License Key String with PHP</title>
		<link>https://www.webmaster-source.com/2013/02/13/generating-a-software-license-key-string-with-php/</link>
		<comments>https://www.webmaster-source.com/2013/02/13/generating-a-software-license-key-string-with-php/#comments</comments>
		<pubDate>Wed, 13 Feb 2013 11:20:38 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4998</guid>
		<description><![CDATA[I was working on a project recently that required unique API keys to be generated for clients connecting to the server. For various reasons, I settled on the style of license key you commonly see for software packages. You know, the kind you always had to read off the back of a CD case and [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I was working on a project recently that required unique API keys to be generated for clients connecting to the server. For various reasons, I settled on the style of license key you commonly see for software packages. You know, the kind you always had to read off the back of a CD case and type in when installing the application. Like <code>H8OV7-HNTB5-JLLOH-W8FG2</code>.</p>
<p>It&#8217;s fairly easy to write such a function. The basic idea is to loop around four times—once for each segment—and have a nested loop that runs five times, picking a random character each time. Here&#8217;s what I came up with:</p>
<pre class="brush: php; title: ; notranslate">
function generate_key_string() {

	$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$segment_chars = 5;
	$num_segments = 4;
	$key_string = '';

	for ($i = 0; $i &lt; $num_segments; $i++) {

		$segment = '';

		for ($j = 0; $j &lt; $segment_chars; $j++) {
    			$segment .= $tokens[rand(0, 35)];
		}

		$key_string .= $segment;

		if ($i &lt; ($num_segments - 1)) {
    			$key_string .= '-';
		}

	}

	return $key_string;

}
</pre>
<p>The <code>$tokens</code> string contains the characters that are valid in the key, so the loop can pick from it. The <code>$segment_chars</code> and <code>$num_segments</code> variables are the number of characters in a segment and the number of segments in the key, respectively. <code>$key_string</code> is an empty string that the loop will add the characters into.</p>
<p>The first for loop runs four times, assuming the desired result is four segments in the key. The inner loop picks a character out of <code>$tokens</code> at random each time it goes around. (PHP strings are also arrays, with the each character having its own numerical offset.) The characters are tacked onto the <code>$segment</code> string.</p>
<p>Then the segment is joined with the <code>$key_string</code>, and a dash character is applied if the loop isn&#8217;t on the final segment yet. End result: something like <code>H8OV7-HNTB5-JLLOH-W8FG2</code>.</p>
<p>Now how can you make sure the key is unique when it&#8217;s generated?</p>
<pre class="brush: php; title: ; notranslate">
do {
	$key_string = generate_key_string();
	$result = $db-&gt;query(&quot;SELECT license_key FROM my_license_key_table WHERE license_key = '$key_string'&quot;);
	//$db is a PDO object. If you're not familiar with PDO, check out http://www.webmaster-source.com/2011/08/05/getting-your-feet-wet-with-pdo-and-migrating-old-mysql-code/
} while ($result != false);
</pre>
<p>You generate a new key string with the function, check to see if it exists in your database, and lather/rinse/repeat until that is no longer the case. Usually you won&#8217;t have collisions too often, so it will only need to run once. I&#8217;m too lazy to figure out the probability, but considering there are 52,521,875 possible combinations for <em>one</em> 5-character segment&#8230;you&#8217;re probably not going to run into performance issues anytime soon. And if you do, just add another segment onto your key strings.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2013/02/13/generating-a-software-license-key-string-with-php/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Using the WordPress 3.5 Media Uploader in Your Plugin or Theme</title>
		<link>https://www.webmaster-source.com/2013/02/06/using-the-wordpress-3-5-media-uploader-in-your-plugin-or-theme/</link>
		<comments>https://www.webmaster-source.com/2013/02/06/using-the-wordpress-3-5-media-uploader-in-your-plugin-or-theme/#comments</comments>
		<pubDate>Wed, 06 Feb 2013 11:21:50 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Themes]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=5001</guid>
		<description><![CDATA[Back in 2010, I wrote a post on Using the WordPress Uploader in Your Plugin or Theme that went on to be one of my most popular tutorials of all time. Then the WordPress team went and added a much cooler media uploader in version 3.5 and make that post outdated. Since most of you [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Back in 2010, I wrote a post on <a href="http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/">Using the WordPress Uploader in Your Plugin or Theme</a> that went on to be one of my most popular tutorials of all time. Then the WordPress team went and added a much cooler media uploader in version 3.5 and make that post outdated. Since most of you probably want to add the <em>new</em> uploader in a theme or plugin you&#8217;re working on right now, I figured it was time for an updated post.</p>
<p style="text-align: center"><img style=' display: block; margin-right: auto; margin-left: auto;'  class="aligncenter size-full wp-image-5002 imgborder" alt="WordPress 3.5 Media Uploader" src="//www.webmaster-source.com/wp-content/uploads/2013/02/wp35mediauploader.png" width="600" height="286" /></p>
<p>The process required to add the new uploader is a bit different, but not too much more difficult. I was able to adapt the old tutorial a little, so it shouldn&#8217;t be too hard to replace some code in an existing project and get the new uploader instead of the old.<span id="more-5001"></span></p>
<p>For the sake of simplicity, let&#8217;s start with the same HTML snippet as in the old tutorial. This goes along with the rest of the HTML for your admin page, or wherever in the admin you&#8217;re trying to add an upload field.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;label for=&quot;upload_image&quot;&gt;
	&lt;input id=&quot;upload_image&quot; type=&quot;text&quot; size=&quot;36&quot; name=&quot;ad_image&quot; value=&quot;http://&quot; /&gt; 
	&lt;input id=&quot;upload_image_button&quot; class=&quot;button&quot; type=&quot;button&quot; value=&quot;Upload Image&quot; /&gt;
	&lt;br /&gt;Enter a URL or upload an image
&lt;/label&gt;
</pre>
<p>Now we need to load up the necessary JavaScript files.</p>
<pre class="brush: php; title: ; notranslate">
add_action('admin_enqueue_scripts', 'my_admin_scripts');

function my_admin_scripts() {
	if (isset($_GET['page']) &amp;&amp; $_GET['page'] == 'my_plugin_page') {
		wp_enqueue_media();
		wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery'));
		wp_enqueue_script('my-admin-js');
	}
}
</pre>
<p>We bind the <code>my_admin_scripts()</code> function to the <code>admin_enqueue_scripts</code> hook, and enqueue both the media scripts and our own JavaScript file. Also, the scripts will only be loaded if the current page is equal to &#8220;my_plugin_page,&#8221; which you would of course replace with the slug your <a href="http://codex.wordpress.org/Administration_Menus">admin menu</a> has.</p>
<p>Now for the complicated part: the script that hooks into the uploader. Continuing with the above example, it would be named <code>my-admin.js</code>.</p>
<pre class="brush: jscript; title: ; notranslate">
jQuery(document).ready(function($){


	var custom_uploader;


	$('#upload_image_button').click(function(e) {

		e.preventDefault();

		//If the uploader object has already been created, reopen the dialog
		if (custom_uploader) {
			custom_uploader.open();
			return;
		}

		//Extend the wp.media object
		custom_uploader = wp.media.frames.file_frame = wp.media({
			title: 'Choose Image',
			button: {
				text: 'Choose Image'
			},
			multiple: false
		});

		//When a file is selected, grab the URL and set it as the text field's value
		custom_uploader.on('select', function() {
			attachment = custom_uploader.state().get('selection').first().toJSON();
			$('#upload_image').val(attachment.url);
		});

		//Open the uploader dialog
		custom_uploader.open();

	});


});
</pre>
<p>When the button is clicked, it creates a new instance of the <code>wp.media</code> object and configures it to only accept a single file, since the text field can only hold one file URL. Then it binds a function to the selection action, which gets the file attributes when an image is chosen and sets the <code>#upload_image</code> text field value to the file&#8217;s URL.</p>
<p>Providing everything went as expected, you should have a form field that will accept an arbitrary URL, or allow the user to upload one.</p>
<p><img style=' display: block; margin-right: auto; margin-left: auto;'  src="//www.webmaster-source.com/wp-content/uploads/2013/02/wp35mediauploader-field.png" alt="File Upload Field" width="352" height="44" class="aligncenter size-full wp-image-5005" /></p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2013/02/06/using-the-wordpress-3-5-media-uploader-in-your-plugin-or-theme/feed/</wfw:commentRss>
		<slash:comments>70</slash:comments>
		</item>
		<item>
		<title>PHP: The Right Way</title>
		<link>https://www.webmaster-source.com/2013/01/23/php-the-right-way/</link>
		<comments>https://www.webmaster-source.com/2013/01/23/php-the-right-way/#comments</comments>
		<pubDate>Wed, 23 Jan 2013 11:42:30 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4980</guid>
		<description><![CDATA[There’s a lot of outdated information on the Web that leads new PHP users astray, propagating bad practices and bad code. This must stop. PHP: The Right Way is an easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative tutorials around the Web. PHP: The Right Way is a useful [&#8230;]]]></description>
				<content:encoded><![CDATA[<blockquote><p>There’s a lot of outdated information on the Web that leads new PHP users astray, propagating bad practices and bad code. This must stop. <a href="http://www.phptherightway.com/"><em>PHP: The Right Way</em></a> is an easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative tutorials around the Web.</p></blockquote>
<p><a href="http://www.phptherightway.com/"><em>PHP: The Right Way</em></a> is a useful guide to how to write PHP that won&#8217;t make other developers cringe in horror. It starts off with some tips on how to manage your development environment and then gets to the good part: what not to do. Advice is featured on matters such as database access, password hashing, and other security issues.</p>
<p>The site is an excellent central resource that gives a good overview of things that every beginning PHP developer should be aware of.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2013/01/23/php-the-right-way/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Manipulating Color Data with phpColors</title>
		<link>https://www.webmaster-source.com/2013/01/02/manipulating-color-data-with-phpcolors/</link>
		<comments>https://www.webmaster-source.com/2013/01/02/manipulating-color-data-with-phpcolors/#comments</comments>
		<pubDate>Wed, 02 Jan 2013 11:34:39 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[color]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4899</guid>
		<description><![CDATA[phpColors is an interesting library that makes it easy to work with colors in PHP. It can determine whether a color is dark or light, as well as darken or lighten a color incrementally, as well as generate complementary colors. It has functions that output hexadecimal or HSL representations of the color, or a gradient [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><a href="http://mexitek.github.com/phpColors/">phpColors</a> is an interesting library that makes it easy to work with colors in PHP. It can determine whether a color is dark or light, as well as darken or lighten a color incrementally, as well as generate complementary colors. It has functions that output hexadecimal or HSL representations of the color, or a gradient array.</p>
<p>It makes it super easy to do something like this:</p>
<pre class="brush: php; title: ; notranslate">
using phpColors\Color;
$color = new Color(&quot;#eeeeee&quot;);

if ( $color-&amp;gt;isLight() ) {
	$gradient = $color-&gt;makeGradient();
	// array( &quot;light&quot; =&gt; &quot;the_light_color_hex&quot;, &quot;dark&quot; =&gt; &quot;the_dark_color_hex&quot; )
}
</pre>
<p><a href="http://mexitek.github.com/phpColors/">phpColors</a> [GitHub]</p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2013/01/02/manipulating-color-data-with-phpcolors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Proposed Secure Password Hashing API in PHP 5.5</title>
		<link>https://www.webmaster-source.com/2012/10/17/proposed-secure-password-hashing-api-in-php-5-5/</link>
		<comments>https://www.webmaster-source.com/2012/10/17/proposed-secure-password-hashing-api-in-php-5-5/#comments</comments>
		<pubDate>Wed, 17 Oct 2012 11:20:05 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[passwords]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4846</guid>
		<description><![CDATA[PHP 5.5 will be gaining a simpler and more newbie-friendly way to securely hash passwords. As those who are active in the PHP community are all to well aware of, it is quite a trial to educate everyone on properly securing passwords in their applications. Even large web companies are routinely outed for their lax [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>PHP 5.5 will be gaining a simpler and more newbie-friendly way to securely hash passwords. As those who are active in the PHP community are all to well aware of, it is quite a trial to educate everyone on <a href="http://www.webmaster-source.com/2012/09/04/6-articles-you-should-read-before-storing-users-passwords/">properly securing passwords</a> in their applications. Even large web companies are routinely outed for their lax measures. Sometimes they&#8217;re stored in plain text and sometimes they might as well be, like when weak MD5 or SHA1 hashes are used. Remember the big scandal when Gawker Media&#8217;s database of user passwords was leaked, and the weak hashes were solved within days? Or more recently, <a href="https://plus.google.com/116797686750161798768/posts/NGV5xQwJywf">when it was discovered</a> that Pandora not only stored your password in cleartext, but transmitted it that way as well? It seems that at least two well-known websites have a similar &#8220;facepalm&#8221; moment every year.</p>
<p>The PHP contributors want to help combat this problem—at least among companies using PHP, obviously the issue is by no means limited to PHP developers—with the new API. A couple of simple functions that even the most novice of developers can use will automatically take care of the hashing using bcrypt with a reasonable work factor.</p>
<p>The proposed syntax is something like this:</p>
<pre class="brush: php; title: ; notranslate">
//hashing a new password
$hash = password_hash($password_entered);

//Checking a password
if (password_verify($password_entered, $hash_from_database)) {
    //password is valid if password_verify() returns true
}
</pre>
<p>For compatibility with versions of PHP prior to 5.5, you can even download <a href="https://github.com/ircmaxell/password_compat">a PHP implementation</a> that will automatically be disabled in a PHP 5.5 environment.</p>
<p><a href="https://gist.github.com/3707231">The new Secure Password Hashing API in PHP 5.5</a> [GitHub]</p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2012/10/17/proposed-secure-password-hashing-api-in-php-5-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GitList: View Your Git Repositories on the Web</title>
		<link>https://www.webmaster-source.com/2012/08/14/gitlist-view-your-git-repositories-on-the-web/</link>
		<comments>https://www.webmaster-source.com/2012/08/14/gitlist-view-your-git-repositories-on-the-web/#comments</comments>
		<pubDate>Tue, 14 Aug 2012 11:03:59 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[GitHub]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[version control]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4776</guid>
		<description><![CDATA[Wouldn&#8217;t it be cool if you could host your own private GitHub, for browsing your local repositories or remote ones you host on your own server? Well, there&#8217;s a new PHP application in town that lets you do exactly that. GitList, the self-described &#8220;elegant and modern git repository viewer&#8221; adds a simple web interface for [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Wouldn&#8217;t it be cool if you could host your own private GitHub, for browsing your local repositories or remote ones you host on your own server? Well, there&#8217;s a new PHP application in town that lets you do exactly that. <a href="http://gitlist.org/">GitList</a>, the self-described &#8220;elegant and modern git repository viewer&#8221; adds a simple web interface for your repositories, allowing you to browse commits and code. It&#8217;s still in its infancy, but it has the basics.</p>
<p style="text-align: center;"><a href="http://gitlist.org/"><img style=' display: block; margin-right: auto; margin-left: auto;'  class="aligncenter size-full wp-image-4777 imgborder" title="GitList: Commits" src="//www.webmaster-source.com/wp-content/uploads/2012/07/gitlist-commits.jpg" alt="" width="600" height="191" /></a></p>
<p>Setup was a little bit of a hassle at first, due to some dependency issues with the development version I was trying to install. I would definitely recommend downloading the stable version <a href="http://gitlist.org/">from GitList.org</a>. The <a href="https://github.com/klaussilveira/gitlist#installing">installation instructions </a>are simple enough, though the script seems to prefer having its own domain or subdomain. (GitList doesn&#8217;t use absolute URLs, and there is no documented configuration option to set a base directory other than the domain root.)</p>
<p>Once you get it up and running, it&#8217;s a convenient way to view commits. I&#8217;d probably be using it regularly if I wasn&#8217;t already hosting my private repositories on <a href="https://bitbucket.org/">BitBucket</a>.</p>
<p style="text-align: center;"><img style=' display: block; margin-right: auto; margin-left: auto;'  class="aligncenter size-full wp-image-4778 imgborder" title="GitList: Diff" src="//www.webmaster-source.com/wp-content/uploads/2012/07/gitlist-diff.jpg" alt="" width="600" height="323" /></p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2012/08/14/gitlist-view-your-git-repositories-on-the-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WordPress&#8217;s&#8230;Interesting Way of Dealing with Magic Quotes</title>
		<link>https://www.webmaster-source.com/2012/08/09/wordpresss-interesting-way-of-dealing-with-magic-quotes/</link>
		<comments>https://www.webmaster-source.com/2012/08/09/wordpresss-interesting-way-of-dealing-with-magic-quotes/#comments</comments>
		<pubDate>Thu, 09 Aug 2012 11:55:19 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[WordPress]]></category>
		<category><![CDATA[Magic Quotes]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4783</guid>
		<description><![CDATA[If you&#8217;ve been working with PHP for awhile, you&#8217;re probably familiar with one of the worst ideas the language&#8217;s developers ever came up with: Magic Quotes. If not, here&#8217;s a brief history lesson. In order to help newbies write functioning MySQL queries, they thought it would be a great idea to automatically escape input data [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;ve been working with PHP for awhile, you&#8217;re probably familiar with one of the worst ideas the language&#8217;s developers ever came up with: Magic Quotes.</p>
<p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="//www.webmaster-source.com/wp-content/uploads/2012/08/magic-quotes-not-magic.png" alt="" title="magic-quotes-not-magic" width="269" height="91" class="alignright size-full wp-image-4785 imgborder" />If not, here&#8217;s a brief history lesson. In order to help newbies write functioning MySQL queries, they thought it would be a great idea to automatically escape input data with slashes, overwriting the $_POST, $_GET and $_REQUEST globals. So if someone submitted <code>hello, I'm Steve</code> through a form, it would be immediately converted to <code>hello, I\'m Steve</code> so the apostrophe wouldn&#8217;t cause issue if a naive user tried inserting it into a database.</p>
<p>But what if you weren&#8217;t going to dump the data into a MySQL database? Too bad, it&#8217;s now full of slashes and you have to use <code>stripslashes()</code> on the variable. Also, you could conceivably end up with something like <code>hello, I\\\'m Steve</code> if you try escaping the data yourself before inserting the data into a database. It was a massive headache, and the normal practice ended up being &#8220;check to see if magic quotes are enabled at the top of your script, and strip the slashes out if the feature is activated. Then handle database queries with prepared statements or by properly escaping the data.&#8221;<span id="more-4783"></span></p>
<p>Fortunately, the PHP project eventually came to their senses and deprecated magic quotes, finally removing the feature entirely with the new PHP 5.4.</p>
<p>Now&#8230;back to WordPress.</p>
<p>I was investigating an issue with a plugin where extraneous slashes were appearing in strings processed by <a href="http://codex.wordpress.org/Class_Reference/wpdb#INSERT_rows"><code>$wpdb-&gt;insert()</code></a> when I found this gem in <code>wp-includes/load.php</code>:</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Add magic quotes to $_GET, $_POST, $_COOKIE, and $_SERVER.
 *
 * Also forces $_REQUEST to be $_GET + $_POST. If $_SERVER, $_COOKIE,
 * or $_ENV are needed, use those superglobals directly.
 *
 * @access private
 * @since 3.0.0
 */
function wp_magic_quotes() {
	// If already slashed, strip.
	if ( get_magic_quotes_gpc() ) {
	        $_GET    = stripslashes_deep( $_GET    );
	        $_POST   = stripslashes_deep( $_POST   );
	        $_COOKIE = stripslashes_deep( $_COOKIE );
	}

	// Escape with wpdb.
	$_GET    = add_magic_quotes( $_GET    );
	$_POST   = add_magic_quotes( $_POST   );
	$_COOKIE = add_magic_quotes( $_COOKIE );
	$_SERVER = add_magic_quotes( $_SERVER );

	// Force REQUEST to be GET + POST.
	$_REQUEST = array_merge( $_GET, $_POST );
}
</pre>
<p>It checks to see if the server has Magic Quotes enabled. But instead of stripping the slashes when the feature is active, which is the standard practice, it 	<em>adds</em> slashes when it&#8217;s disabled. If I were working at a desk when I saw that, I would have hit my head on it.</p>
<p>Purportedly, it&#8217;s for backwards-compatibility with older, poorly-coded themes and plugins. While I understand the predicament, it&#8217;s a backwards solution. It encourages poor development practices, and creates obstacles for those trying to do things properly.</p>
<p>I hope they end up phasing this out sometime, but for now, we&#8217;ll just have to make do with this solution:</p>
<pre class="brush: php; title: ; notranslate">
$post = array_map('stripslashes_deep', $_POST);
$get = array_map('stripslashes_deep', $_GET);
$request = array_map('stripslashes_deep', $_REQUEST);
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2012/08/09/wordpresss-interesting-way-of-dealing-with-magic-quotes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Handling File Uploads with PHP</title>
		<link>https://www.webmaster-source.com/2012/07/17/handling-file-uploads-with-php/</link>
		<comments>https://www.webmaster-source.com/2012/07/17/handling-file-uploads-with-php/#comments</comments>
		<pubDate>Tue, 17 Jul 2012 11:54:31 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[(x)html]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4747</guid>
		<description><![CDATA[So you want to add a file uploader to your site. It&#8217;s quite easy to do with PHP, but first you must understand the inherent risks. You&#8217;re going to allow just anyone to take a file and put it on your server. That file could be anything. It could be an image like you may [&#8230;]]]></description>
				<content:encoded><![CDATA[<p><img style=' float: right; padding: 4px; margin: 0 0 2px 7px;'  src="//www.webmaster-source.com/wp-content/uploads/2012/07/file_upload_sketch_icon.png" alt="" title="File Upload" width="128" height="128" class="alignright size-full wp-image-4752" />So you want to add a file uploader to your site. It&#8217;s quite easy to do with PHP, but first you must understand the inherent risks. You&#8217;re going to allow just anyone to take a file and put it on your server. That file could be anything. It could be an image like you may intend, or someone could get clever and try to upload a malicious PHP script, which could then be run when called by the appropriate URL. Or a user could upload larger files than you intended and waste your server&#8217;s storage space. (This is assuming you intend to have a public-facing uploader, of course. It&#8217;s less of an issue if its a back-end feature.)</p>
<p>Let&#8217;s start with the basics of setting up the form, and handling the uploaded file. Then we can tackle some of the security issues.</p>
<p>For the upload to work, you must add <code>enctype="multipart/form-data"</code> to your <code>form</code> tag. This signals that the POST request will contain upload data as well as the form field values.</p>
<p>Among fields you&#8217;ll need are a hidden field named <code>MAX_FILE_SIZE</code>, which tells the client not to accept a file over a certain number of bytes (300000, or 300 kilobytes, in this example) as well as the file upload field itself.<span id="more-4747"></span></p>
<pre class="brush: xml; title: ; notranslate">
&lt;form method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
	&lt;input type=&quot;hidden&quot; name=&quot;MAX_FILE_SIZE&quot; value=&quot;300000&quot; /&gt;
	&lt;input type=&quot;file&quot; id=&quot;myupload&quot; name=&quot;myupload&quot; /&gt;
	&lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
&lt;/form&gt;
</pre>
<p>This form is going to submit to itself (that is, the PHP file that outputs the form is also the script that processes the data) so it is unnecessary to specify an <code>action</code> value for the form.</p>
<p>The code that processes the upload is actually just a couple lines. The rest is error-checking.</p>
<pre class="brush: php; title: ; notranslate">
if ($_POST['submit']) { //If the form was submitted, commence doing stuff

	if ($_FILES['myupload']['error'] != 0) {
		//The upload failed for some reason, so output a human-friendly error message for the corresponding error number.
		$errcode = array(
			&quot;No errors&quot;,
			&quot;File exceeded the PHP INI upload_max_filesize value.&quot;,
			&quot;File exceeded the maximum allowed size.&quot;,
			&quot;Partial upload.&quot;,
			&quot;No file uploaded.&quot;,
			&quot;UPLOAD_ERR_NO_TMP_DIR&quot;,
			&quot;UPLOAD_ERR_CANT_WRITE&quot;,
			&quot;UPLOAD_ERR_EXTENSION&quot;,
			&quot;UPLOAD_ERR_EMPTY&quot;
		);
		$error = $errcode[$_FILES['myupload']['error']];
		echo &quot;Error: &quot; . $error;
	}
	else {
		//No errors, so we can move the uploaded file to our uploads directory
		move_uploaded_file($_FILES['myupload']['tmp_name'], &quot;./uploads/&quot;.$_FILES['myupload']['name']);
		unset($_FILES);
	}

}
</pre>
<p>The most important part here is the <a href="http://php.net/manual/en/function.move-uploaded-file.php"><code>move_uploaded_file()</code></a> function, which does what it says on the box. The first argument is the temporary path of the uploaded file (which $_FILES[&#8216;myupload&#8217;][&#8216;tmp_name&#8217;] contains) and the second is the destination. In the example, I set it to use the name of the uploaded file (you may want to rename it) and put it in <code>./uploads</code>.</p>
<p>That should be enough for a basic file uploader, but it does absolutely nothing to check that the uploaded data is what you&#8217;re expecting. It could be exploited terribly easily.</p>
<p>To combat abuse, you should add some checks. A couple of good things to look for are:</p>
<ul>
<li>The MIME type. Inspect the uploaded file and make sure it&#8217;s an image file (or whatever kind of document you&#8217;re wanting).</li>
<li>The existence of &#8220;.php&#8221; in the filename.</li>
</ul>
<p>It&#8217;s also a good idea for you to set the permissions of your uploads folder to disallow execution of shell scripts.</p>
<p><a href="http://www.webmaster-source.com/2012/07/10/find-an-images-dimensions-and-mime-type-with-php/">Checking the MIME type</a> of an image is surprisingly easy, since there&#8217;s a handy function built-in to retrieve that information from a valid image file.</p>
<pre class="brush: php; title: ; notranslate">
$imgdata = getimagesize($_FILES['myupload']['tmp_name']);
if (!in_array($imgdata['mime'], array( 'image/gif', 'image/png', 'image/jpeg', 'image/pjpeg' ))) {
	//This isn't an image file. Better display an error and NOT move the image to its permanent spot. The temp file will be deleted automatically.
}
</pre>
<p>Preventing PHP files from being uploaded, fortunately, doesn&#8217;t require a scary Regular Expression. You can just use <code>strpos()</code> to check for the presence of a substring.</p>
<pre class="brush: php; title: ; notranslate">
if (strpos(strtolower($_FILES['ad_img']['name']), '.php') !== false) {
	//Stop right there. Why does an image file have '.php' in it?
}
</pre>
<p>That&#8217;s enough to discourage your average script kiddie, though someone with real skill might be able to find a way to get around such checks. If anybody has something to add, I&#8217;d like to hear it.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2012/07/17/handling-file-uploads-with-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Find an Image&#8217;s Dimensions and MIME Type with PHP</title>
		<link>https://www.webmaster-source.com/2012/07/10/find-an-images-dimensions-and-mime-type-with-php/</link>
		<comments>https://www.webmaster-source.com/2012/07/10/find-an-images-dimensions-and-mime-type-with-php/#comments</comments>
		<pubDate>Tue, 10 Jul 2012 11:58:12 +0000</pubDate>
		<dc:creator><![CDATA[Matt]]></dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webmaster-source.com/?p=4741</guid>
		<description><![CDATA[What&#8217;s the easiest way to figure out the width and height of an image, as well as the format of the file, in PHP? Given that the existence of a core function for practically everything is one of the language&#8217;s strengths, it&#8217;s unsurprising that it&#8217;s pretty easy. The getimagesize() function returns an array containing the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>What&#8217;s the easiest way to figure out the width and height of an image, as well as the format of the file, in PHP? Given that the existence of a core function for practically everything is one of the language&#8217;s strengths, it&#8217;s unsurprising that it&#8217;s pretty easy.</p>
<p>The <a href="http://www.php.net/manual/en/function.getimagesize.php"><code>getimagesize()</code></a> function returns an array containing the width and height and the content type.</p>
<pre class="brush: php; title: ; notranslate">
//Basic usage
$info = getimagesize($filename);
$width = $info[0];
$height = $info[1];
$format = $info['mime'];

//Alternate one-liner suggested by the manual
list($width, $height, $type, $attr) = getimagesize($filename);
</pre>
<p>This function is really useful for handling image uploads, since you can&#8217;t necessarily trust the MIME type that <code>$_FILES</code> reports. The function actually inspects the file to ascertain the type, rather than relying on what the client reports. Also, you may want to make sure that the uploaded images match the dimensions you have in mind.</p>
<p>Here&#8217;s how I like to handle it:</p>
<pre class="brush: php; title: ; notranslate">
$imgdata = getimagesize($_FILES['image_upload']['tmp_name']);

if ($imgdata[0] &gt; 640 || $imgdata[1] &gt; 480) {
	$errors[] = &quot;Your image is too big!&quot;;
}

if (!in_array($imgdata['mime'], array( 'image/gif', 'image/png', 'image/jpeg', 'image/pjpeg' ))) {
	$errors[] = &quot;Your file should be a PNG, JPG or GIF!&quot;;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.webmaster-source.com/2012/07/10/find-an-images-dimensions-and-mime-type-with-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/


Served from: www.webmaster-source.com @ 2026-04-28 08:26:10 by W3 Total Cache
-->