How to Create SEO friendly URLs in PHP

This is a handy PHP code snippet which accepts a regular string as input and returns a SEO friendly slug which can become a part of a URL.

Useful Read : Export Data From MySQL table to CSV File using PHP

public function stringToSlug($string){
  //Remove white spaces from both sides of a string
  $string = trim(string);
		
  //Lower case everything
  $string = strtolower($string);
		
 //Make alphanumeric (removes all other characters)
 $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
		
 //Clean up multiple dashes or whitespaces
 $string = preg_replace("/[\s-]+/", " ", $string);
		
 //Convert whitespaces and underscore to dash
 $string = preg_replace("/[\s_]/", "-", $string);
		
 return $string;
}

 

Export Data From MySQL table to CSV File using PHP

CSV  stands for  Comma separated values. It is one of the most widely used format to transfer data from one application to another in a tabular form. In this post, we are going to learn to export the data from database to a CSV file.

Quick Tip : PHP script to extract zip files

The Script:

<?php 
//Connect and select a database
mysql_connect('localhost','root','');
mysql_select_db('webapp');

//Output headers to make file downloadable
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=spreadsheet.csv');

//Write the output to  buffer
$data = fopen('php://output', 'w');

//Output Column Headings
fputcsv($data,array('Name','Email Address'));

//Retrieve the data from database
$rows = mysql_query('SELECT name, email FROM users');

//Loop through the data to store them inside CSV
while($row = mysql_fetch_assoc($rows)){
	fputcsv($data, $row);
}

As you can see, on line 3 and 4, we are connecting our script with the database. Then, on line 7 we are producing HTTP headers to specify the MIME type of the file which is text/csv. On the next line, we have set the Content-Disposition to attachment to make the file downloadable and spreadsheet.csv is the name of the file which will be downloaded.

Line 11 creates a write-only output stream which allows us to write the data to the buffer. On line 14, we are printing column headings which in out case are Name and Email Address,  you can change them as per your requirement. And on line 17, we are retrieving the data from database using a simple MySQL query.

And online 20 and 21, we are looping through retrievedthe data and writing it to our output stream.

I hope you enjoyed the tutorial and fount it useful. In case you have any query, feel free to comment.

PHP Script to Fetch the Alexa Rank of a Website

Basically, Alexa rank is the frequency of visits on a particular website. Lower Alexa rank means more traffic volume to that website. Its ranking system is based on information collected from users who have installed its toolbar.

In this post, I will show you to fetch the Alexa rank of a particular website using a simple PHP script. To get the alexa rank, all you need to do is pass the URL of website to getAlexaRank() function. The function will return the rank which can be further stored inside a variable or in the database, or can be simple displayed on screen.

//PHP Script to Fetch Alexa Rank
function getAlexaRank($url){
	$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
	$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
	return $rank;
}
echo getAlexaRank('http://coffeecupweb.com');

Useful Read: Unzip a file with php

How to get youtube video ID from url using php?

Here’s a handy PHP code snippet which allows you to extract the video ID of a YouTube video from URL. All you need to do is pass the YouTube URL to the getYouTubeId() function.

Quick Tip : Unzip a file with php

//get video id from youtube url
function getYouTubeId($url){
	parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
	return $my_array_of_vars['v'];
}
echo getYouTubeId('https://www.youtube.com/watch?v=y2Ky3Wo37AY');

The Above code will output,

y2Ky3Wo37AY

 

How to get Facebook likes count of a page using Graph API

Due to change in Facebook API this code snippet doesn’t work any longer. Click Here for solution.

Facebook’s graph API is the simplest way to get the like count of a Facebook page. Using the following code snippet you can grab the like count of a particular Facebook page and display it on your website.

All you need to do is pass Username or id of the page,

//Get Facebook Likes Count of a page
function fbLikeCount($id){
	//Construct a Facebook URL
	$json_url ='https://graph.facebook.com/'.$id.'';
	$json = file_get_contents($json_url);
	$json_output = json_decode($json);
 
	//Extract the likes count from the JSON object
	if($json_output->likes){
		return $likes = $json_output->likes;
	}else{
		return 0;
	}
}
//This Will return like count of CoffeeCupWeb's Facebook page
echo fbLikeCount('coffeecupweb');

Useful Read: How to Add the Facebook Like Box / Fan Box in WordPress

How to execute PHP code in Text Widget without using Plugin.

By default, WordPress doesn’t allow you to execute the PHP code within the text widget. But, you can easily fix this problem by adding a small amount of code to your functions.php file.

To enable PHP code within WordPress text widget, paste the following code in your functions.php file located inside your theme directory.

//Execute PHP code in WordPress text widget
function execute_php_text_widget($html){
	if(strpos($html,"<"."?php")!==false){ 
		ob_start(); 
		eval("?".">".$html);
		$html=ob_get_contents();
		ob_end_clean();
	}
	return $html;
}
add_filter('widget_text','execute_php_text_widget',100);

Now, to test whether the code is working correctly or not, paste a simple Hello World! program inside a text widget.

//Hello World
<?php echo "Hello World!" ?>
execute php code inside a WordPress text widget without using a plugin

Execute php code inside a WordPress text widget without using a plugin

If you have done everything correctly, you will be able to see the output similar to one shown in the image below,

execute php code inside a WordPress text widget without using a plugin

Execute php code inside a WordPress text widget without using a plugin

Useful Read: How to Use Shortcodes in WordPress Text Widgets?

How to create a zip file in php?

In one of my previous post, We  have already seen How we can extract Zip Files using PHP. In this tutorial, we are going to create a Zip file with PHP. To perform this task, we are going to use a built-in extension in PHP known as ZipArchive classs.

This is a very basic PHP function which accepts two parameters array of files to be zipped and name of zip file to be created.

//Creating a Zip File Using PHP
function genZip($files = array(),$zipName){
	$zip = new ZipArchive();
	$zip->open($zipName.'.zip', ZipArchive::CREATE);
	foreach($files as $file){
		$zip->addFile($file);
	}
	$zip->close();
}

Usage:

//Usage of genZip function
$files = array(
		'file1.pdf',
		'file2.pdf',
		'file3.pdf',
		'folder2/file4.pdf',
		'folder2/file5.pdf'
	);
$zipName = 'myfiles';
genZip($files,$zipName);

How to extract Zip Files with PHP?

In the previous post, we have created a random alphanumeric password generator script. In this post, I will show you, how to extract zip/compressed files using PHP. PHP has built-in extensions for dealing with compressed files.

Quick Tip : Simple PHP Password Generator

Following PHP function can be used to unzip the compressed files. It accepts two parameters, source i.e full path to zip file and destination i.e path to which files will be extracted.

<?php
//extract a file with php
function extractZip($src,$dest){
	$zip = new ZipArchive;
	$res = $zip->open($src);
	if ($res === TRUE) {
		$zip->extractTo($dest);
		$zip->close();
		echo 'Files Extracted Successfully!';
	} else {
		echo 'Extraction Failed!';
	}
}

$src = "zip/file.zip";
$dest = "extractedfile/1/";
echo extractZip($src,$dest);
?>

Author: rdlowrey

Source: Stack Overflow

Simple PHP Password Generator

When building web based applications, often you need to generate passwords for users. This is a simple PHP script which allows you to generate random passwords.

Useful Read: Get Current Page URL

<?php
/**
 * Generates random passwords.
 * @param   int  Password Length (Default : 10)
 * @return  Random String
 * @author  Harshal Limaye (http://coffeecupweb.com/)
 */
function genPass($len = 10) {
    $charPool = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array();
    $length = strlen($charPool) - 1;
    for ($i = 0; $i < $len; $i++) {
        $n = rand(0, $length);
        $pass[] = $charPool[$n];
    }
    return implode($pass);
}
echo genPass();
?>

 

How to Get the Current Page URL in PHP?

When developing PHP based web application,  sometimes you need to grab the URL of current page.  Using the following PHP code snippet you will be able to get the URL of current webpage.

Useful Read: PHP Age Calculator

<?php
/**
 * Grabs and returns the URL of current page.
 * @param   none
 * @return  URL of current page
 */
function grabCurrentURL(){
	if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
		$url = "https://";
	}else{
		$url = "http://";
	}
	$url .= $_SERVER['SERVER_NAME'];
	if($_SERVER['SERVER_PORT'] != 80){
		$url .= ":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	}else{
		$url .= $_SERVER["REQUEST_URI"];	
	}
	return $url;
}

echo grabCurrentURL();
?>