Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Wednesday, March 25, 2015

Singleton Design Pattern in PHP Example

Singleton Pattern
Hello! As we all know that, design patterns used to solve any issue in software engineering. All of design patterns have typical skills. For example, in the singleton pattern a class can distribute one instance of itself to other classes. In this article I'll show you how to design a PDO database class using singleton design pattern in PHP programming language.





//singleton design pattern
class DB {
 
 private static $status = NULL;
 private static $info = 'mysql:host=localhost;dbname=dbname';
 private static $username = 'username';
 private static $password = 'password';
 
 private function __construct() { }
 
 public static function connect() {
  if(!self::$status) {
   try {
    self::$status = new PDO(self::$info, self::$username, self::$password);
    self::$status->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    self::$status->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
   }
   catch (PDOException $e) {
    throw new Exception($e->GetMessage()); 
   }
  }
  return self::$status;
 }
 
 public function __destruct() {
  self::$status = NULL; 
 }
}

First, We define status as a static variable, because we want to control whether connection is exists via only one variable. Aftet that define database information as private static variables. After all we create our connection static function, that is connect().

Here is the way is actually, if status variable is not null, code try to connect PDO database, otherwise connection is exists and will return true,NOT null.
Finally, in destruct function, connection has been closed by null value. When we want to connect database, we call the singleton like:
DB::connect();
If class has any other function, then like:
DB::connect()->functionName($param);

See you!

Saturday, March 8, 2014

Sending Data to MySQL Database Using PHP With Unity3D Game Engine

Hello everyone, In this article, I will share an Unity3D game engine example with you guys. We will imagine that we have got a game has been played and opened score scene. This step will be sharing platform for scores between users. At this stage score information will be taken and posted to PHP page for sending to MySQL database. For these steps, we'll need these digital materials and tools given below:
  • An empty scene in the Unity3D game engine and Main Camera
  • An JavaScript scripting file for posting data to PHP page
  • An table named highscore in the MySQL database
  • An Server that can work PHP programming language

First, we will add javascript file to Main Camera Inspector in the empty scene.

function send(data, username) {
    var form = new WWWForm();
    form.AddField("action", "send");
    form.AddField("score", data);
        form.AddField("username", username);
    var url = "http://localhost/unity/send.php";
    var w = WWW(url, form);
    yield w;
}

send(999, "phpservisi");

Codes given above send score information to send.php PHP file for saving MySQL database. WWWForm object has been created for outside connection. This object has got action attribute and send value. This value will be used in PHP file as a condition to send MySQL database. score attribute's value is going to share with other players. For that reason we need all attribute, variable and values. Url variable shows us what will we use for target POST URL information.

Just remember that you have to add this JavaScript file to Main Camera's Inspector part using Add Component.

Now, we can finally create our PHP file for saving datas to MySQL DATABASE. But first create highscore table in the MySQL: 


Let's get PHP file:

mysql_connect("localhost","username","password");
mysql_select_db("database_name");
 
if($_REQUEST['action']=="send") {
$score = $_REQUEST['score'];
$username = $_REQUEST['username'];
$query = "INSERT INTO `highscore` (username, score) VALUES ('$username', '$score')";
mysql_query($query);

From on now, we can send our score data to PHP file for saving database, when the game run. send function helps us to POST datas. username and score datas are used via JavaScript file in the Unity3D game engine. $score and $username variables came from JavaScript file as you have known. After this we just use
SQL query.



As result, we have just done sent datas to MySQL database using PHP programming language with Unity3D game engine JavaScript codes. This article will be helpful. Because if you want to create a game for muliplatform, you have to develop multiplatform.

See you guys next articles!

Saturday, January 4, 2014

How to Generate Search Engine Friendly URL - SEF LINK

Hi! I will talk about making web site optimized for search engines. SEF link stands for Search Engine Friendly words in English language. This concept makes structure of web sites better and user friendly. For example imagine that a database on your server. You want to show products from the table in the database. In general, we developers get data with field of the table and use it like id=1 URL structure. Because that is so simple. But this showing is not understandable and useful for search engines, Google, Yahoo, Yandex etc. That's the point we should get SEF links!

programming_language.php?id=1


The URL given above us POST global id variable and returns 1 value. Yes, this is functional. Because after this step, we'll just make that query given below for getting datas:

SELECT * FROM table_name WHERE id=1


But we all know that the uses of the above is suck for nowadays. For that reason, we need to get URL given below:

programming-language-php.html
php-programming-language


We have to create a .htaccess file on the server side for generating an URL for above, that goes:

Options +FollowSymLinks
RewriteEngine On
ReWriteRule (.*) programming_language.php?id=$1 [L, QSA]


.htaccess file runs programming_language.php page and gets id value as SEF structure in the (.*) statement. According to these conditions lets make a PHP file for using SEF!

$var = $_POST["id"]; //getting URL data with using POST global variable
echo $var;


When we run the PHP page as www.whateverstdioe.com/php, we can see php on the screen. Because of there is a similarity between www.whateverstdioe.com/php and www.whateverstdioe.com/id=php. See you next article!

Tuesday, August 20, 2013

Redirect Mobile Devices Using PHP

Hi everyone!

Today, I want to share this useful article with you. This article is going to be about redirecting mobile devices with PHP programming language. I am sure that you will need it.
If you have your own web site or something else, It means that you have members, users or followers on your site. Sure, we should remember that most of people uses mobile devices. Internet, social media, game or some applications etc, and we know that they visit your web site from their mobile devices. For that reason if we put this special feature on, we get more quality site of course.
As I said the title, I am doing this using PHP. So, let me show you:
//just define user's agents (iphone or android)
$iphoneDevice  =  strpos($_SERVER['HTTP_USER_AGENT'], "iPhone");
$androidDevice =  strpos($_SERVER['HTTP_USER_AGENT'], "Android");

if($iphoneDevice) {
    print "Your device is iphone!";
}

if($androidDevice) {
    print "Your device is android, you can download Fast Boy Game 
Application from Play Google
"; print " FAST BOY"; }

That's it. If the user use iphone, will see "Your device is iphone!" message on the screen, if use android device,
Your device is android, you can download Fast Boy Game 
Application from Play Google
FAST BOY (clickable)

If you want to put more features on your web site, for example blackberry, webos or ipod, you can use already.
$webOSDevice      = strpos($_SERVER['HTTP_USER_AGENT'], "webOS");
$BlackBerryDevice = strpos($_SERVER['HTTP_USER_AGENT'], "BlackBerry");
$ipodDevice       = strpos($_SERVER['HTTP_USER_AGENT'], "iPod");
The code given above shows us other devices and brands.
We will see you next article!

Monday, August 19, 2013

How To Create Scheduled Jobs With Crontab in Linux

Hi everyone!


In this article, I want to talk about cronjob. Some of us heard about this subject before. Cronjob scheduled task used in the sense of is very important for us. Because you can use it everytime you have to set some scripts will run next date. So, imagine that you have got a web site there are so many users on it. If you want to send e-mail to all your members at 02:00 am, here is the time you need cronjob!

Some hosting companies offer to manage cronjob service, but not all. Because of it is every hosting have not CPanel. Maybe you can use SSH or something else. Me, show you how to manage cronjob using SSH. In this regard, open your Unix Server using SSH, and;

vi /etc/crontab

* * * * * ( [minute] [hour] [day] [month] [day of the week] )
┬ ┬ ┬ ┬ ┬
│ │ │ │ │
│ │ │ │ │
│ │ │ │ └───── day of the week (0 – 7) (total 7 days)
│ │ │ └────────── month (1 – 12)
│ │ └─────────────── day (1 – 31)
│ └──────────────────── hour (0 – 23)
└───────────────────────── minute (0 – 59)

//test.php file
$db->query("INSERT INTO db_name.table_name(field_name) values('test')");
 
#cronjob file
* * * * * username php test.php

The code given above shows us the script that adds data to the database every minutes.
*/15 * * * * username php test.php

The code given above also shows us the script that adds data to the database every 15 minutes.
#02:00am at night
00 02 * * * username php test.php
 
#every 3 hours during the day
0 */3 * * * username php test.php
 
#each hour
0 * * * * username php test.php
 
#4 pm o'clock on the 15th day of each month
00 16 15 * * username php test.php
 
#weeks every night at 2 am
00 02 * * 1-5 username php test.php
 
#every hour every Sunday
0 * * * sun
 
#every 3 hours
0 2,5,8,11,14,17,20,23 * * * username php test.php

The codes given above shows us different cronjob examples. You can try and work for creative and usefull cronjob examples.
We'll see you guys next article!

Friday, July 5, 2013

CURL Requests With PHP

Hello,
Most developers prefer to use HTTP Request / Response service in their projects. In this situation, you have to send data as POST method to the opponent.

Imagine that you are a web master of your own e-commerce web site. Members of the site use coupon during check out. In these conditions, you may connect to other systems, for example the store which is in another sector, and have to validate if the coupon is correct or something like that. Here is the magnificent specimen of pure one of the best example in the world for this article :)

If you want, let's code CURL for now!

For this, I set a service up for posting data: service.php
if(isset($_POST['field'])) {
    print "Field is: ".$_POST['field'];
}
else {
    print "Field is blank!";    
}
Like you've just seen above, the service is waiting for field post variable on it. If you send a field data, the screen is going to be like,

Field is your field value
But else,

Field is blank!
I suppose to send a field value to the service: myfile.php

//display error
ini_set('display_errors', 1);
 
//curl
$ch = curl_init("http://localhost/CURL/service.php");
 
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'field=phpservisi.com');
 
curl_exec($ch);
curl_close($ch);
If I run the myfile.php page, just going to see on on the screen like,

Field is phpservisi.com
For this example, I used a page which was http protocol. But sometimes I need use to https. In these conditions,have to add this line on it,

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
There are so many settings and options in CURL. If you want to check it out, you can visit PHP official page, here

See you next articles!

Thursday, July 4, 2013

How To Generate EXCEL Files With PHP

Hello,
Today, I will share a very useful application with you guys, generating excel files with using PHP. As you know, we need reports as excel, pdf, word etc. in our web sites. For that reason, generating all of'em is important thing for us. Some of us use basic HTML files with using PHP & a data base. But this is not enough. Thus, I use generating excel.
So, Let's code :)
$filename = "myExcelFile_".date('Y-m-d-h-i').".xls"; 

header("Content-Disposition: attachment; 
        filename=\"$filename\""); 

header("Content-Type: application/vnd.ms-excel"); 

header('Content-Type: application/x-msexcel; 
        charset=UTF-8; format=attachment;');

echo "\tMy EXCEL DATA\r\n"; 

exit;

I set my file name up as myExcelFile_ plus current time and some header configuration. Then finally I print. That's it.
If you run, you'll see this view:

This article was short but so useful. You can develop better, of course.
See you next article.

Tuesday, October 16, 2012

Encryption Functions in PHP: crypt() and md5()

Hi! In this article, I am going to share encryption functions on PHP programming language with you. Well, there are several functions about this subject, but here the point is crypt and md5.


md5 function is a text encryption. Here the text or string may be probably as password. md5 function makes the text a value which is 32-digit. Sure this value is probably going to be more complex than older text value.
print md5("phpservisi.com");
md5 function's output
The example given above shows us phpservisi.com string value's output with md5 function.

crypt function is the same mission with md5. Namely this is encryption function too. Here the variety is complexity of output. Because of it is some of us use this one, like me :) 

One more feature is the output of crypt function's about making one-way string hashing. crypt function will return a hashed string using alternative algorithms that may be available on the system.

Now, I'm coding about this:


echo crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com"); 
echo "\n".crypt("phpservisi.com");

crypt function's output
As you've seen on the top is crypt function's output. I did the same thing 8 times, and crypt function has just given us different results about those.

If you want to learn more information about this subject, you can visit the PHP Manual web page: md5cryptsha1_filecrc32sha1hash

Sunday, June 17, 2012

Getting Contents of a DIV With PHP's DOM

Hi! Almost all of us use XML in our web sites. We can get contents with parsing XML files. But sometimes, we need another ways. The reason of this is that we want to get only one dom's content. For example an img element's content or it's value of id


Well, I will introduce how to get contents of element in this article. That's why I'll show you the sample given belown.


For my example, I got two files here:
  1. GetContent.php
  2. test.html
GetContent.php
<?php
$content="test.html";
$source=new DOMdocument();
$source->loadHTMLFile($content);
$path=new DOMXpath($source);
$dom=$path->query("*/div[@id='test']");
if (!$dom==0) {
   foreach ($dom as $dom) {
      print "<br>The Type of the element is: ". $dom->nodeName. "<br><b><pre><code>";
      $getContent = $dom->childNodes;
      foreach ($getContent as $attr) {
         print $attr->nodeValue. "</code></pre></b>";
      }
   }
}
?>
So, If you analyze the sample given above, you can see the point easily. The point is the content of div element which is id=test. The reason of existing test.html page is to get div's content.

test.html
<div id="test">This is my content</div>

What we have just seen up there, should be like on this demo page.

The Type of the element is: div
This is my content

The result is the text above. We'll see you guys next article!

Wednesday, June 13, 2012

PHP and Microsoft Access Database Connection

We all know that MySQL database connection is the best way for PHP. This make us so strong during coding. But what I have to say is that is not the only way. We have some opinions about connecting to databases. These may be between PHP&Access, PHP&Sqlite and PHP&PostgreSQL etc. But here, we interested in the first one, PHP&Access.

Access is one of the most popular databases in the world. It was made by Microsoft Corporation. You can find here more information about Access. A person who uses the Access can create, update, delete, etc tables on databases without using SQL.  That's why we can see easily how important  the interface is. In this respect this is so simple and useful.


An Example on Access : Getting data from access


<?php
$conn = new COM("ADODB.Connection") or die("ADODB Oops!");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\ MyDatabaseFile .mdb");
$data = $conn->Execute("SELECT * FROM myTable ORDER BY users ASC");

print "<TABLE border='1'><TR><TD colspan='6'>DATA</TD><TR>";
while (!$data->EOF)
{
print "<tr>";
print "<td>" . $ data ->Fields[0]->value . " </td>";
print "<td>" . $ data ->Fields[1]->value . " </td>";
print "</tr>";
$ data ->MoveNext();
}
echo "</TABLE>";


Just save code above as access.php and run it. It's going to be like the screen belown.
Screen View
If you try to figure that out, codes belown will be helpful for you.

$conn = new COM("ADODB.Connection") or die("ADODB Opps!");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\MyDatabaseFile.mdb");

We try to connect access database with php here.

odbc_connect(‘dsn name’, ‘user name’, ‘password’);

There is a problem with this! When you look at the code belown, can realize user_name and password field. What are these ones? How can we build on these? That's the point on this article actually. Just go to the localhost and this page:

phpinfo.php


<?php
Phpinfo();
?>



When run phpinfo.php file, need look into ODBC properties

ODBC with phpinfo.php
You must implement your user name and password for working on it. By the way, it is easier to make this operations with codes. That's why i show you as code, not screen views.

Well, let's code then :)

$conn = new COM("ADODB.Connection") or die("ADODB Opps!");
$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)};DBQ=C:\Users\UserName\Desktop\MyDatabaseFile.mdb");

$data = $conn->Execute("SELECT * FROM myTable ORDER BY users ASC");

print "<TABLE border='1'><TR><TD colspan='6'>DATA</TD><TR>";
while (!$data->EOF)
{
print "<tr>";
print "<td>" . $ data ->Fields[0]->value . " </td>";
print "<td>" . $ data ->Fields[1]->value . " </td>";
print "</tr>";
$ data ->MoveNext();
}
echo "</TABLE>";

This is my result page with php, html and sql.

See you guys next article!

Wednesday, March 28, 2012

Using PHP-GTK to Serve Desktop Applications: Creating a Simple Interface

PHP-GTK is a library for PHP that provides an object-oriented interface to GTK+ classes and functions. Actually this is a little bit hard, so that is slow to develop itself. PHP-GTK uses object-oriented programming on it.

What is PHP-GTK?

GTK is a library to develop PHP and created by Andrei Ziminevski, you want to see him? There are some varieties about that, Scintilla, GtkHTML, etc.
According to some of us, Java, C++ or C# is better to use than PHP-GTK. But If the coder who knows how to code on PHP use it, PHP-GTK should be very simple to code. That's why is OOP kind of PHP 5.

Installing PHP-GTK for Windows
Had you set any plugin up before, you shall say that, installing PHP-GTK plugin is so hard, but actually is not'cuz you have to know something about that. First go this site: gtk.php.net or here and download gtk library. After that open the .rar or .zip file you've just downloaded.

Download gtk library: gtk.php.net
When you open this archive, just copy all folders to C:/
After this, open the winnt folder and copy the php.ini file, paste to php4 folder. And finish! You have finally finished the installing right now!
This one is for windows installation. If you want to install this package other system (Linux, MacOS something else), you can visit this official page.


The First GTK Project!
As we know, when the first project created, just done "hello world!". What we're gonna do is like that :) For this we need to php code and GTK library. that's it!
helloworld! MyFirstProject.php file

function clearThis() {
  Gtk::main_quit();
}
$window = new GtkWindow(); 
$window->connect('destroy','clearThis');

$window->set_border_width('50'); //Alert's width set as 50px.

$label = new GtkLabel("Hello World"); //Written Text sets here.
$window->add($label);

$window->show_all();
Gtk::main();
It is time to work the project. First open your windows command screen and follow this directory: c:\php4\php c:\php4\test\MyFirstProject
Output
Well, we have installed PHP-GTK library on C:/ and created the first project about it. As result, we can say, PHP language is not just for the web, can use it as desktop.


See you guys next article!

Saturday, January 28, 2012

A web interface for Virtualbox: phpvirtualbox



The previous article (http://stdioe.blogspot.com/2012/01/creating-virtual-machine-with.html) was about creating a virtual machine with VBoxManage command. I must confess that using that VBoxManage command to manage Virtualbox machines is not easy. A web interface would be easier than using command-line. There are some alternatives to get it. The first one is The Software Developer Kit. You can download it from http://download.virtualbox.org/virtualbox/4.1.8/VirtualBoxSDK-4.1.8-75467.zip address. This package contains all required tools and libraries, If your aim is to develop..

But I'm going to talking about phpvirtualbox project which is hosted on code.google.com site. The web address of this project is "http://code.google.com/p/phpvirtualbox/". You can download the project from this site or help to develop more and you may want to support it. Finally, it's realy useful and capable to manage the Virtualbox structure. I want to talk about this project which is ready for use after then my previos two entries of course.


1-) Apache http server installation.

support@tester:~$ sudo apt-get install apache2 php5
[sudo] password for support:
...
...
Do you want to continue [Y/n]?
...
...
...
Setting up php5 (5.3.6-13ubuntu3.3) ...
Setting up php5-cli (5.3.6-13ubuntu3.3) ...

Creating config file /etc/php5/cli/php.ini with new version
update-alternatives: using /usr/bin/php5 to provide /usr/bin/php (php) in auto mode.
Setting up ssl-cert (1.0.28) ...
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
support@tester:~$

If you want to check the installation you can create a "test.php" file in the /var/www/ directory as shown below:

<?php phpinfo(); ?>

Now you will able to see all information about your completed setup of Php.

2-) Downloading and extracting Phpvirtualbox package.

support@tester:~$ wget http://phpvirtualbox.googlecode.com/files/phpvirtualbox-4.1-7.zip
support@tester:~$ sudo apt-get install unzip
support@tester:~$ unzip phpvirtualbox-4.1-7.zip
support@tester:~$ sudo cp -R phpvirtualbox-4.1-7 /var/www/phpvirtualbox

Right now, we have to rename "config.php-example" file and edit it. It is the configuration file of Phpvirtualbox.

support@tester:~$ cd /var/www/phpvirtualbox/
support@tester:/var/www/phpvirtualbox$ sudo mv config.php-example config.php
support@tester:/var/www/phpvirtualbox$

Edit 12th, 13th and 52th lines as shown below:

  1 <?php
2 /**
3 * phpVirtualBox example configuration.
4 * @version $Id: config.php-example 366 2011-12-01 19:56:57Z imooreyahoo@gmail.com $
5 *
6 * rename to config.php and edit as needed.
7 *
8 */
9 class phpVBoxConfig {
10
11 /* Username / Password for system user that runs VirtualBox */
12 var $username = 'support';
13 var $password = '[password_of_support]';
14
...
...
51 // Disable authentication
52 var $noAuth = true;
53
...
...

3-) Starting vboxwebsrv service and accessing to phpvirtualbox interface.

support@tester:~$ sudo touch /var/log/vboxwebsrv.log
support@tester:~$ sudo chown support /var/log/vboxwebsrv.log
support@tester:~$ vboxwebsrv -b -F /var/log/vboxwebsrv.log
Oracle VM VirtualBox web service version 4.1.8
(C) 2005-2011 Oracle Corporation
All rights reserved.
VirtualBox web service 4.1.8 r75467 linux.amd64 (Dec 19 2011 14:49:48) release log
00:00:00.000 main Log opened 2012-01-27T20:52:43.870809000Z
00:00:00.000 main OS Product: Linux
00:00:00.000 main OS Release: 3.0.0-12-server
00:00:00.000 main OS Version: #20-Ubuntu SMP Fri Oct 7 16:36:30 UTC 2011
00:00:00.000 main OS Service Pack: #20-Ubuntu SMP Fri Oct 7 16:36:30 UTC 2011
00:00:00.000 main Executable: /usr/lib/virtualbox/vboxwebsrv
00:00:00.000 main Process ID: 19407
00:00:00.000 main Package type: LINUX_64BITS_UBUNTU_11_10

-b parameter is for starting the service in the background and -F parameter is for creating a log file "/var/log/vboxwebsrv.log". The problem is, the user support has not rights to create a log file in the "/var/log" directory. So we created it as root and gave the ownership to support again in top two command. If we need a startup script to auto start when base system is booting, we have to have the caseful ownership part as below, (/etc/init.d/vboxwebsrv_starter)

#!/bin/bash

u=`/usr/bin/id -u`

case "$1" in
start)
if [ $u -eq 0 ]; then
/bin/su support -c '/usr/bin/vboxwebsrv -b -F /var/log/vboxwebsrv.log'
else
echo "Start vboxwebsrv"
/usr/bin/vboxwebsrv -b -F /var/log/vboxwebsrv.log
fi
;;
stop)
# nothing
;;
restart)
# commands for restarting will come here then...hah?
stop
start
;;
status)
# ..
echo "vboxwebsrv:";
/bin/ps -ef | /bin/grep vboxwebsrv
;;
*)
echo "Usage: /etc/init.d/vboxwebsrv_starter [start|stop|restart|status]"
exit 1
;;
esac
exit 0

Finally, we have to give execute permissions and add inittab with update-rc.d command as shown below:

support@tester:~$ sudo chmod +x /etc/init.d/vboxwebsrv_starter
support@tester:~$ sudo update-rc.d vboxwebsrv_starter defaults
update-rc.d: warning: /etc/init.d/vboxwebsrv_starter missing LSB information
update-rc.d: see <http://wiki.debian.org/LSBInitScripts>
Adding system startup for /etc/init.d/vboxwebsrv_starter ...
/etc/rc0.d/K20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
/etc/rc1.d/K20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
/etc/rc6.d/K20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
/etc/rc2.d/S20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
/etc/rc3.d/S20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
/etc/rc4.d/S20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
/etc/rc5.d/S20vboxwebsrv_starter -> ../init.d/vboxwebsrv_starter
support@tester:~$

4-) You can select a Virtualbox based password protection or Apache based password protection to access to Phpvirtualbox directory.


a) Edit sudo vim /etc/apache2/sites-enabled/000-default file to get ready to password protection on apache. I added "+" lines to 000-default file as shown below:

<VirtualHost *:80>
ServerAdmin webmaster@localhost

DocumentRoot /var/www
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>

+ <Directory /var/www/phpvirtualbox>
+ Options Indexes FollowSymLinks MultiViews
+ AllowOverride AuthConfig
+ Order allow,deny
+ allow from all
+ </Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
</Directory>
...
....
......

b) Create a user and a password with "htpasswd" command as shown below:

support@tester:~$ htpasswd -c /home/support/passwords vboxuser
New password:
Re-type new password:
Adding password for user vboxuser
support@tester:~$

The "-c" parameter is for creating a new file which contains both user and password information.

c) Create "access" file in the password protected directory. Save following content in /var/www/phpvirtualbox/.htaccess file.

AuthType Basic
AuthName "Virtualbox Management Interface"
AuthUserFile /home/support/passwords
Require user vboxuser

Finally we have to reload / restart apache service to apply changes as shown below:

support@tester:~$ sudo /etc/init.d/apache2 restart

Note: This article about just installation. I'll talk about authentication and multiple user configuration. This feature supply different virtual machines lists for each other user.

Sunday, December 4, 2011

Facebook Like Button Example With JQuery

Hi! We all got a Facebook account. As you remember, Facebook's got so much options that we can use, Like button, Chat, TimeLine etc.

In last article, I made mention of Jquery used within Facebook. Today, I'll show you one of'em. That is "like button".

As you know, when our friends share something, we can like it easily. When clicked the like button, data is saved without refresh. Because of this is JQuery&Ajax. Actually this example is not going to be like Facebook Like Button Module exactly, but, may be a good idea to do it for some of us. This things're so easy to do. We all need a database, a PHP page and a coding ajax page with ajax library, where is that complex?

Let's start it!

First, create your MYSQL Table;
CREATE TABLE `jquery_app`.`LikeButton` (
`ID` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`data` VARCHAR( 255 ) NOT NULL
)
You shall need this files:
  1. settings.php //database configurations
  2. jquery.js //your jquery code
  3. jquery library //you must include this file on index.php page
  4. match.php //your php code that you do like something and write database
  5. index.php //default page

index.php

This is facebook like button example. This is what i share! :)
< a href="#" id="like">Like < div id="whathappened"> //We see total clicked like button
< /div>
< div id="whathappening"> //We see what happening now
< /div>

When click the link, sending query to jquery.js page. After that jquery starts ajax method and searchs match.php page for adding +1.

jquery.js
// JavaScript Document
$(document).ready(function() {
 $('#like').click(function() {
  $('#whathappening').fadeIn(1000);
  var wait="Adding..";
  $.ajax({
   cache:false,
   async:false,
   url:'match.php',
   success:function(inc) {
    $('#whathappened').html(inc);
    $('#whathappening').html(wait);
    $('#whathappening').fadeOut(1000);
   }
  });
 });
});

When id=like click, data'll been added to database. If you ask how to add this, you should analyze the page is shown below.

match.php

 include("settings.php");
 //adding data
 $random=rand(0,99999999);
 $ekle=mysql_query("INSERT INTO LikeButton(data) values('$random')");
 //how many data we got
 //with the data we've just added
 $show=mysql_query("select * from LikeButton");
 $total=mysql_num_rows($show); //Getting total liked
 echo "Total: ".$total; //Print total liked.

What you see here, all php code. We include settings.php page for connection database. We get total and add +1 to this.

settings.php

 $conn=mysql_connect("localhost", "username", "password") or die("error1");
 mysql_query("SET NAMES 'utf8'") or die("error2");
 mysql_select_db("jquery_applications",$conn);
 error_reporting(0);
 ini_set('display_errors','Off');
 error_reporting(E_ALL); 

That's it! You've just done Facebook like module. If you want to see how to work this, you can visit the web site for demo.
Module view
When "Like" link click

Wednesday, November 30, 2011

How to Connect Cisco Router with PHP Scripts



I used to explain a Perl version of these scripts in page "http://stdioe.blogspot.com/2011/09/how-to-connect-cisco-router-with-perl.html". And now, I'm talking about the Php version. Because, Php is known to be easier than Perl by the most of the people. You may want to implement these samples in your existing projects. Essentially, we are establishing a telnet session between our script and a Cisco router. It's only a telnet connection. There are a lot of telnet-scripts for php in the internet. You can use them but we are talking about a specific situation. Let's write it from scratch.

I prepare to write those scripts as much as parametric, that is, I will avoid writing all of staff hard-coded. "$argv" variable is a predefined array in Php and it is able to capture the given parameters as well as in the console. For example,

<?php
#!/usr/bin/php
$if(isset($argv[2])) {
print "The first parameter is:".$argv[1]."\n";
print "The second parameter is:".$argv[2]."\n";
} else {
print "usage: ./sample.php parameter1 parameter2 \n";
print "or \n";
print "usage: php sample.php parameter1 parameter2 \n";
}

?>

You can execute the script by typing "./sample.php" or "php sample.php" directly in your console. If you want to execute it as "./sample.php", you have to add the line (#!/usr/bin/php) on the top of your script and you have to give executive permissions to sample.php. (chmod +x sample.php). If you want to execute with the syntax "php sample.php", you don't need to add the line and give those rights. Because, the executing rights are already given for "php" part.

The sample.php script is capturing your parameters using the array variable $argv. You can see all of the $argv content using the line "print_r($argv);" in you Php script. So we will use the $argv array to take ip_address, username and password values from the user. I used fsockopen, fput and fgets commands to establish connections, to send commands and to get the output from the router, respectively.

If the cisco router output is very long for one page, it returns a " -- More -- " statement in the last line. If we press the space button on the keyboard when we see this statement, the router will send next page. If we press the enter key on the keyboard when we see this statement, router will send the next line. So we have to control the content and if there is a " -- More -- " statement in the content, we have to send a space character to get next part of the router output. We will control the " -- More -- " statement with an "ereg" function of php.

The php script for connecting to the Cisco router (telnetCisco.php):

#!/usr/bin/php
<?php
if(!isset($argv[2])) {
die ("usage: ./scriptName router_ip username password\n");
}
$port = 23;
$timeout = 10;
$router_ip = $argv[1];
$username = $argv[2];
$password = $argv[3];

$connection = fsockopen($router_ip, $port, $errno, $errstr, $timeout);

if(!$connection){
echo "Connection failed\n";
exit();
} else {
echo "Connected\n";
fputs($connection, "$username\r\n");
fputs($connection, "$password\r\n");
fputs($connection, "show run\r\n");
fputs($connection, " ");

$j = 0;
while ($j < 16) {
fgets($connection, 128);
$j++;
}
stream_set_timeout($connection, 2);
$timeoutCount = 0;
while (!feof($connection)){
$content = fgets($connection, 128);
$content = str_replace("\r", '', $content);
$content = str_replace("\n", "", $content);
print $content."\n";

# If the router say "press space for more", send space char:
if (ereg('--More--', $content) ){ // IF current line contain --More-- expression,
fputs ($connection, " "); // sending space char for next part of output.
} # The "more" controlling part complated.

$info = stream_get_meta_data($connection);
if ($info['timed_out']) { // If timeout of connection info has got a value, the router not returning a output.
$timeoutCount++; // We want to count, how many times repeating.
}
if ($timeoutCount >2){ // If repeating more than 2 times,
break; // the connection terminating..
}
}
}
echo "End.\r\n";
?>

"stream_get_meta_data" function is the most critical one in this article. Because, I used the stream_get_meta_data to check the status of connection. Following output shows the "stream_get_meta_data" content with print_r function to see "how to recognize end of the output". (The last three loop)

....
...
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)
Array
(
[stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] => 1
[blocked] => 1
[eof] =>
)

The time_out values are "1" in the last two loops. The $timeoutCount value is counting that "1"s in the telnetCisco.php and if it gets "1" more than two times, it stops reading the output with a "break;" line.

Tuesday, November 15, 2011

Web 2.0 Tech and a Jquery Auto Search Complete Application!

Hi! Today I want to talk about web 2.0 technology. As you know, web 2.0 is being used by many of us. Especially frameworks developed with javascript and ajax, used by everyone. Well, we can say that huge companies which are google, yahoo, facebook and twitter etc. use web 2.0 too.

I would like to make an application on Jquery and share with you guys. So, in 2006, Jquery's started to be developed as an open source project. When you see "The write less, do more", you should understand that is Jquery! There is a powerful library of javascript, that's why we can do good jobs with the less code on Jquery.

If you want to see more information, you can visit the official web site of jquery. You can also find documentation and examples on it. That is here!

You must call as include jquery library on your web site, for the successful operation of your jquery code. You can find the library on Jquery Web Site easily.

The point I wanted to show you here is an ajax application on jquery. However, I am thinkin' that I should show you couple simple examples, before starting to applicaton.

$('#divID').slideUp(1000); //Sliding the div up
$('#divID').slideDown(1000); //Sliding the div down
$('#divID').slideToggle(1000); //Sliding the div up and down
$('#divID').FadeToggle(1000); //Displaying or hiding the div
$('#divID').html(“Hello World!”); //Printing something as HTML tags

$(‘a’).click(function() {
 $("#divID").animate({left:'+=100px'}, 2000); //when you click the mouse, do something
});

As you have seen, when you code jquery, you can control the web site all the way.
The application I'll show you, is an AUTO SEARCH COMPLETE!


This is the text field we'll use when searching.


This is the div layer will open during our php script works.
// JavaScript Document
$(document).ready(function() {
 $('#TextBox').keyup(function() {
  document.getElementById("result").style.display="block";
  var variable=$('#TextBox').val();
  $.ajax({
      url:"data.php",
      data:"TextBox="+variable,
      cache:false,
      async:false,
      method:'post',
      success:function(kitchen) {
          var message="Loading..";
          $('#result').html(message).load();
      }
  });
 });       
});

As you have seen, when keyup() function works, the system is getting data from data.php page. data.php page is shown below

 include("database.php");
 $data=$_REQUEST["TextBox"];
 if(!$data==0) { 
  $MyData=mysql_query("select * from names where name like '%$data%'");
  if(mysql_num_rows($MyData)<"1") {
   echo "There is nothing about it!"; 
  } else {
   echo "Languages!
"; while($MyList=mysql_fetch_array($MyData)) { echo $MyList["name"]."\n"; } } } else { echo "Please, start to write something.."; }


Today, we made a jquery search auto complete application. If you visit and see this application, just click demo page!

See you guys next article!