Create URL Slug from Post Title using PHP

The following functions will helps to create search engine optimization url for the website. This will strip all the special characters and punctuation away from the URL and place hyphen in between each words.

For acheving the required results, used regular expression function that replaces spaces between words with hyphens and its remove the special characters from string or post title provided as input to fundtion.

Javascript function which helps to create slug url and place the created slug value in the given place holder.

[js]
/**
* Jquery stringToSlug plugin
* @param {Object} options
* Options will contains the trigger action on specified event and place holder for slugging text box.
*/
jQuery.fn.stringToSlug = function(options) {
var defaults = {
setEvents: ‘keyup keydown blur’, //set Events that your script will work
replace: ‘#permalink’
};

var opts = jQuery.extend(defaults, options);

jQuery(this).bind(defaults.setEvents, function () {
var stringToSlug = jQuery.trim(jQuery(this).val()).replace(/\s+/g,’-‘).replace(/[^a-zA-Z0-9\-]/g,”).toLowerCase().replace(/\-{2,}/g,’-‘);
jQuery(defaults.replace).val(stringToSlug);
return this;
});

return this;
};

$(document).ready(function() {
// You can define which textbox value need to create as slug and also event also you can provide in options
$("#Post_name").stringToSlug({replace: ‘#Post_link’});
// #Post_name is the ID of the textbox which contain string with / without special characters.
// #Post_link is the ID of the textbox to display the link generated based on the text given in #Post_name. #Post_link textbox should be read only, then only user will not update the link details.
});
[/js]

It is server side URL slug creation method, in this method also will strip all the special characters and punctuation away from the URL and place hyphen in between each words.

[php]
/**
* Create Slug from title
* @param $string
*/
function createSlug($string){
$slug = strtolower(preg_replace(array(‘/[^a-zA-Z0-9 -]/’, ‘/[ -]+/’, ‘/^-|-$/’), array(”, ‘-‘, ”), trim($string)));
return $slug;
}
[/php]

For example:
[php] echo createSlug(“US Dollar $ convertion into INR, $1 = RS. ?”); [/php]

output:
[code] us-dollar-convertion-into-inr-1-rs[/code]

Thanks for reading this post. Share your comments, which will help me to improve posting blog.

Permanent link to this article: https://blog.openshell.in/2014/08/create-url-slug-from-post-title-using-php/

Best way to order the best matching records in MySQL

If we are searching a word (string) in the mysql table, usually we will use the below method:

[sql]
SELECT * FROM user WHERE name LIKE ‘%searchstring%’ ORDER BY name ASC;
[/sql]

If you search like this, It will order the result set based on the ASC of name. It will not order the result set based on the string found at the beginning, middle and last position.

For Example:

If you are searching for name as “KRISHANA” in user table, from the following records:

1) ANANDA KRISHNAN
2) KRISHANA MORTHI
3) GEETHA RAMA KRISHANAN
4) KRISHANA

It will display the result set as below:

1) ANANDA KRISHNAN
2) GEETHA RAMA KRISHANAN
3) KRISHANA
4) KRISHANA MORTHI

But best matching record should always display on top of the resultset. To display the resultset based on matching string at position of beginning, middle and last. Follow the below steps:

[sql]
SELECT name
FROM users
WHERE name LIKE ‘%KRISHNA%’
ORDER BY
CASE
WHEN name LIKE ‘KRISHNA%’ THEN 1
WHEN name LIKE ‘%KRISHNA%’ THEN 2
ELSE 3
END
[/sql]

Output:
As the result of the Query, The resultset will be like this:

1) KRISHANA
2) KRISHANA MORTHI
3) ANANDA KRISHNAN
4) GEETHA RAMA KRISHANAN

It Will automatically sort the record based on best matching string. Thanks for reading this post, If you have any ideas or comments please share it.

Permanent link to this article: https://blog.openshell.in/2014/08/best-way-to-order-the-best-matching-records-in-mysql/

How to save an image of the highcharts on the server?

Highcharts have a built-in option to export the current chart, it have the option to save the chart as PNG, JPEG, PDF or SVG.

It doesn’t have option to save the image on the server, instead of downloading in browser (clinet).

To save an image of the highcharts on the server, follow the steps:

Step 1: Create file as “highcharts.php” and save the following code:

[html]
<!– Javascript SVG parser and renderer on Canvas, used to convert SVG tag to Canvas –>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>

<!– Hightchart Js –>
<script src="http://code.highcharts.com/highcharts.js"></script>

<!– Highchart container –>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

<!– canvas tag to convert SVG –>
<canvas id="canvas" style="display:none;"></canvas>

<!– Save chart as image on the server –>
<input type="button" id="save_img" value="saveImage"/>

<script type="text/javascript">
$(function () {
$(‘#container’).highcharts({
……………..
……………..
……………..
});

$("#save_img").click(function(){
var svg = document.getElementById(‘container’).children[0].innerHTML;
canvg(document.getElementById(‘canvas’),svg);
var img = canvas.toDataURL("image/png"); //img is data:image/png;base64
img = img.replace(‘data:image/png;base64,’, ”);
var data = "bin_data=" + img;
$.ajax({
type: "POST",
url: savecharts.php,
data: data,
success: function(data){
alert(data);
}
});
});
});

</script>
[/html]

Step 2: Create savecharts.php and save the following code, to save the highcharts on the server.

[php]
<?php

$data = str_replace(‘ ‘, ‘+’, $_POST[‘bin_data’]);
$data = base64_decode($data);
$fileName = date(‘ymdhis’).’.png’;
$im = imagecreatefromstring($data);

if ($im !== false) {
// Save image in the specified location
imagepng($im, $fileName);
imagedestroy($im);
echo "Saved successfully";
}
else {
echo ‘An error occurred.’;
}
[/php]

For Reference: https://code.google.com/p/canvg/

Permanent link to this article: https://blog.openshell.in/2014/08/how-to-save-an-image-of-the-highcharts-on-the-server/

How to create the JAR file

The JAR file format is a compressed format used primarily to distribute Java applications and libraries. It is built on the ZIP file format, and functions in a similar way; many files are compressed and packaged together in a single file, making it easy to distribute the files over a network. If you need to package a Java application or library, you can create a JAR file using the Java Development Kit (JDK) and your computer’s command prompt.

Step 1:

Put all the files you want to include in the JAR file inside a single folder.

Step 2:

Open a Terminal command prompt, and set it to the target directory where your JAR files are located.

Step 3:

Run the following command in the terminal to make jar file,

[code]jar cfv HelloWorld.jar HelloWorld.class[/code]

The basic commands for creating the JAR file.

[code]jar cf jar-file.jar input-file(s)[/code]

The options and arguments used in this command are:

The “jar” portion refers to the jar.exe program, which compiles the JAR file.
The “c” option specifies that you want to create a JAR file
The “f” option means that you want to specify the filename.
The “jar-file” portion is where you should type the name that you want the file to have.
“Input-file(s)” is a space-separated list of all the files to be included in the JAR file.

Permanent link to this article: https://blog.openshell.in/2014/08/how-to-create-the-jar-file/

How to install maven on Ubuntu

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project’s build, reporting and documentation from a central piece of information.

This will helps you to install Apache Maven 3 on ubuntu.

Follow the steps to install:

Step1: Before you can install Maven you’ll need to update your repository details on your machine, simply run the following command in Terminal.

sudo apt-get update

Step2: To get all the available Maven package details run the command in a terminal.

apt-cache search maven

You will get output like this:

libapache-pom-java – Maven metadata for all Apache Software projects
libcommons-parent-java – Maven metadata for Apache Commons project
maven-ant-helper – helper scripts for building Maven components with ant
maven-repo-helper – Helper tools for including Maven metadata in Debian packages

Step3: Install maven package, run the following command.

sudo apt-get install maven

Step4: Once your installation completed, you can verify the installed maven package version.

mvn -version

You will the following output as results:

Apache Maven 3.0.4
Maven home: /usr/share/maven
Java version: 1.7.0_65, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-7-oracle/jre
Default locale: en_IN, platform encoding: UTF-8
OS name: “linux”, version: “3.2.0-67-generic”, arch: “amd64”, family: “unix”

Maven package where installed on, /usr/share/maven

Step5: Maven configuration files where stored in following location.

$ ls -lsrt /etc/maven/
total 16
12 -rw-r–r– 1 root root 10224 Jan 21  2012 settings.xml
4 -rw-r–r– 1 root root   184 Jan 21  2012 m2.conf

Now, Maven was successfully installed on your machine.

Permanent link to this article: https://blog.openshell.in/2014/08/how-to-install-maven-on-ubuntu/

How To Install Apache Tomcat 8 on Ubuntu

Apache Tomcat is an open source web server used to deploy and serve JavaServer Pages (JSP) and Java Servlets.

This will helps you to install Apache Tomcat 8, Apache Tomcat 8 now has its first stable release: 8.0.9.

Follow the steps to install Apache Tomcat 8 on Ubuntu:

Step 1: Install Java 7

Before you can install Tomcat you’ll need to install the Java Development Kit (JDK) 7. First let’s check to see if Java is installed:

java -version

If that returns the following then Java hasn’t yet been installed:

The program ‘java’ can be found in the following packages:

To install Java, simply run the following command (and at the prompt enter Y to continue):

apt-get install openjdk-7-jdk

Step 2: Install Tomcat from Binary

First, head-on-over to the Apache Tomcat 8 Download site.

Then, under the heading 8.0.9 (the current version as of July 2014), or whichever is the newest version at the time you read this article, you’ll see Binary Distributions. Under Binary Distributions you’ll see Core and then tar.gz. Right click on tar.gz and copy the URL.

From your server, download Apache Tomcat 8 from the URL you copied in the previous step:

wget http://mirrors.ibiblio.org/apache/tomcat/tomcat-8/v8.0.9/bin/apache-tomcat-8.0.9.tar.gz

After the download completes, decompress the file:

tar xvzf apache-tomcat-8.0.9.tar.gz

Now, move the file into a proper location:

mv apache-tomcat-8.0.9 /opt/tomcat

Step 3: Configure .bashrc

Now let’s set the environment variables in .bashrc:

vim ~/.bashrc

Note: If you have questions about Vim, check out our new user tutorial on Vim!

Add this information to the end of the file:

export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
export CATALINA_HOME=/opt/tomcat

Simply save and exit .bashrc, then make the changes effective by running the following command:

. ~/.bashrc

Step 4: To start Apache tomcat server

Tomcat and Java should now be installed and configured on your server. To activate Tomcat, run the following script:

$CATALINA_HOME/bin/startup.sh

You should get the output as similar to:

Using CATALINA_BASE: /opt/tomcat
Using CATALINA_HOME: /opt/tomcat
Using CATALINA_TMPDIR: /opt/tomcat/temp
Using JRE_HOME: /usr/lib/jvm/java-7-openjdk-amd64/
Using CLASSPATH: /opt/tomcat/bin/bootstrap.jar:/opt/tomcat/bin/tomcat-juli.jar
Tomcat started.

Verify that Tomcat is working by visiting the server ip address:8080. For example: http://127.0.0.1:8080 or http://wbsrvr1:8080

 

Permanent link to this article: https://blog.openshell.in/2014/08/how-to-install-apache-tomcat-8-on-ubuntu/

How to uninstall Software packages from Eclipse editor

The Uninstall wizard allows you to review and uninstall software package in your eclipse editor. This wizard is shown when you selected software package and press Uninstall from the Installed Software page.

To uninstall software from your system:

1) Click Help > About Eclipse and then click command link Installation Details button in opened dialogue page.

2) It will open another dialogue page that provide more detail about your installation of software package in your eclipse editor.

3) Click the Installed Software tab to see a list of the software items that you have installed into your eclipse editor.

4) Select the Software package that you wish to uninstall, Click Uninstall… button. The Uninstall Details page will show you a list of the items that will be uninstalled. Expanding each item will show what additional items (if any) will be uninstalled as a result of your choice. If you change your mind about which items should be uninstalled, you may click Back to see a checkmark list of the items you selected before. You may check and uncheck different items in the list, and click Next when you are ready to continue.

5) Click Finish to start the uninstall, Once all of the software is uninstalled successfully, you will be prompted to restart for the Workbench. Click Yes when asked to exit and restart the Workbench for the changes to take effect.

Permanent link to this article: https://blog.openshell.in/2014/08/how-to-uninstall-software-packages-from-eclipse-editor/

How to use NuSOAP Toolkit for PHP

NuSOAP is a rewrite of SOAPx4, provided by NuSphere and Dietrich Ayala. It is a set of PHP classes – no PHP extensions required – that allow developers to create and consume web services based on SOAP 1.1, WSDL 1.1 and HTTP 1.0/1.1. Clik here to can download NuSOAP Toolkit for PHP.

Steps to use NuSOAP Toolkit:

Step1: Download NuSOAP Toolkit

Step2: Extract the downloaded NuSOAP Toolkit folder into your project location under library folder.

Step3: Include the NuSOAP PHP library file into your application file like this “require_once ‘lib/nusoap.php'”. Now you are ready to use NuSOAP library file into your project.

Method 1:

[php]
// include nusoap class file
require_once(‘lib/nusoap.php’);

// invoke webservice url
$client = new nusoap_client("http://test.wsdl.com/soap2?wsdl", $wsdl = true);

// detect any error occured while invoke webservice
$err = $client->getError();

if ($err) {
echo ‘<h2>Constructor error</h2><pre>’ . $err . ‘</pre>’;
echo ‘<h2>Debug</h2><pre>’ . htmlspecialchars($client->getDebug(), ENT_QUOTES) . ‘</pre>’;
exit();
}

// parameters for webservice method
$params = array(
‘manufacturer’ => "O’Reilly",
‘mode’ => ‘books’,
‘name’ => ‘lets c’,
);

// invoke webservice method with respective parameters
$result = $client->call(‘SearchRequest’, $params);

// detect if any error occured
if ($client->fault) {
echo ‘<h2>Fault (Expect – The request contains an invalid SOAP body)</h2><pre>’;
print_r($result); echo ‘</pre>’;
} else {
$err = $client->getError();
if ($err) {
echo ‘<h2>Error</h2><pre>’ . $err . ‘</pre>’;
} else {
echo ‘<h2>Result</h2><pre>’;
print_r($result); echo ‘</pre>’;
}
}

// to view SOAP webservice request XML
echo ‘<h2>Request</h2><pre>’ . htmlspecialchars($client->request, ENT_QUOTES) . ‘</pre>’;
// to view SOAP webservice response XML
echo ‘<h2>Response</h2><pre>’ . htmlspecialchars($client->response, ENT_QUOTES) . ‘</pre>’;
// to view SOAP webservice response result in step by step, it helps to debug
echo ‘<h2>Debug</h2><pre>’ . htmlspecialchars($client->getDebug(), ENT_QUOTES) . ‘</pre>’;
[/php]

Method 2:

[php]
// include nusoap class file
require_once(‘lib/nusoap.php’);

// invoke webservice url
$client = new nusoap_client("http://test.wsdl.com/soap2?wsdl", $wsdl = true);
$client->soap_defencoding = ‘utf-8’;
$client->useHTTPPersistentConnection(); // Uses http 1.1 instead of 1.0

// detect any error occured while invoke webservice
$err = $client->getError();

if ($err) {
echo ‘<h2>Constructor error</h2><pre>’ . $err . ‘</pre>’;
echo ‘<h2>Debug</h2><pre>’ . htmlspecialchars($client->getDebug(), ENT_QUOTES) . ‘</pre>’;
exit();
}

$request_xml = ‘
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<username>username1</username>
<password>test1234</password>
</soapenv:Header>
<soapenv:Body>
<m:processRequest>
<sOAPElement>
<searchRequest>
<query>books</query>
</searchRequest>
</sOAPElement>
</m:processRequest>
</soapenv:Body>
</soapenv:Envelope>
‘;

// invoke webservice with data
$result = $client->send($request_xml);

// detect if any error occured
if ($client->fault) {
echo ‘<h2>Fault (Expect – The request contains an invalid SOAP body)</h2><pre>’;
print_r($result); echo ‘</pre>’;
} else {
$err = $client->getError();
if ($err) {
echo ‘<h2>Error</h2><pre>’ . $err . ‘</pre>’;
} else {
echo ‘<h2>Result</h2><pre>’;
print_r($result); echo ‘</pre>’;
}
}

// to view SOAP webservice request XML
echo ‘<h2>Request</h2><pre>’ . htmlspecialchars($client->request, ENT_QUOTES) . ‘</pre>’;
// to view SOAP webservice response XML
echo ‘<h2>Response</h2><pre>’ . htmlspecialchars($client->response, ENT_QUOTES) . ‘</pre>’;
// to view SOAP webservice response result in step by step, it helps to debug
echo ‘<h2>Debug</h2><pre>’ . htmlspecialchars($client->getDebug(), ENT_QUOTES) . ‘</pre>’;

[/php]

To extract the response result from the SOAP webservice, follow the below steps:

[php]

// invoke webservice with data
$result = $client->send($request_xml);

// invoke webservice method with respective parameters
$result = $client->call(‘SearchRequest’, $params);

// by using both method you will get the results in $results variable, to view the results of webservice
echo ‘<h2>Result</h2><pre>’;
print_r($result); echo ‘</pre>’;

// To get attribute value of XML node
echo $result[‘searchResponse’][‘books’][‘!ID’];

// To get XML node value
echo $result[‘searchResponse’][‘books’][‘author’];

[/php]

If you have any queries on the above code, Please drop your comments.

Permanent link to this article: https://blog.openshell.in/2014/07/how-to-use-nusoap-toolkit-for-php/

How to use MySQL for case sensitive string comparison

By default MYSQL character set and collation are latin1 and latin1_swedish_ci, so non-binary string comparisons are case insensitive. This means that if you search with col_name LIKE ‘a%’, you get all column values that start with A or a. To make this search as case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

i.e,

If you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation

[code]
col_name COLLATE latin1_general_cs LIKE ‘value%’
col_name LIKE ‘value%’ COLLATE latin1_general_cs
col_name COLLATE latin1_bin LIKE ‘a%’
col_name LIKE ‘value%’ COLLATE latin1_bin
BINARY col_name = ‘value’
[/code]

Your SQL Query will be look like this to make a case-sensitive query

[code]
SELECT * FROM table_name WHERE BINARY column_name = ‘value’;

SELECT * FROM table_name WHERE col_name COLLATE latin1_general_cs LIKE ‘value%’;

SELECT * FROM table_name WHERE col_name LIKE ‘value%’ COLLATE latin1_general_cs;
[/code]

If you want a column always to be treated in case-sensitive manner, then declare it with a case sensitive or binary collation while creating your table.

For Reference:
http://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html

Permanent link to this article: https://blog.openshell.in/2014/07/how-to-use-mysql-for-case-sensitive-string-comparison/

phpmyadmin – Cannot start session without errors, please check errors

Unfortunately sometimes we get the problem with phpMyAdmin, here is the error from phpMyAdmin on ubuntu machine.

phpMyAdmin – Error

[code]
Cannot start session without errors, please check errors given in your PHP and/or webserver log file and configure your PHP installation properly.
[/code]

To find out where the session.save path
http://wiki.phpmyadmin.net/pma/session.save_path

run this script on your web server

[php]
<?php
// save as "session_test.php" inside your webspace
ini_set(‘display_errors’, ‘On’);
error_reporting(6143);

session_start();

$sessionSavePath = ini_get(‘session.save_path’);

echo ‘<br><div style="background:#def;padding:6px">’
, ‘If a session could be started successfully <b>you should’
, ‘ not see any Warning(s)</b>, otherwise check the path/folder’
, ‘ mentioned in the warning(s) for proper access rights.<hr>’;

if (empty($sessionSavePath)) {
echo ‘A "<b>session.save_path</b>" is currently’,
‘ <b>not</b> set.<br>Normally "<b>’;
if (isset($_ENV[‘TMP’])) {
echo $_ENV[‘TMP’], ‘</b>" ($_ENV["TMP"]) ‘;
} else {
echo ‘/tmp</b>" or "<b>C:tmp</b>" (or whatever’,
‘ the OS default "TMP" folder is set to)’;
}
echo ‘ is used in this case.’;
} else {
echo ‘The current "session.save_path" is "<b>’,
$sessionSavePath, ‘</b>".’;
}

echo ‘<br>Session file name: "<b>sess_’, session_id()
, ‘</b>".</div><br>’;
?>
[/php]

If you get error like this

[code]
Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/lib/php) in Unknown on line 0
[/code]

Follow the instruction to fix this issue:

[code]sudo vim /etc/php/apache2/php.ini[/code]

Find the session.save_path, if the folder doesn’t exist, create one.

[code]mkdir /var/lib/php/session[/code]

You may have to change ownership of the directly

[code]chown user:group /var/lib/php/session[/code]

Or just need to change the permissions to readable and writable for the directory

[code]chmod 0777 /var/lib/php/session[/code]

Note: /var/lib/php/session ownership and permissions well reverse back to root and not writable after a reboot. It’s a good idea to run chmod and chown @reboot so you don’t have to do it manually.

Once fixed this issue, run the script on your web server.

Here is the Output,

[code]The current "session.save_path" is "/var/lib/php/session".[/code]

If you get above output, phpmyadmin issue has resolved. Now you can start using phpmyadmin on your webserver.

Permanent link to this article: https://blog.openshell.in/2014/06/phpmyadmin-cannot-start-session-without-errors-please-check-errors/