Amoeba Solution Kioskhttp://ask.amoeba.co.in Providing solutions for PHP, MySQL, Flash, Flex, Action Script, Javascript, YUI, JQuery, CSS, XHTML problems.Mon, 12 Aug 2013 13:54:29 +0000enhourly1http://wordpress.org/?v=3.2.1PHP – Expire Session When Page is Refreshed or Browser Back Button is Clickedhttp://ask.amoeba.co.in/php-expire-session-when-page-is-refreshed-or-browser-back-button-is-clicked/ http://ask.amoeba.co.in/php-expire-session-when-page-is-refreshed-or-browser-back-button-is-clicked/#commentsMon, 12 Aug 2013 13:52:32 +0000Aneeskahttp://ask.amoeba.co.in/?p=208I would not say this is a great feature to have in a web application. But many people wanted to learn how the user session of a web application can be ended if the logged in user clicks on the Back button in the browser or refreshes the page. You might have seen this feature implemented in many online banking applications and online ticket booking sites. Actually, this is a bad user experience as an accidental pressing of Backspace button or clicking of Back button will require the user to log in to the application again. But this is considered as a extended security feature this will prevent XSRF to a great extent. But this is a performance killer, so make sure you have enough bandwidth and infrastructure in place to handle the situation.

I am now going to talk about how we can implement this behavior in a PHP application. There are two things that we need to do to achieve this behavior.

Make sure the webpage is not cached in browsers and that the browser makes a request to the server every time a page is opened in the browser, even if the user navigates to a page by clicking the Back button. This way, browser will not render anything from the cache but will make a request to the server to fetch fresh content every time.

Define and validate a unique token for each request. You will have to generate a unique token for each request and all expect the next request from the user to have this token defined in the URL.

I have created a sample prototype to demo this feature. This is just a one page web app with no proper authentication done. This is just a prototype for you to understand how the behavior is implemented. You can scale it and use it according to your needs and to fit in your applications.

You just need to make sure that the $token parameter is added to all URLs in your page.

Save the code in a PHP file and run it using a browser and it will ask you to login. The dummy login function will log you in and it will start generating tokens for each request and validate it. As long as you keep on clicking on the Navigate link, the session will be active. The moment you use the browser Back button to navigate or refresh the page, the session will be expired and will ask you to login again.

Please let me know if you have any questions.

]]>http://ask.amoeba.co.in/php-expire-session-when-page-is-refreshed-or-browser-back-button-is-clicked/feed/0Sending Mails using PHP in localhost on Windows/IIS using smtp4devhttp://ask.amoeba.co.in/sending-mails-using-php-in-localhost-on-windowsiis-using-smtp4dev/ http://ask.amoeba.co.in/sending-mails-using-php-in-localhost-on-windowsiis-using-smtp4dev/#commentsThu, 01 Aug 2013 09:25:05 +0000Aneeskahttp://ask.amoeba.co.in/?p=205The mail function in PHP doesn’t work in Windows/IIS environment unless you set up an SMTP server and configure it. SMTP server now doesn’t come built in with Windows 7 either.

So here is a quick way for you to be able to send mails from your applications and test the mails you send out from PHP or any other applications using SMTP on your localhost. There are two advantages here. You can verify that the mails you are sending out from your applications are correct in format and content. It also stops sending real emails from your development or local servers avoiding unwanted delivery of mails during development and testing.

]]>http://ask.amoeba.co.in/sending-mails-using-php-in-localhost-on-windowsiis-using-smtp4dev/feed/0PHP find substring without breaking words or don’t cut words – MultiByte (MB) Stringshttp://ask.amoeba.co.in/php-find-substring-or-cut-a-string-without-breaking-a-word-multibyte-mb-strings/ http://ask.amoeba.co.in/php-find-substring-or-cut-a-string-without-breaking-a-word-multibyte-mb-strings/#commentsFri, 19 Oct 2012 11:20:19 +0000Aneeskahttp://ask.amoeba.co.in/?p=197substr to fetch a part of the string, we can only specify the length of the new string. That means, PHP will cut the string at the specified length and will not worry about words. When you usesubstr for showing excerpts, it doesn't look good with a split word at the end. Use the provided code to extract part of a string for a specified length.]]>Often we need to extract a portion of a string specified by a length. When we use the PHP function substr to fetch a part of the string, we can only specify the length of the new string. That means, PHP will cut the string at the specified length and will not worry about words. When you usesubstr for showing excerpts, it doesn’t look good with a split word at the end. Use the below code to extract part of a string for a specified length. The example uses the PHP MultiByte functions so you can use it for multi-byte encoded languages. If you are going to use it only for English, just replace all mb_ functions with normal functions.

If the character at the length specified is not a space, the code tries to find the previous space and cuts the string from there. If there is no space in the whole string it cuts at the specified length. Even though it uses a few mb_ functions, the performance was great. The execution time was very low and negligible (0.0003~).

]]>http://ask.amoeba.co.in/php-find-substring-or-cut-a-string-without-breaking-a-word-multibyte-mb-strings/feed/0VBScript Fetch and show the content of an HTML Table from a web pagehttp://ask.amoeba.co.in/vbscript-fetch-and-show-the-content-of-an-html-table-from-a-web-page/ http://ask.amoeba.co.in/vbscript-fetch-and-show-the-content-of-an-html-table-from-a-web-page/#commentsThu, 28 Jun 2012 09:18:42 +0000Aneeskahttp://ask.amoeba.co.in/?p=195). After accessing the table object, it loops through the rows and columns and appends the cell text to a string to finally print it.]]>Someone wanted the code written in VBScript, which would fetch the content of a webpage, grab the html table with a specific identifier from it, and print all the text in its cells. This script loads an instance of Internet Explorer in the background and asks it to load a webpage. We can then grab any DOM element on the page using Document.getElementById(). After accessing the table object, it loops through the rows and columns and appends the cell text to a string to finally print it. The example fetches a table from the webpage hosted here, http://anees.amoeba.co.in/table.html. The ID of the table is ‘daTable’.

Copy the code in to a Text Editor and save the file as .vbs. Run the file in Windows by double clicking it.

]]>http://ask.amoeba.co.in/vbscript-fetch-and-show-the-content-of-an-html-table-from-a-web-page/feed/1Pretty Print JSON String with PHP and Javascripthttp://ask.amoeba.co.in/pretty-print-json-string-with-php-and-javascript/ http://ask.amoeba.co.in/pretty-print-json-string-with-php-and-javascript/#commentsTue, 12 Jun 2012 14:48:09 +0000Aneeskahttp://ask.amoeba.co.in/?p=187While coding, many of us want to see a JSON string printed right in the browser in a readable format for easy debugging. In PHP, I usually convert the JSON string back to an Array and use print_r to print the array which throws readable output in the view-source mode. In some cases we really want to print the JSON string formatted. Use the below methods.

I. If you are using PHP 5.4.0 and above, you can use the json_encode method to print a JSON string formatted.

Here is a PHP function which accepts a JSON string and returns the formatted string. It uses 4 spaces for indentation. Change the value of $tab to the number of desired spaces for indent. The second parameter when set to true, returns the output in HTML format so that you can see the formatted JSON string right in the browser. Set it to false when you want to view the string in the source or in a console. This method can be used used for a JSON object of any depth.

However if you want to show the JSON string formatted in the HTML in a browser window, use the function below. You can also see how I am passing the data from PHP to JavaScript. The output of json_encode from PHP can be echoed directly to a JS variable which will create a JavaScript Object.

]]>http://ask.amoeba.co.in/pretty-print-json-string-with-php-and-javascript/feed/2Installing/Setting up PHP on WIndows 7 with IIS7 and PHP Managerhttp://ask.amoeba.co.in/installingsetting-up-php-on-windows-7-with-iis7-and-php-manager/ http://ask.amoeba.co.in/installingsetting-up-php-on-windows-7-with-iis7-and-php-manager/#commentsFri, 16 Dec 2011 10:28:12 +0000Aneeskahttp://ask.amoeba.co.in/?p=179Setting up PHP with IIS on a Windows OS has never been so easy. The PHP Manager for IIS makes it really to easily install, configure, manage and troubleshoot one or many PHP versions on the same IIS server. So if you are looking to setup PHP on your Windows 7 machine with IIS 7, follow the below steps.

I. Enable IIS on your machine:

In Start Menu, choose Run or press Windows Key+R to launch the Run dialog and type “optionalfeatures.exe” and click OK.

This launches the Windows Features where you can turn on/off default Windows programs and applications.

Enable Internet Information Services (IIS)

Expand the Internet Information Services node and open World Wide Web Services and then Application Development Features.

Click on Register New PHP Version and provide the path to php-cgi.exe in the dialog opened. (Refer the image below)

php-cgi.exe will be in the folder where you extracted the downloaded PHP software in the above step.

That’s all! Your PHP has been configured on IIS7. Click on Check phpinfo() to see whether it did it correct. PHP Manager has taken care of everything related to configuring PHP on IIS. PHP Manager does the following things.

Register PHP with IIS;

Validate and properly configure existing PHP installations;

Run multiple PHP versions side by side on the same server and even within the same web site;

You can now easily setup multiple PHP versions and configure them. You don’t need to edit the php.ini file in a text editor anymore. This tool makes it easy to enable/disable extensions and change the configuration settings.

Update: If you see any errors related to Fast-CGI quitting unexpectedly or missing MSVCR110.dll, install the Microsoft Visual C++ Redistributable software and make sure you chose the 32 bit version if you installed the x86 version of PHP. You can download the package here: http://www.microsoft.com/en-us/download/details.aspx?id=30679

Good Luck!

]]>http://ask.amoeba.co.in/installingsetting-up-php-on-windows-7-with-iis7-and-php-manager/feed/6Free WordPress themes and Malicious/Devil Codeshttp://ask.amoeba.co.in/free-wordpress-themes-and-maliciousdevil-codes/ http://ask.amoeba.co.in/free-wordpress-themes-and-maliciousdevil-codes/#commentsFri, 04 Nov 2011 10:17:09 +0000Aneeskahttp://ask.amoeba.co.in/?p=172I know it doesn’t sound good to talk bad here specially when you are writing an article after a long while. We have changed our website theme so it looks simple and loads pretty fast and we are back in to our business of giving things free and expecting nothing back . We don’t ask you to sign-up, we don’t ask you to click or read through our ads, and we don’t ask you to pay for our service. There are many amazing things out there which are absolutely free, like the WordPress platform we are using which is incredible! One would normally not really think twice before using any freely available WordPress theme. I did the same mistake, I went ahead and installed a theme named ‘Freshblog’ created by ‘Best WordPress Themes’ and featured at WordPress Theme Shock and Themes2WP for this site only to realize that I was hacked! I first noticed a few links pointing to some crazy websites being inserted at the bottom of every page which I couldn’t really find where they were coming from. It was not any of the plug-ins doing this. I used the WP Re-install feature to rewrite all the WP files except the Wp-Content and the WP-Config files. The problem didn’t go away. Did a backtrace at different levels and find out a chunk of malicious code in Wp-Config.php. I then did a search for similar pattern in my entire server and whoa! all the PHP files on my server had been injected with this malicious code.

I would not have had any issues if they added a few links back to their site for providing this theme for free but the buggers injected the malicious code in all the PHP files on my server, driving me nuts. Thank God, it was all in the same pattern making it easy for me to clean them using a script.

Now, how to scan for this malicious script and clean it?

Here is the script I wrote to clean the malicious code from all the PHP files on the server. Copy the below code to a file and put it in your root folder in your server and run it. I am sure most of the free themes from the above mentioned sites would have the malicious code in the same format. I’ll try to add more patterns to this script as you or I come across the others.

Before installing any free theme you got from a gallery site, search for terms like ‘md5′, ‘eval’, ‘create_function’, ‘wp_add_filter’, ‘hex’ in your theme source and make sure that they are not malicious code.

You can also install and run the plug-in ‘Exploit Scanner’ to see if you are already hacked. If you see a different pattern for these malicious code, send me the code and I will add the matching patterns for them in my scanner code.

Have Fun!

]]>http://ask.amoeba.co.in/free-wordpress-themes-and-maliciousdevil-codes/feed/0Compare two arrays in PHP using array_diff | Check whether arrays are equal.http://ask.amoeba.co.in/compare-two-arrays-in-php-using-array_diff-check-whether-arrays-are-equal/ http://ask.amoeba.co.in/compare-two-arrays-in-php-using-array_diff-check-whether-arrays-are-equal/#commentsTue, 07 Jun 2011 15:50:08 +0000Aneeskahttp://ask.amoeba.co.in/?p=166PHP function, array_diff to compute the difference of arrays. But this function just checks whether all the values of array1 is in array2 and if not returns the values which are not present in array2.]]>You want to compare two arrays in PHP. Basically what you need is to make sure that both the arrays contain the same set of values may or may not be in the same order. You can use the built-in PHP function, array_diff to compute the difference of arrays. But this function just checks whether all the values of array1 is in array2 and if not returns the values which are not present in array2.

]]>http://ask.amoeba.co.in/compare-two-arrays-in-php-using-array_diff-check-whether-arrays-are-equal/feed/3Remove Dashboard Widget Boxes (Meta Boxes) from WordPress and Network Admin Dashboardhttp://ask.amoeba.co.in/remove-dashboard-widget-boxes-meta-boxes-from-wordpress-and-network-admin-dashboard/ http://ask.amoeba.co.in/remove-dashboard-widget-boxes-meta-boxes-from-wordpress-and-network-admin-dashboard/#commentsFri, 22 Apr 2011 18:54:13 +0000Aneeskahttp://ask.amoeba.co.in/?p=162WordPress, by default shows a number of Widget Boxes in it’s admin homepage a.k.a the dashboard. These boxes are called Meta Boxes and shows Incoming Links, Plugins Feed, WordPress.org News and other WordPress news. Since WordPress 3.1, the Network features are managed through a Network Admin Dashboard accessible to the Super Admins. This Network Admin Dashboard also features these Meta Boxes.

We can pro grammatically remove these boxes. Use the below pieces of code in your theme’s functions.php or in your plugin or wherever you are overriding WordPress functionality.

]]>http://ask.amoeba.co.in/remove-dashboard-widget-boxes-meta-boxes-from-wordpress-and-network-admin-dashboard/feed/2Short Circuit Evaluation and its Use and Advantages in PHP and JavaScript – IF-less Flow Controlhttp://ask.amoeba.co.in/short-circuit-evaluation-and-its-use-and-advantages-in-php-and-javascript-if-less-flow-control/ http://ask.amoeba.co.in/short-circuit-evaluation-and-its-use-and-advantages-in-php-and-javascript-if-less-flow-control/#commentsMon, 20 Sep 2010 11:16:56 +0000Aneeskahttp://ask.amoeba.co.in/?p=157We call it Short Circuit Evaluation (also known as minimal evaluation, or McCarthy evaluation) when a programming language DOES NOT evaluate/execute the second operand in a condition. if the first operand alone can fully determine the outcome of that condition.

We have been using this concept in our codes always. All PHP guys must be familiar with this piece of code.

mysql_connect(localhost,$user,$password) or die( “Unable to connect”);

Yes, this is Short Circuit Evaluation! If the above code can connect to a mysql database successfully, the second operand “die” never gets executed. But if the mysql_connect function returns false, then the program dies.

Let’s take two examples to understand how it works:

if ($_POST && isset($_POST['name']) { //Do something here }

This is an AND operation and the statements inside IF block will get executed only if both the conditions are TRUE (or Truthy – It doesn’t really have to be a boolean TRUE , but just need have a value other than any Falsy values). So there is no point in evaluating the second condition if the first one is False. It stops execution if $_POST is not defined and skip the IF block.

if ($password == ” || strlen($password) < 4) { //Throw error here } Here the second operand will be only evaluated if the first condition is False that is when the $password variable is not blank.

IF-less flow control. In both the above examples, we used IF blocks. But we can actually use this Short Circuit evaluation to get rid of IFs and Elses in our code. If you look at the code of many advanced programmers, you can see that they use this Short Circuit Evaluation method to write small and clean code.

The mysql_connect example at the top is an example for OR Short Cut. Another example:

$from && $to && $msg && sendMail();

This code is equal to,

if ($from && $to && $msg) { sendMail(); }

In PHP a conditional expression only returns Boolean values. So the Result Type of these Short Cut operators are known as Boolean. See this example.

$name = ‘John’;$title = $name || “no name”; echo $title;

$title will hold a value of 1 because the expression returned a True Result. Even if the $name is false, the $title will hold a value of 1.

But in JavaScript, a conditional expression returns the last evaluated sub expression.

So the Javascript version of the above code would be different.

var name = ‘John’;var title = name || “no name”; alert(title);

This will alert “John” hence javascript returns the Last Value evaluated. This feature allows us to write more simple and cleaner code in Javascript.

var name = ‘John’;var title = name && “no name”; alert(title);

The above example (a stupid example) will alert “no name” because, the first operand “name” is Truthy and it moves on to evaluate the second expression and returns it as the “Last Value” regardless of the evaluation result.