Tag Archive: PHP

A little Nested foreach Tip

PHP

Here is a tip I found when fixing the database error for one of my clients.

<?php
	$row_parts = array("Monthly", "Special", "Transport", 10, 20);
	foreach ($row_parts as $row_part):
		foreach ($row_parts as $row_part_2):
			if ($row_part == $row_part_2):
				continue;
			elseif (!is_numeric($row_part) && !is_numeric($row_part_2)):
				continue;
			elseif (is_numeric($row_part) && is_numeric($row_part_2)):
				continue;
			endif;
			echo $row_part . "_" . $row_part_2 . "<br />";
		endforeach;
	endforeach;
?>

The above code outputs the following:

Monthly_10
Monthly_20
Special_10
Special_20
Transport_10
Transport_20
10_Monthly
10_Special
10_Transport
20_Monthly
20_Special
20_Transport

It uses a single array to store both words and numbers. Then combine them together through a nested foreach loop with an underscore to form reversible variables, reversible columns in this case.

I then can use these generated values to match the existing columns in the MySQL table and assign the corresponding variables to these values. For example, “20_Monthly” column would assign to $monthly_20 if “Monthly_20″ column is undefined.

It saves client’s, other developers’, and my time to look for the source of errors in the future if the database column change from “20_Monthly” to “Monthly_20″, assuming that the format of the database column names remain the same.

This type of error for changing the name of database column is often occurred during the server migration. An unexperienced client would manually type the database entries by himself or by hiring an assistant, instead of using export and import features in phpMyAdmin.

Have you had similar clients? And how did you respond to them? Discuss them in the comments section below.

A Nice way to use the foreach Loop

PHP

I have been using this technique for a long time. Because I wanted to decrease the code I want to write, I developed this technique. Another reason that I found this technique helpful is that I don’t have to remember the whole snippets when learning a new trick.

Here is an example of the technique for the foreach loop I’m talking about:

$theme_mods = array(
	"footer_bg_color" => "#ADFF2F"
);
foreach ($theme_mods as $theme_mod => $default):
	$$theme_mod = get_theme_mod($theme_mod, $default);
	if (empty($$theme_mod)):
		$$theme_mod = $default;
	endif;
endforeach;

For those who are wondering what the above code is about. It’s used to apply the Theme Customizer settings to a WordPress theme. Here is the link to get_theme_mod() function documentation page, which is what the above code mainly about.

As the code shows, I use nested variables to assign each value in the loop to different variables for use outside the loop. For instance, the key “footer_bg_color” in the array would be converted into $footer_bg_color to provide value “#ADFF2F”.

I often use this technique on forms, where the fields need to be checked whether or not it’s empty. If so, assign an empty value. Otherwise, retrieve the value from the database and store it to the variable.

Here is the usage for the above code:

<style type='text/css'>
.site-footer {
	background-color: <?php echo $footer_bg_color; ?>;
}
</style>

In the future, when I need to add additional items to the theme_mods list, I just have to insert needed keys and values to the theme_mods array and add the key variables to the corresponding code.

I think that’s what others called DRY (Don’t Repeat Yourself) practice? I use it as a method for laziness to remember stuff :)

Do you practice DRY method often or rarely? And can you remember new techniques through using this method as well? Please share them in the comment. Thanks.

Don’t Generate Stylesheet Dynamically

WordPress Tips

During the early stages of my theme development process, I planned to use a PHP-generated stylesheet as the main stylesheet. Borrowing the WordPress native functions in wp-load.php, I would be able to use WP functions inside the PHP file which is the source file that the stylesheet would be generated.

For those unfamiliar with the above meaning, here is a line of code which needs to be placed in the first line of the stylesheet to be “dynamically generated”:

<?php header("Content-type:text/css"); ?>

And add the php extension to the filename of the stylesheet (ex style.css.php), as well as change the corresponding code in functions.php in your theme folder from:

wp_enqueue_style("shadow_leaves-style-custom", get_template_directory_uri() . "/css/custom.css", array("shadow_leaves-style"));

to:

wp_enqueue_style("shadow_leaves-style-custom", get_template_directory_uri() . "/css/custom.css.php", array("shadow_leaves-style"));

However, during my research of how to dynamically include wp-load.php instead of hard coding it, I discovered this article which talks about the bad practice of loading wp-load.php into external scripts, and generated CSS/JS in general.

Basically, for wp-load, it would allow the server to load two instances of WordPress, cause high resources usage on the server, in turn causing slow down of the site.

As for the dynamic generated scripts, it’s a bad practice because the server needs to generate the stylesheets / scripts every time one of the pages on the site is visited, as well as caching.

Overall, the primary reason for not using wp-load and dynamically generated files is to prevent slow down of the site.

Did you use PHP header() function to dynamically generate either stylesheets or javascript files or both before? And what’s your creative use of the header() function? Please discuss in the comment below. Thanks.

Access PHP values within JavaScript in WordPress

WordPress JavaScript

When using JavaScript to access PHP values in WordPress, the official way, according to the WordPress Codex, is

<?php

// Register the script first.
wp_register_script( 'some_handle', 'path/to/myscript.js' );

// Now we can localize the script with our data.
$translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_value' => '10' );
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// The script can be enqueued now or later.
wp_enqueue_script( 'some_handle' );

?>

And then using JavaScript OOP method to access the variable:

<script>
    alert( object_name.some_string) ; // alerts 'Some string to translate'
</script>

I know that the PHP function is used for translating the values across different languages (such as English to French), and for transferring multiple values to JS as well. However, for transferring simple value such as the location of a file in a plugin and some numbers, you can use inline JS directly.

	// Pass the PHP variables to JS
function js_vars() {
?>
	<script type="text/javascript">
		var dir = "<?php echo plugins_url("", __FILE__); ?>";
	</script>
<?php
}

add_action("wp_head", "js_vars");
?>

And you can access the variable(s) in JS:

$(".ast_gplus img").attr("src", dir + "/Google.png");

Of course, you need to use wp_localize_script PHP function if you follow OOP (Object Oriented Programming) practice.

Have you used wp_localize_script before to transfer such simple values to JavaScript? And for what reason, code consistency by using OOP, have many variables to transfer to JavaScript, or else?

A Quick PHP array Tip

PHP

Here is a small tip for the nested arrays in PHP.

When using nested arrays, make sure not to include an array in a key. Only include an array in a value.

For instance, the following code results in the “illegal offset type” error:

$fruits = array("apple", "banana", array("good", "well")=>"pineapple");

Here, the problem is in the third pair of the fruits array. Here is the right way to do it:

$fruits = array("apple", "banana", "pineapple"=>array("good", "well"));

Have you experienced this issue before, or did you already know this type of error?

Disable PHP in Uploads issue in iThemes Security

Disable PHP in Uploads

Caution when enabling the “Disable PHP in Uploads” option under System Tweaks section for iThemes Security. It will prevent all the files containing “php” in the filename from displaying, whether or not it’s in the filename section or the extension section. For example, example.php will display the not found page, and lessphp.png will also display the not found page.

Disable PHP in Uploads

“Disable PHP in Uploads” option located in the iThemes Security settings page. Click the image to enlarge.

The solution is to avoid using “php” in the filename when uploading images while the option is enabled. And if you still want to use “php” in the filename, you can disable the Disable PHP uploads option, however it’s not recommended.

Image is broken

Do you have this issue that the image is not showing up after you uploaded the image like the screenshot on the left?

Then this might be the problem.

If you still have questions regarding this issue, please leave a comment below.

Replace a phrase in several posts for WordPress

MySQL replace function

I talked about changing the URL paths of images and links for the old posts will be based on the 404 not found error generated through traffic, one by one. Apparently, this was a bad decision. I don’t expect the traffic go up so quickly after I added these old posts. It seems that they still are more popular than my new ones. Therefore, I decided to search for a solution to replace some parts of url for the links (and images) in the old posts with the current url format so that it can direct them to the correct file locations.

During the research, I stumbled across MySQL replace function. I thought that it could come in handy when replace certain phrase within some posts, such as old links and image links. And here are the steps:

  1. Login to cPanel of your web host.
  2. Find and login to phpmyadmin.
  3. Go to the database which your WordPress installation resides.
  4. Click the SQL tab and type the following codes into the text box:
    update wp_posts set post_content = replace(post_content, ‘find this text’, ‘replace with this’);

    Replace “find this text” with the text or phrase or whatever you want to be replaced, and replace “replace with this” with the text you want to replace. For instance, mine was

    update wp_posts set post_content = replace(post_content, ‘robbychen.com/oldBlog’, ‘blog.robbychen.com’);
  5. Click Go button and the text is changed in the database.

Now that almost all the links were fixed (at least I think), I still will continue monitoring the 404 errors to see which links are missed from the above code until there are no more 404 errors.

If the above code could not work for you, you can’t understand one or more of above steps, or you have other solutions to replace the text across multiple posts, leave a comment below.

Creating an even Simpler Framework than MVC – Part 2

I discussed a little bit about this mini-framework in part 1. Today I rewrote the whole code for the index.php to be more configurable, and I added another folder for storing PHP pages. And yes, it includes the automatic page title generation.

It’s up to you to create other folders for the includes, images, and other files, but the PHP pages folder is a must have. Without this folder, the framework will grab the original page without process through the framework.

Let’s begin.

I need to first introduce the basic folder structure for the framework:

Note that I’ve included lessPHP inside the css folder to make writing styles easier.

The .htaccess file in the root folder is exactly the same as part 1‘s:

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>

However, the one in the pages folder is different:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteRule ^(.*)$ ../$1 [L]
</IfModule>

As those of you who understands the Apache better knows, the above code acts like access rejection. It means that whenever someone tries to access the pages folder or one of the files within it, this code will automatically rewrite the URL to the root folder. Note the difference between rewrite and redirect.

The pages folder is kinda like public or webroot folder, except it’s only used for PHP pages, not for images, stylesheets, Javascripts, or any other files.

Now the most important file, index.php. This file is placed in the root folder, and contains the most important code in the whole framework. I also added page title generation in this file as stated before.

[php]
<?php
	// Variables configuration
$rootDir = dirname(__FILE__) . "/";
$mainDir = "pages/";
$appDir = $rootDir . $mainDir;
if (isset($_GET['url'])):
	$url = $_GET['url'];
	$path = $appDir . $url . ".php";
else:
	$path = $appDir . "index.php";
endif;
if (!file_exists($path)):
	$path = $appDir . 'notfound.php';
	$title = "Page not found";
endif;

	// Set page title
	// First set the page title from the the title variable from the individual page if presented
foreach (file($path) as $content):
	if (strstr($content, "title")):
		if (strstr($content, """)):
			$quote = """;
		else:
			$quote = "'";
		endif;
		$titleVar = explode($quote, $content);
		$title = $titleVar[1];
	endif;
endforeach;
	// Process the URL as the page title if title variable is not set
if (empty($title)):
	$urlPath = explode("/", $_SERVER['REQUEST_URI']);
	$titleVar = (string)$urlPath[sizeof($urlPath)-1];
	$title = "";
	for ($i=0; $i < strlen($titleVar); ++$i):
		if ($titleVar{$i} == strtoupper($titleVar{$i})):
			$title .= " ";
		endif;
	$title .= $titleVar{$i};
	endfor;
	$title = ucfirst($title);
endif;

	// Include the neccesary pages
include_once $rootDir . 'includes/header.php';
include_once $path;
include_once $rootDir . 'includes/footer.php';
?>
[/php]

As you have noticed, I’m using URL to auto-generate the page title. You can also set the page title for each page using the $title variable.

The $mainDir variable is configurable, so you can rename the pages folder to whatever you want.

That’s it. If you don’t count the img, css, and js folder and files inside them, the files for the framework would be total of 7 files.

Here is the completed files.

If you have any issues working with this mini-framework, leave a comment below and I will happy to help you.

Creating an even Simpler Framework than MVC Framework – Part 1 (Updated)

Update: I rewrote the code for the framework and added page title generation as well, take a look at part 2.

After building and digging through the source of the simple MVC framework provided by Anant Garg, I was able to discover the true nature of the MVC framework. Actually, I’m able to modify his framework to an even simpler framework which just use View and a little Controller in the MVC (Model-View-Controller) with no database connectivity.

The primary use for the MVC pattern is to work with the database. However, sometimes we don’t need to use database to creating a web site. According to my own knowledge, the Model is used to interact with the database and the Controller uses logical to process the database.

I stated that I need to use “a little” Controller because it also controls which page to display and sends it to the View.

In this simple framework (and perhaps all of the MVC frameworks), the most important file is .htaccess which controls the URL. Here is the content of the file copied directly from Anant’s post:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

</IfModule>

Note that this .htaccess file needs to place in th root directory of your web site instead of public folder because we will be creating a framework that has no directory. You can create public folder or webroot folder if you want, but make sure to change the following code accordingly.

The above code converts the URL path to the url query. For example, the URL http://localhost/mvc/test would be converted to http://localhost/index.php?url=mvc/test.

Next step is to create the index.php file which used to process the url query:

<?php
	if (isset($_GET['url'])):
		$url = $_GET['url'];
		$path = "{$url}.php";
	else:
		$path = "home.php";
	endif;

	include_once 'includes/header.php';
	if (file_exists($path)):
		include_once $path;
	else:
		include_once 'notfound.php';
	endif;
	include_once 'includes/footer.php';
?>

This is what I called “reverse include”, because I had always been include header and footer manually on every page until I found CakePHP MVC framework.

I also stated that this framework will not have any folder. Well, to include header and footer, you need to create an includes folder to place all the repeatable scripts, unless you really want to be disorganized :) .

Congratulation, you just created a mini framework. Note that this framework is used for small websites or personal sites where the database is not used at all. This means that it doesn’t have a back-end to edit the page directly on the server.

However, there is also an advantage to it. You don’t need to include the header and footer manually when creating a new page. It will include them automatically. It also can direct to the custom page if the specified page is not found.

About the title issue: I haven’t found a solution to set the title on individual page yet. Right now the title in the header is static. I will update this post once I find a solution to this issue.

Feel free to discuss this framework with me in the comment below.