25 August 2025

Need a Time Difference Website

 If you travel a lot, you may need to compare times between cities.

Here is a brand new website with a clear user interface. 

Time difference calculator between major cities. Not only finds the time difference but also it gives:

  • Time zone names
  • UTC offsets
  • Time in 12h and 24h format
  • Am/Pm time comparison between city times.

Check the https://www.timedifference.net/ two find time differences between cities.


23 May 2025

Debian Nginx Port 80 Already in Use Problem and Solution

 In Debian operation system, when using nginx web server, we can get port 80 already in use error.

And this prevents system restart.

Solution is to list all processes that use port 80 and kill each of them.

Connect to your server via SSH.

And they the command below:

sudo netstat -tulpn

This command will list 

sudo netstat

And kill each process with the PID number on the right with using the command below:

sudo kill -2 <PID>

And restart the nginx

sudo service nginx restart

Now your webserver will work as usual.



29 August 2016

Update Nginx Commands

Nginx is the fastest web server which is started to used widely.
Several cloud platforms let us to install and manage nginx on cloud virtual machines.
Sometimes important security updates are published.
We need to update our web server to stay up to date.
Here is the simple commands to update nginx on cloud platforms.

sudo apt-get update         # Fetch the list of available updates
sudo apt-get dist-upgrade   # Install the updates


Than a restart may required.

sudo service nginx restart





22 August 2013

PHP Database Class MySQLi

Almost in every project I need a database class behind my BLL classes. I keep my SQL queries in BLL classes and use the database class to run the queries. This is kind of engine used by all classes in common. I will explain how to implement and how to use step by step in comments code.

Note that this class does not use the deprecated MySQL library, it uses MySQLi library. Here is the complete PHP Database Class source code;

First php is the configuration file for use in database class.
I call it dbconfig.php
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "db_username");
define("DB_PASS", "db_user_password");
define("DB_NAME", "db_scheme_name");
?>
I think it is better to keep configuration data in a seperate php file, because if change the database name, username or password, i just change the dbconfig.php file.

MySQLi Database Class
<?php

// My database Class called myDBC
class myDBC {

// our mysqli object instance
public $mysqli = null;

// Class constructor override
public function __construct() {
 
include_once "dbconfig.php";        
       
$this->mysqli = 
   new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

if ($this->mysqli->connect_errno) {
    echo "Error MySQLi: ("&nbsp. $this->mysqli->connect_errno 
    . ") " . $this->mysqli->connect_error;
    exit();
 }
   $this->mysqli->set_charset("utf8"); 
}

// Class deconstructor override
public function __destruct() {
   $this->CloseDB();
 }

// runs a sql query
    public function runQuery($qry) {
        $result = $this->mysqli->query($qry);
        return $result;
    }

// runs multiple sql queres
    public function runMultipleQueries($qry) {
        $result = $this->mysqli->multi_query($qry);
        return $result;
    }

// Close database connection
    public function CloseDB() {
        $this->mysqli->close();
    }

// Escape the string get ready to insert or update
    public function clearText($text) {
        $text = trim($text);
        return $this->mysqli->real_escape_string($text);
    }

// Get the last insert id 
    public function lastInsertID() {
        return $this->mysqli->insert_id;
    }

// Gets the total count and returns integer
public function totalCount($fieldname, $tablename, $where = "") 
{
$q = "SELECT count(".$fieldname.") FROM " 
. $tablename . " " . $where;
        
$result = $this->mysqli->query($q);
$count = 0;
if ($result) {
    while ($row = mysqli_fetch_array($result)) {
    $count = $row[0];
   }
  }
  return $count;
}

}

?>
Other Descriptions
Because I always use UTF-8 encoding I set my database engine connection to utf8 too.
   $this->mysqli->set_charset("utf8");

Actually you dont need to close the connection, as the connection closes it self after the query executions completted. But sometimes I run lots of queries in same session and I just close it.
public function __destruct() {
   $this->CloseDB();
 }

Usage Examples


SQL Insert Example
include "mydbclass.php";

$mydb = new myDBC();

$firstname = $mydb->clearText($firstname);
$lastname  = $mydb->clearText($lastname);

$sql = "INSERT INTO users (usr_firstname,usr_lastname) 
VALUES ('$firstname','$lastname'); ";

$mydb->runQuery($sql);


SQL SELECT Example
include "mydbclass.php";

$mydb = new myDBC();

$id = $mydb->clearText($id);
$sql = "SELECT * FROM users WHERE usr_id='$id' LIMIT 1;";

$result = $mydb->runQuery($sql);

if(isset($result)) 
{
  $row = mysqli_fetch_array($result);
  $firstname = $row['usr_firstname']; 
  $lastname = $row['usr_lastname']; 
}


18 August 2013

PHP Get Server OS Name

The operating system name where the php running on can be read by several ways;
echo PHP_OS;

// output: CentOS

But if we want to get more detailed information about the OS, we may use php_uname
 
echo php_uname('s');

// output: Linux 2.6.18-348.6.1.el5 x86_64

php_uname gives information including; OS name, OS version, if it is 32bit or 64bit.

17 August 2013

PHP Check If Form Submitted

There are several ways to check whether a form submitted or not.

if(isset($_POST))
{
// do work
}

if (!empty($_POST))
{
// do work
}
 

But it is much better to check the server parameter. There are pretty much information stored in $_SERVER.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
{
// now we are pretty sure for the post action 
}
 
 


Request method is just more rock solid way to check is a form submitted or not.

15 August 2013

PHP Get Referrer Url

in Php $_SERVER array consists of various data in it. Such as;
  • SERVER_NAME
  • REQUEST_METHOD
  • QUERY_STRING
  • HTTP_REFERER
Where the  HTTP_REFERER is the page address which the user agent referred.
Note that it is not guaranteed that this referrer set.
If the visitor comes from the bookmark, it will not be set.

So if it is set, we can get the url of the referrer by ;

$url="";
if(isset($_SERVER["HTTP_REFERER"]))
    $url = $_SERVER["HTTP_REFERER"];


Why we need this referrer url ?
Well I use this referrer url to redirect user to a certain page after a certain job done.
For example, log in user, than redirect to user to his/her profile page.

Example;

$url="";
if(isset($_SERVER["HTTP_REFERER"]))
    $url = $_SERVER["HTTP_REFERER"];

// ... do some job here ...

Header("Location: ".$url);
exit();

This may helpful when a user tries to access a log in required content, after log in successful he/she will be redirected to the previous page and continue whatever he/she will do on that page.

Note that, it is not always a good idea to trust this referrer url, referrer url should be stored in SESSION or cookie will be more secure.

PHP Get Page Parameter Safe $_GET

Most of us have to use the $_GET in PHP to get the desired content id and print the contents on page. But we cannot trust the incoming paremeter directly from the url.
We should check the parameter and validate it.

If it is set
Check if the parameter is set or not
if ( isset($_GET['id']) )
{
 // ok it is set.
}

Now I also check if it is empty or not;

If it is not empty

if ( isset($_GET['id']) && !empty($_GET['id']) )
{
 // ok it is set and not empty
}

If you know the parameter must be integer, than lets check
If it is a valid number. 

if ( isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id']) )
{
 // ok it is set, not empty, and a number, get it;
$id = trim($_GET['id']);
}

Finally we get our parameter safely in PHP.

PHP Get Current URL

I need to get the current url for some purposes, such as;
  • Check the url if it is used to be. This is required to prevent dublicated content from different urls in your website.
  • Generate social bookmark and like data-href links
It is easy to get the current url in PHP;

<?php 

echo "http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];

?>


This will give you the exact url of the current page.

29 June 2011

Maximum Request Length Exceeded ASP.NET

I got this error Maximum request length exceeded while i was trying to upload several files, or a single big size file. As default, max file upload size is 4MB.
We can easily have a solution by not touching our asp.net c# source code.

Just add a single line of code in your Web.config file, and you are done.

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="32768" />
  </system.web>
</configuration>


Now we will not get maximum request length exceeded error in asp.net.

14 April 2011

C# Convert String to Integer

Converting string to int is simple in c#. There are two comman ways to convert string to int.
  • Convert.ToInt32
  • Int32.TryParse
Here is the screen shot of our string to int converter sample application:


Note that our integer number must be between −2,147,483,648 and +2,147,483,647 range.

The c# source code to convert string to integer:
private void btnConvert_Click(object sender, EventArgs e)
{
int numValue = 0;
string strValue = string.Empty;

strValue = tbInput.Text.Trim();

try
{
numValue = Convert.ToInt32(strValue);
lblResult.Text = numValue.ToString();
}
catch (Exception exc)
{
tbInput.Text = string.Empty;
lblResult.Text = string.Empty;
MessageBox.Show("Error occured:" + exc.Message);
}
}       

private void btnTryParse_Click(object sender, EventArgs e)
{
ConvertToIntTryParse();
}

private void ConvertToIntTryParse()
{
int numValue = 0;
bool result = Int32.TryParse(tbInput.Text, out numValue);
if (true == result)
lblResult.Text = numValue.ToString();
else
MessageBox.Show("Cannot parse string as int number");
}

I think IntTryParse is better to convert string to int, because it handles the parse error inside and returns bool value if the string is parsable to int.
IntTryParse return boolean value, so that if it parses the string it returns true, else returns false.

Note the parsing string with Convert.ToInt32 may cause a FormatException if the parse string value is not suitable.

06 December 2010

Fix MySQL Character Encoding Problem UTF-8 PHP

While gathering data from Mysql database i got character encoding problems when my tables have non-english text.
I found a solution that completly solves character encoding problem while you calling your sql queries.

Simply set your character set before you call a sql query.
$myconnection= mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die(mysql_error());
mysql_select_db(DB_NAME, $myconnection) or die(mysql_error());
mysql_set_charset('utf8',$myconnection);

mysql_set_charset method sets your character set before the calls.
Don't forget to encode your php files to utf-8, or what encoding you want to encode with.

25 May 2009

ASP.NET How To access Master Page Variables Class Members C#.NET

Sometimes we need to access to a variable in master page file.
For example I need to change the body onload event in html.

In the asp.net file, we simply cast our master page as its class name.

in master page aspx we add the code below.

<body onload="<%=myloadstr %>" >

in master page cs code we add the code below.
we declare it as public to access the variable.

public string myloadstr = "";


And add the code below in your asp.net cs source file.

((myMasterPage)this.Master).myloadstr = "here some javascript for load";

myMasterPage is the name of my masterpage class. We cast our asp.net page its masterpage, with "this.Master".

22 May 2009

Run PHP On Local Machine

When I want to develop a php website, it is always be hard to run and test the php code on local machine.
After I search how to run php on local machine, I found an awesome tool for this.


XAMPP is a great open source software that helps you run php on local, and also it runs MySQL Server service, Filezilla FTP.

Simply download xampp and install it, I select the run apache as service option.

By its default, it installs into C:\xampp directory,
you can copy your php files into C:\xampp\htdocs directory, and open in your browser.

16 December 2008

C# MS Access Connection String OLE DB OleDbConnection

The Connection String for MS Access can be set as ;
 private constr =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=yourdbfile.mdb;
Jet OLEDB:Database Password=yourpassword;";
And the C# code to connect to MS Access database ;
 public bool OpenConnection()
{
OleDbConnection con; con = new OleDbConnection(constr);

if (con.State != ConnectionState.Open)
{
try
{
con.Open(); return true;
}
catch (Exception) { return false; }
}
else return false;
}
C# Access Connection String OLE DB OleDbConnection password field is the password you set up in access database.

Mobile Phone Hide Your Number

To hide your number when you are calling someone with your mobile phone,
simply add *31# in the beginning of the number you will call.

hide number
*31#

Imei Number Learn Your Mobile Phone Imei Number

You can easily learn you mobile phone's IMEI number
by pressing star square 06 square

*#06#

11 December 2008

C# Read Harddisk Serial Number WMI ManagementClass Win32_LogicalDisk

With the Win32_LogicalDisk Management path we can reach the local disk information.

Even you can read harddisk serial number,
size, partitions, free space and so on.

Now let's read the serial number of a harddisk in C# with ManagementClass WMI.
public static string HardDiskID()
{
ManagementClass partionsClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection partions = partionsClass.GetInstances();

string hdd = string.Empty;

foreach (ManagementObject partion in partions)
{
hdd = Convert.ToString(partion["VolumeSerialNumber"]);

if (hdd != string.Empty)
return hdd;
}

return hdd;
}
This static function will simple give us the volume serial numbers.
C# Read Harddisk Serial Number WMI ManagementClass.

28 November 2008

C# Textbox Auto Scroll To End ScrollToCaret Scrolling Textbox

Many of my sample C# codes,
I use textbox to write the results.

When textbox is multiline property set to true, and when I insert text into it,
I want it to auto scroll to the last line.

Here is a simple way to auto scrolling textbox.
 textbox1.SelectionStart = textbox1.Text.Length;
textbox1.ScrollToCaret();
textbox1.Refresh();
Textbox SelectionStart will force the textbox control to select the last part of the text,
and ScrollToCaret() function will auto scroll textbox to the end.

C# The process cannot access the file because it is being used by another process

The process cannot access the file because it is being used by another process.
This error message is mostly comes up,
when you try to access a file which is opened by another process.

You may open an image file in one of your form in a picturebox with using ImageFromFile or something.
I mostly use memorystream to open an image.
After read it in byte[] write it into a stream and close it.

You can check whether a file is being used or not with a simple function.
Try to open a file with none share.
 public bool IsFileUsedbyAnotherProcess(string filename)
{
try
{
File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (System.IO.IOException exp)
{
return true;
}
return false;

}
This function will return true if
the file because it is being used by another process or not.