Posts Tagged PHP

Create a TinyURL using PHP and TinyURL API

TinyURL is an awesome service. For those who don’t know what TinyURL is, TinyURL allows you to convert your long URLs like “http://www.akchauhan.com/category/jquery/” to small URLs like “http://tinyurl.com/yz4c4ba”. Basically you need such type of service when you are posting your data to some third party web service and there is limit on the number of characters you can post like Twitter. Twitter only allow 140 characters long Tweet.

Using the PHP and TinyURL API, you can create these tiny URLs.

function get_tiny_url($url)  
{  
	$ch = curl_init();  
	$timeout = 5;  
	curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url);  
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);  
	$data = curl_exec($ch);  
	curl_close($ch);  
 
	return $data;  
}
 
//test it out!
$new_url = get_tiny_url('http://www.akchauhan.com/category/jquery/');
 
//returns http://tinyurl.com/yz4c4ba
echo $new_url;

,

4 Comments


Create Random Alphanumeric Password in PHP

We can use this simple password generation function to create random passwords. The maximum limit of generated password is 36 characters.

<?php
	function gen_password($size = 8) {
		$size = $size > 36 ? 30 : $size;
		$pool = array_merge(range(0, 9), range('A', 'Z'));
		$rand_keys = array_rand($pool, $size);
 
		$password = '';
 
		foreach ($rand_keys as $key) {
			$password .= $pool[$key];
		}
 
		return $password;
	}
 
	$password = gen_password(10);
?>

We can use it like this.

<?php
	$password = gen_password(10);
?>

,

2 Comments


Create Windows Service to Schedule PHP Script execution

If you want to schedule your PHP script or any other command on Windows Platform recursively after a fix interval of time then you can create a Windows Service for it. Windows service is very easy to create in Visual Studio.Net. I’m using C# language for this scheduler service you can also use VB.net for it. Basically we need this type of service if we want to execute some PHP script in background in a specific interval of time. For example, If you want to import data in bulk from some web service.

You need to follow these steps: -

  • Create a project by using the Windows Service application template. This template creates a class for you that inherits from ServiceBase and writes much of the basic service code, such as the code to start the service.
  • Write the code for the OnStart and OnStop procedures, and override any other methods that you want to redefine.
  • Add the necessary installers for your service application. By default, a class that contains two or more installers is added to your application when you click the Add Installer link: one to install the process, and one for each associated service that your project contains.
  • Build your project.
  • Create a setup project to install your service, and then install it.
  • Access the Windows 2000 Services Control Manager and start your service.

For more detail check “Walkthrough: Creating a Windows Service Application in the Component Designer” topic in MSDN.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
 
namespace MyNewService
{
    public partial class MyNewService : ServiceBase
    {
        private Timer syncTimer = null;  
 
        public MyNewService()
        {
            InitializeComponent();
        }
 
        protected override void OnStart(string[] args)
        {
            syncTimer = new Timer();
            this.syncTimer.Interval = 180000;
            this.syncTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.syncTimer_Tick);
            syncTimer.Enabled = true;
        }
 
        protected override void OnStop()
        {
            syncTimer.Enabled = false;
        }
 
        private void syncTimer_Tick(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"C:\xampp\htdocs\task.bat");
        }  
    }
}

The task.bat file is a batch file. We are executing our PHP script through this batch file. First we set the path of directory where php.exe is located in your windows. The import.php is basically importing data in bulk from some web and we need to execute this script file background in every 3 minutes.

@echo off
cd\
set path=C:\xampp\php;
cd "C:\xampp\htdocs"
php import.php
exit

, , ,

2 Comments


How use cURL library when running PHP through Command Line

If you run any PHP code which using cURL extension through command line like this:

c:\>php somefile.php

it might give error that “curl_init()” function is not defined. The reason is the cURL extension “php_curl.dll” is not loaded. So, to resolve this issue you can load cURL (or any extension) dynamically in your PHP code. The “dl()” basically load PHP extension at runtime.

<?php
dl("php_curl.dll");
...
?>

,

No Comments


Convert XML to Array using DOM extension in PHP5

The xml2array class convert the XML stored in a string into an ARRAY. We are using the DOM extension of PHP5. The DOM extension replaced the DOM XML extension available in PHP4. The DOM XML extension is depreciated in PHP5.

<?php
class xml2array {
 
	function xml2array($xml) {
		if (is_string($xml)) {
			$this->dom = new DOMDocument;
			$this->dom->loadXml($xml);
		}
 
		return FALSE;
	}
 
	function _process($node) { 
		$occurance = array();
 
		foreach($node->childNodes as $child) {
			$occurance[$child->nodeName]++;
		}
 
		if($node->nodeType == XML_TEXT_NODE) { 
			$result = html_entity_decode(htmlentities($node->nodeValue, ENT_COMPAT, 'UTF-8'), 
                                     ENT_COMPAT,'ISO-8859-15');
		} 
		else {
			if($node->hasChildNodes()){
				$children = $node->childNodes;
 
				for($i=0; $i<$children->length; $i++) {
					$child = $children->item($i);
 
					if($child->nodeName != '#text') {
						if($occurance[$child->nodeName] > 1) {
							$result[$child->nodeName][] = $this->_process($child);
						}
						else {
							$result[$child->nodeName] = $this->_process($child);
						}
					}
					else if ($child->nodeName == '#text') {
						$text = $this->_process($child);
 
						if (trim($text) != '') {
							$result[$child->nodeName] = $this->_process($child);
						}
					}
				}
			} 
 
			if($node->hasAttributes()) { 
				$attributes = $node->attributes;
 
				if(!is_null($attributes)) {
					foreach ($attributes as $key => $attr) {
						$result["@".$attr->name] = $attr->value;
					}
				}
			}
		}
 
		return $result;
	}
 
	function getResult() {
		return $this->_process($this->dom);
	}
}
?>

We can use this class like this.

<?php
	$obj = new xml2array($XML_string);
	$XML_array = $obj->getResult();
?>

, ,

No Comments