Visual C# Upload File/Image via PHP with Squid-Cache in the Network

Info.Tech, Linux System Administration, PHP, Software Development, Visual C# View Comments

Today, I’ve been developing an oDesk-like activity monitoring application but for local network for my company, Innermax Support, and I came across with a problem of an errors:

  • An exception occurred during a WebClient request.
  • The remote server returned an error: (417) Expectation failed.

And during my search in Google — from forums, MSDN and other developers’ resources — they face same problem. The common issue was the 100-Continue problem passing to a network with squid-cache. So there’s a websites that I combined their codes and luckily it works. Just forgot the URLs, I can’t credit thank-you’s to them.. hehehe!

The setup is like this… there’s a firewall which has squid-cache in the local network and my server where I will upload my file/image is at the other network with public IP address. I will directly upload the file/image to my server using the assigned public IP address via PHP script.

Here’s my code to solve the problems;

public void uploadFile()
{
    try
    {
        // decleration of webclient
        ServicePointManager.Expect100Continue = false;
        System.Net.WebClient webby = new System.Net.WebClient();

        //initiate credentials
        webby.UseDefaultCredentials = false;
        webby.Credentials = new NetworkCredential("anonymous", "");

        //add headers
        webby.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.832)");
        webby.Headers.Add("Content-Type", "binary/octet-stream");

        //initiate upload file
        Byte[] result = webby.UploadFile("http://120.0.0.1/upload.php", "POST", @filename);

        string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
        MessageBox.Show(s);
        webby.Dispose();
    }
    catch (Exception)
    {
        // do nothing...
        MessageBox.Show("Upload failed!");
    }
}

So far, it works fine with me and satisfied of my solution. Hope this will help your problem too… :)

Outsourcing in the Philippines: InnerMax Support

Administration, Info.Tech, Learn New Things, Linux System Administration, Personal, PHP, Web Development View Comments

InnerMax SupportI’ve crossed  a good outsourcing firm in the Philippines, Innermax Support specializes in Web Development, Web Designing, SEO Services, Data Entry, Social Media Marketing, Inbound Phone Support, Outbound Phone Support.

They are comparatively new to the industry, but with their management along with all their agent’s combined knowledge, skills, and significantly valuable experiences; they surely can consistently turn every single task, great or small, highly distinguished more than any clients could wish for.

  • Innermax Support provides high quality services
  • Takes your business outsourcing to a new level with more leads and sales
  • Endows with the best services way beyond your desired results and expectations
  • Has assigned the best agents that fit every campaign you asked to be dealt with.
  • Gladly welcomes high level of engagement with the corporate stakeholders at your company.

Expect Quality Services

  • Exceptional results and return on assets
  • They never fail to keep our eyes peeled towards particular outcomes and circumstances of your campaign and in most instances; they most likely notice any sorts of any diversities and take action before such gets out of hand.
  • They are firmly committed to quality service and accommodation.
  • They are very knowledgeable by every inch and corners from tiniest to most immense aspects about e- marketing.
  • They never would hesitate to establish bountiful relationship and develop harmonious companionship with their valuable clients.
  • They live by the virtue of courteous and respectful demeanor to each of their clients.
  • They never would leave their clients oblivious about any current status of the relayed tasks.
  • And above all. They walk what they talk.

HowTo? .htaccess SEO-friendly URL

Administration, Info.Tech, Linux System Administration, PHP, Web Development View Comments

Today, its my 3rd time I created a SEO-friendly URL for a website… and its been a year since my last setup and forgot the procedure.. So I’m writing it down to my blog to remind me what I did… this time, I used different method coz I’m getting lazy using regex. hehehehe…

I used .htaccess generator at www.myseotool.com and upload to the server.. I tested it out.. and it seems it won’t work…

I search for the solution and I found the solution of Eddie Ringle about his experience too. So I edited my httpd.conf , since I’m also the system/server administrator, I have full access on the server, and change from;

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

to

<Directory />
  Options FollowSymLinks
  AllowOverride All
</Directory>

then save httpd.conf new changes. Then restart httpd or apache. then I tested it out..

wallah! it works!

[Rackspace] Backup web server files to Cloud Files using PHP API

Administration, Info.Tech, Linux System Administration, PHP, Web Development View Comments

My latest task if to enhance our backup system that we currently have which all our backups are stored in the same server. Today, I managed to create an API integration to Rackspace Cloud Files and to transfer the generated backups of the web server to Cloud Files. Below is the guide for those who are having trouble using the API.

HowTo:

  1. Download the Cloud Files API – https://github.com/rackspace/php-cloudfiles/tree
  2. Follow the steps in extracting the API files to your server, http://cloudfiles.rackspacecloud.com/index.php/PHP_API_Installation
  3. And you may start creating php script, read http://docs.rackspacecloud.com/files/api/cf-devguide-latest.pdf

Possible Problems you will encounter:

PHP Fatal error:  Uncaught exception 'BadContentTypeException' with message 'Required Content-Type not set ...

Solution:

  • Install the PHP PECL FileInfo
# yum -y install php-devel php-pecl php-pear

// if "sh: make: command not found" error OR "ERROR: `make' failed" occur, groupinstall the Development Tools.
# yum -y groupinstall "Development Tools"

// install fileinfo
# pecl install fileinfo
# service httpd restart

if still occurs, last resort is upgrade your php to php 5.3

  • Upgrade your PHP to 5.3

first, remove the current installed php and php-common

# yum -y erase php php-common

then install the PHP v5.3

# yum -y install php53 php53-devel php-mysql php-gd php-pecl php-pear php-common
#service httpd restart

and that’s it.. your php script should be running…

for my scenario:

[root@server backups]# ls
backup.logs                          mysql_03262011_0155.tar.gz  mysql_04042011_0155.tar.gz  mysql_04132011_0155.tar.gz  WebFiles_04-06-2011.tar.gz
backup.mail                          mysql_03272011_0155.tar.gz  mysql_04052011_0155.tar.gz  mysql_04142011_0155.tar.gz  WebFiles_04-13-2011.tar.gz
backupSQL.script                     mysql_03282011_0155.tar.gz  mysql_04062011_0155.tar.gz  mysql_04152011_0155.tar.gz  WebFiles_04-20-2011.tar.gz
backupSQL.script.11082010            mysql_03292011_0155.tar.gz  mysql_04072011_0155.tar.gz  mysql_04162011_0155.tar.gz  cronjobs.txt
backup.web                           mysql_03302011_0155.tar.gz  mysql_04082011_0155.tar.gz  mysql_04172011_0155.tar.gz  init.cdn.script
backupWEB.script                     mysql_03312011_0155.tar.gz  mysql_04092011_0155.tar.gz  mysql_04182011_0155.tar.gz  monthly.2011
cdn.backup.php                       mysql_04012011_0155.tar.gz  mysql_04102011_0155.tar.gz  mysql_04192011_0155.tar.gz  scripts
mysql_03242011_0155.tar.gz  mysql_04022011_0155.tar.gz  mysql_04112011_0155.tar.gz  mysql_04202011_0155.tar.gz
mysql_03252011_0155.tar.gz  mysql_04032011_0155.tar.gz  mysql_04122011_0155.tar.gz  WebFiles_03-30-2011.tar.gz

These files are my backup files, so I created a PHP script named cdn.backup.php, with initializer named init.cdn.script to upload the backup files to Cloud files. If I execute my script, this is the output:

[root@server backups]# ./init.cdn.script
. . . . . . . . . . . . . Uploadeding mysql_04202011_0155.tar.gz...
SQL backup completed!
. . . . . . . . . . . . . . . . . . . . Uploadeding WebFiles_04-20-2011.tar.gz...
Web files backup completed!

That’s it… My files has been uploaded to cloud files.

Source code:

<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@date_default_timezone_set(@date_default_timezone_get());

require('cloudfiles.php');

date_default_timezone_set('America/New_York');
$cfgAccount = array('user'=>'demo','keys'=>'fe01ce2a7fbac8fafaed7c982a04e229');

$auth = new CF_Authentication($cfgAccount['user'], $cfgAccount['keys']);

$auth->authenticate();

if ($auth->authenticated())
{
	$conn = new CF_Connection($auth);
	//$conn->ssl_use_cabundle();

	$container_name = "backups";

	// execute this if no container
	//$backup_obj = $conn->create_container($container_name);
	//echo $backup_obj;

	if (function_exists('systemxx'))
	{
		system("ls -t",$lines);
		foreach($lines as &$line)
		{
			echo $line . "\n\n";
		}
	}
	else
	{
		$backupSQLSent = 0;
		$backupFILESent = 0;
		$limit = date("j") - 7;
		for ($i = date("j"); $i > $limit; $i--)
		{
			$d = dir("/backups/");
			//echo "Handle: " . $d->handle . "\n";
			//echo "Path: " . $d->path . "\n";
			while (false !== ($entry = $d->read()))
			{
				//  mysql_04122011.tar.gz
				if ((preg_match("/mysql_".date("mdY")."/", $entry)) && ($backupSQLSent == 0))
				{
					$backup_obj = $conn->get_container($container_name);

					echo 'Uploadeding '.$entry."...\n";

					$tarballs = $backup_obj->create_object("cdn_".mktime()."_".$entry);
					$filename = "/backups/".$entry;

					// upload file in a hard way
					$fsize = (float) sprintf("%u", filesize($filename));
					$fp = fopen($filename, "r");
					$tarballs->write($fp, $fsize);

					// upload file in a convenience way
					//$tarballs->load_from_filename($filename);

					echo "SQL backup completed!\n";
					$backupSQLSent = 1;
				}

				// WebFiles_04-20-2011.tar.gz
				if ((preg_match("/WebFiles_".date("m-d-Y")."/",$entry)) && ($backupFILESent == 0))
				{
					$backup_obj = $conn->get_container($container_name);

                                        echo 'Uploadeding '.$entry."...\n";

                                        $tarballs = $backup_obj->create_object("cdn_".mktime()."_".$entry);
                                        $filename = "/backups/".$entry;

                                        // upload file in a hard way
                                        $fsize = (float) sprintf("%u", filesize($filename));
                                        $fp = fopen($filename, "r");
                                        $tarballs->write($fp, $fsize);

                                        // upload file in a convenience way
                                        //$tarballs->load_from_filename($filename);

					echo "Web files backup completed!\n";
                                        $backupFILESent = 1;
				}

				if (($backupFILESent == 1) && ($backupSQLSent == 1))
				{
					break;
				}
				echo ". ";
			}
			$d->close();

			// if backup sent, end loop
			if (($backupFILESent == 1) && ($backupSQLSent == 1))
			{
				break;
			}
			echo "\n";
		}
	}

}
else
{
	echo 'Unable to connect to Cloud Files!';
}

?>

Downloads:

  1. Cloud Files PHP API (78)
  2. cdn.backup.php (69)

PHP: Pagination | Paginator

Info.Tech, PHP, Web Development View Comments

Pagination Screenshot

Last month, my classmate ask me how to create a pagination or paginator that can handle hundred of thousands of rows. And I realized that my current paginations are not good enough. It must be dynamic as possible. So, I created one. I tried this last-last week, but I didn’t completed it since I’m very busy for that past few weeks. Just now, I got a chance to solve the problem.

Before that, this is my old pagination;

function paginationTest($offset = 0, $css = 'padding: 5px 5px 5px 5px; border-top: 1px #D7D7D7 dashed; text-align: right;')
	{
		global $cfgMax;
		global $globalProjectID;

		$MAXPAGE = $cfgMax;
		//$MAXPAGE = 2;

		$sqlQ = "SELECT * FROM pagetest";
		$result = mysql_query( sprintf( $sqlQ ) );

		$MaxValue = mysql_num_rows($result);
		$MaxPerPage = $MAXPAGE;
		$OffSet = 0;
		$PageCounter = 1;
		$TotalPages = ceil( $MaxValue / $MaxPerPage );

		if ($MaxValue >= $MAXPAGE)
		{
			$rdata = '<div style="'.$css.'">Page: ';
			for ($i = 0; $i < $TotalPages; $i++)
			{
				$OffSet = $MaxPerPage * $i;
				if ($OffSet == $offset)
				{
					$rdata .= ' '.($i + 1).' ';
				}
				else
				{
					$rdata .= ' <a href="pagination.php?offset='.$OffSet.'">'.($i + 1).'</a> ';
				}
			}
			return $rdata.'</div>';
		}
		else
		{
			return ' ';
		}
	}

And here’s my new pagination… :)

	function paginationTest($page = 1, $cssContainer = 'padding: 5px 5px 5px 5px; border-top: 1px #D7D7D7 dashed; text-align: right;', $cssLink = '', $cssCurrent = '')
	{
		global $MAXPAGE;
		if ($page == 0)
		{
			$page = 1;
		}

		$sqlQ = "SELECT COUNT(id) FROM pagetest";
		$result = mysql_query( sprintf( $sqlQ ) );

		$tmp = mysql_fetch_row($result);
		$MaxValue = $tmp[0];
		unset($tmp);
		mysql_free_result($result);

		$MaxPerPage = $MAXPAGE;
		$endPage = $MaxValue / $MAXPAGE;
		$endPage = ceil($endPage);

		if ($page <= 5)
		{
			$start = 1;
			$end = 10;
		}
		else
		{
			if (($page + 5) > $endPage)
			{
				$start = $endPage - 9;
				$end = $endPage;
			}
			else
			{
				$start = $page - 4;
				$end = $page + 5;
			}
		}

		$rdata = '<div style="'. $cssContainer .'">';
		if ($MaxValue >= $MAXPAGE)
		{
			if ($page > 5)
			{
				/*
						DEFINITION: if previous is the previous page
						NOTES: if you like this pagination, just uncomment this and comment the other method (line 116)
				*/
				//$prevPage = $page - 1;

				/*
						DEFINITION: sif previous is the page block
						NOTES: if you like this pagination, just uncomment this and comment the other method (line 110)
				*/
				$prevPage = $start - 1;

				$rdata .= ' <a href="pagination.php?offset=0" class="'.$cssLink.'">«</a> ';
				$rdata .= ' <a href="pagination.php?offset='.$prevPage.'" class="'.$cssLink.'"><</a> ';
			}
			for ($i = $start; $i <= $end; $i++)
			{
				if ($page == $i)
				{
					$rdata .= ' <a href="javascript:alert(\'Page already shown!\');" class="'.$cssCurrent.'">'.$i.'</a> ';
				}
				else
				{
					$rdata .= ' <a href="pagination.php?offset='.$i.'" class="'.$cssLink.'">'.$i.'</a> ';
				}
			}
			if (($page + 5) < $endPage)
			{
				/*
						DEFINITION: if next is the next page
						NOTES: if you like this pagination, just uncomment this and comment the other method (line 144)
				*/
				//$nextPage = $page + 1;

				/*
						DEFINITION: if next is the page block
						NOTES: if you like this pagination, just uncomment this and comment the other method (line 138)
				*/
				$nextPage = $end + 1;

				$rdata .= ' <a href="pagination.php?offset='.$nextPage.'" class="'.$cssLink.'">></a> ';
				$rdata .= ' <a href="pagination.php?offset='.$endPage.'" class="'.$cssLink.'">»</a>';
			}
		}
		else
		{
			$rdata = ' ';
		}
		$rdata .= '</div>';

		return $rdata;
	}

that’s it… :) Hope this would help …

Epoch Time

Info.Tech, PHP, Software Development, Visual C#, Web Development View Comments

I saved this information due to I used it all the time in my programming either PHP, JavaScript nor Visual C#. I found very very useful.. :)

——————————————–

What is epoch time?

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z). Literally speaking the epoch is Unix time 0 (midnight 1-1-1970), but ‘epoch’ is often used as a synonym for ‘Unix time’. Many Unix systems store epoch dates as a signed 32-bit integer, which might cause problems on January 19, 2038 (known as the Year 2038 problem or Y2038).

Human readable time Seconds
1 minute 60 seconds
1 hour 3600 seconds
1 day 86400 seconds
1 week 604800 seconds
1 month (30.44 days) 2629743 seconds
1 year (365.24 days) 31556926 seconds

How to get the current epoch time in …

Perl time
PHP time()
Ruby Time.now (or Time.new). To display the epoch: Time.now.to_i
Python import time first, then time.time()
Java long epoch = System.currentTimeMillis()/1000;
Microsoft .NET C# epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
VBScript/ASP DateDiff("s", "01/01/1970 00:00:00", Now())
Erlang calendar:datetime_to_gregorian_seconds(calendar:now_to_universal_time( now()))-719528*24*3600.
MySQL SELECT unix_timestamp(now()) More information
PostgreSQL SELECT extract(epoch FROM now());
Oracle PL/SQL SELECT (SYSDATE - TO_DATE('01-01-1970 00:00:00', 'DD-MM-YYYY HH24:MI:SS')) *
24 * 60 * 60 FROM DUAL
SQL Server SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
JavaScript Math.round(new Date().getTime()/1000.0) getTime() returns time in milliseconds.
Unix/Linux Shell date +%s
PowerShell Get-Date -UFormat "%s" Produces: 1279152364.63599
Other OS’s Command line: perl -e "print time" (If Perl is installed on your system)

Convert from human readable date to epoch

Perl Use these Perl Epoch routines
PHP mktime(hour, minute, second, month, day, year) More information
Ruby Time.local(year, month, day, hour, minute, second, usec ) (or Time.gm for GMT/UTC input). To display add .to_i
Python import time first, then int(time.mktime(time.strptime('2000-01-01 12:34:00', '%Y-%m-%d %H:%M:%S'))) - time.timezone
Java long epoch = new java.text.SimpleDateFormat ("dd/MM/yyyy HH:mm:ss").parse("01/01/1970 01:00:00");
VBScript/ASP DateDiff("s", "01/01/1970 00:00:00", time field) More information
MySQL SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD
More on using Epoch timestamps with MySQL
PostgreSQL SELECT extract(epoch FROM date('2000-01-01 12:34'));
With timestamp: SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40-08');
With interval: SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
SQL Server SELECT DATEDIFF(s, '1970-01-01 00:00:00', time field)
JavaScript use the JavaScript Date object
Unix/Linux Shell date +%s -d"Jan 1, 1980 00:00:01" Replace ‘-d’ with ‘-ud’ to input in GMT/UTC time.

Convert from epoch to human readable date

Perl Use these Perl Epoch routines
PHP date(output format, epoch); Output format example: ‘r’ = RFC 2822 date More information
Ruby Time.at(epoch)
Python import time first, then time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(epoch)) Replace time.localtime with time.gmtime for GMT time. More information
Java String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
VBScript/ASP DateAdd("s", epoch, "01/01/1970 00:00:00") More information
MySQL from_unixtime(epoch, optional output format) The default output format is YYY-MM-DD HH:MM:SS more …
PostgreSQL PostgreSQL version 8.1 and higher: SELECT to_timestamp(epoch); More information Older versions: SELECT TIMESTAMP WITH TIME ZONE 'epoch' + epoch * INTERVAL '1 second';
SQL Server DATEADD(s, epoch, '1970-01-01 00:00:00')
Microsoft Excel =(A1 / 86400) + 25569 Format the result cell for date/time, the result will be in GMT time (A1 is the cell with the epoch number). For other timezones: =((A1 +/- timezone adjustment) / 86400) + 25569.
Crystal Reports DateAdd("s", {EpochTimeStampField}-14400, #1/1/1970 00:00:00#) -14400 used for Eastern Standard Time. See Timezones.
JavaScript use the JavaScript Date object
Unix/Linux Shell date -d @1190000000 Replace 1190000000 with your epoch, needs recent version of ‘date’. Replace ‘-d’ with ‘-ud’ for GMT/UTC time.
PowerShell Function get-epochDate ($epochDate) { [timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($epochDate)) }, then use: get-epochDate 1279152364. Works for Windows PowerShell v1 and v2
Other OS’s Command line: perl -e "print scalar(localtime(epoch))" (If Perl is installed) Replace ‘localtime’ with ‘gmtime’ for GMT/UTC time.

———————————–

Reference: http://www.epochconverter.com

[PHP] Converting a value to MAC address format

Info.Tech, PHP, Web Development View Comments

php_codeI just want to post this since someone ask about it. It might help if someone in this world is searching for an answer with the same problem my friend does. This is about converting a value of 0014:f8c4:9e32 or 0014f8c49e32 to 00:14:f8:c4:9e:32

Now here’s some answers for that…

function convertMACAddress($input)
{
    // clean up unwanted characters
    $input = preg_replace( '/[^a-zA-Z0-9]/', '', $input);

    // initiate character positioning
    $pos = 0;

    // declare output container
    $output = '';

     // if given MAC is invalid, terminate process and return an error
     if (strlen($input) < 12)
     {
           return '[Unrecognized MAC address]';
     }

    // initiate convertion...
    for ($i = 0; $i < 6; $i++)
    {
           if ($i == 0)
           {
                  $output .= substr($input, $pos, 2);
           }
           else
           {
                   $output .= ':'.substr($input, $pos, 2);
            }
            $pos += 2;
     }

      return $output;
}

That’s it… Problem solved. :) If need a sample code, please download the source -> Mac Convert (74) — Have fun coding..

[PHP] Shortcuts of If-Else statement

Info.Tech, PHP, Web Development View Comments

When I learn PHP last September 2005, I was little bit confuse in PHP if-else statement… especially a statement contains with ? and : but somehow, I got it right. I post this cause somebody ask again what’s the difference. So told him, its all the same and its just a shortcuts.

<?php

$authenticated = true;

// [1] standard if-else statement
if ($authenticated)
{
     echo
‘YES’;
}
else
{
      echo ‘NO’;
}

// same with [1] :P
if ($authenticated) { echo ‘YES’; } else { echo ‘NO’; }

// [2] lil bit shortcut
if ($authenticated)
      echo ‘YES’;
else
      echo ‘NO’;

// [3] the shortcut
echo $result = ($authenticated) ? ‘YES’ : ‘NO’;

?>

Or let me say its an evolution of if-else statement… Hahaha.. or maybe the laziness of the programmer. :P So got it? hehehehe..

[PHP] How to upload a file

Info.Tech, PHP, Web Development Comments Off

I would like to share this script to all since most of my friends ask how to create an upload script using PHP.

Download the PHP script at;

  1. Main Download: Simple Upload Demo (51)
  2. Mirror 1: simple_upload.zip

Upload File Demo: http://www.cable21.net/camilord/simple_upload/index.html

Modification according to your preferred setup

Its default upload directory is uploads/ and to change this, just change the line 19;

// set upload destination
$uploaddir = “uploads/”;

In the script, it is capable to validate allowed file types. As default, images files are only allowed to be uploaded. To change this, just edit the upload.php at line 37.

// allowed file types
$validMIME = array(‘jpg’,‘jpeg’,‘bmp’,‘png’,‘gif’);

Just add any file extension you want to allow… Sample;

// allowed file types
$validMIME = array(‘jpg’,‘jpeg’,‘bmp’,‘png’,‘gif’,‘doc’,‘zip’,‘pdf’);

So I just allowed Document, Zip and PDF files…

That’s all.. I think everything is understandable.. hehehe.. Please read also the comments.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Log in