Showing posts with label PERL. Show all posts
Showing posts with label PERL. Show all posts

Monday, November 21, 2011

PHP Weird Initialization Criteria

It is weird that before pushing data to an array, one needs to initialize the array before that.

Here's what I did to avoid this weird error (pushed data will be missing):



$my_array = array(); // initialize $my_array is of array type

array_push($my_array, "myTestData1");



If you are used to PERL, this is weird.
Read More »

Wednesday, October 5, 2011

PHP fwrite/fputs Newline Problem in IIS7

The problem I encountered is that I couldn't write a newline to the file under PC environment.

Then I tried this and it worked:


fwrite($fh, "My Text...\r\n");



Instead of just \n, I need to have the \r\n pair under PC environment. No such issue using PERL under PC. Weird.
Read More »

Wednesday, March 10, 2010

Fixing PERL script saved in UTF-8 Format using Notepad

If your PERL script needs to display non-English texts, say Japanese or Chinese, usually you will save your script in UTF-8 format. Problem arises if you are using Notepad to save the UTF-8 format as it adds the BOM (Byte Order Mark) header to the file.

The problem is that PERL won’t run the UTF-8 file with BOM header once it is uploaded to the server. However, it will run fine if you are running with later version of Apache locally using your Windows based PC.
To solve this problem (if you are not running locally with latest Apache), the following is a PERL script to rid of the first three bytes (BOM header) of the UTF-8 file saved using notepad:

#!c:\perl\bin\perl.exe #or use path to your perl executable
$input = “myfile.pl”;
$output = “myfile_utf8.pl”;
print "Content-type: text/html\n\n";
binmode(STDIN);
binmode(STDOUT, ":utf8");
open(IN, "$input");
@ALL = <IN>;
close(IN);
$all = join("",@ALL);
$BOM_removed = substr $all, 3;
open(OUT, ">$output");
print OUT $BOM_removed;
close(IN);
print “Conversion done! File is output to $output.”;

You can assign $input and $output variables to the file names you desire. These PERL codes can be saved in normal ANSI format.

After the conversion, if the output file doesn’t contain any non-English characters, Notepad will assume it is a ANSI file. Don’t worry. Try to put some non-English characters in your $input file and run this conversion, the $output file will show up as UTF-8 file using Notepad (when you do a Save As…, you will see the format).

Upload the $output file to your server using ASCII transfer mode (not Binary mode), your $output file will run without any Internal Server Error message after chmod (change file permission) $output file to 755.

Please also make sure your $input/$output PERL script prints "Content-type: text/html; charset=utf-8\n\n" HTML header for proper UTF-8 content output.


Note: Do not save the $output file again with notepad, it will lose its "charm". :)
Read More »

Tuesday, March 2, 2010

Diplaying Server Date Using PERL and Javascript

I only find PHP solution after googling around, but I wanted to use PERL. Here’s how I did it:


PERL side:

#!/usr/bin/perl

$time = localtime(time);
print "Content-type: text/html\n\n";
print "var serverdate='$time';";
exit;


Javascript side:

<script language="JavaScript" src="/cgi-bin/getservertime"></script>
<script type="text/javascript">
<!--
document.getElementById('time').innerHTML = '<font face=tahoma size=1>'+serverdate+'</font>';
//-->
</script>




Please place a <div id=”time”> </div> somewhere in the your HTML body to receive the server date from this javascript. The PERL script name is getservertime and you can change accordingly if you like.
Read More »

Saturday, February 27, 2010

Sending Email using PERL Net::SMTP module

I recently bumped into a problem with my old CGI script that sends emails from LINUX/UNIX server in PERL platform.



I later found out that the server I rented/shared is no longer supporting emails using the sendmail –t command. I found a solution to it by using the PERL module of Net::SMTP.


Here are the codes that saved my day:



use Net::SMTP;

$smtp = Net::SMTP->new("smtp.yourdomain.com");

$smtp->mail("username\@ yourdomain.com");
$smtp->to($touser);
$smtp->data();
$smtp->datasend("MIME-Version: 1.0\n");
$smtp->datasend("From: $fromuser\n");
$smtp->datasend("To: $touser\n");
$smtp->datasend("Subject: $subject\n\n");
$smtp->datasend("$messagebody");
$smtp->dataend();
$smtp->quit();



Make sure you know your smtp address before using these codes. I found many other similar codes online but none is fully working. These codes are fully tested with no problem. Let me know if find any problem with these codes.



P.S.: Please replace your own variables for $touser, $fromuser, $subject, $messagebody in PERL.
Read More »

Wednesday, February 24, 2010

PERL connect to DBI subroutines (smart detect)

Here are the codes:


sub connect_db {
 if (!$connect) {
  $dbh = DBI->connect("dbi:mysql:your_db_name;host=localhost:3306;user=db_user;password=user_password") or die "Couldn't connect to database: DBI::errstr\n";
  $connect = 1;
 }
}


sub disconnect_db {
 $dbh->disconnect;
 $connect = 0;
}


Try to use as little disconnect as possible as connecting and disconnecting may cause delay and to the HTML connection. As you may already know you may need to install the DBI module for PERL before running these codes. You also need to create a database and obtain the database name, user id and password in order to connect to the database.
Read More »

Tuesday, February 23, 2010

Installing PERL CRYPT:SSLEAY module

This module is important for SSL - LWP connections. I used this command to install the module using ppm (usually in c:\Perl\bin):

ppm> install http://theoryx5.uwinnipeg.ca/ppms/Crypt-SSLeay.ppd

I just reran the command a few days ago and it is still working!
Read More »

Thursday, February 18, 2010

Who says CGI/PERL is obsolete?

Some say CGI/PERL is slow.
Some say CGI/PERL has security problem.
Some say CGI/PERL is phased out by PHP.
...

But there is still one "BIG" website that is still using CGI/PERL until today. Have you seen this:

https://www.paypal.com/my/cgi-bin/webscr

If CGI/PERL is not good, why is PayPal still using it until today to deal with large sum of credit everyday?
UPDATE (April 4th, 2016): It has been six years since I posted this comment about PERL's popularity. But I now would say PERL is already obsolete for me as PHP is far well supported by the developer's community. PERL's support doesn't seem to exist anymore as most developers are now using PHP as their favorite scripting software running on the server side. Whether Paypal is still using PERL, nobody knows as it is important for website like Paypal to refrain the visitors from knowing the type of scripting language it is using. Even the question now is whether PHP will be phased out by free online web editors such as Wordpress, Drupal and Blogger.
Read More »

Tuesday, February 16, 2010

Speeding Up PERL in CGI Output

Usually I will do the following setting:


select(STDOUT);
$| = 1;
print "Content-type: text/html\n\n"; # whenever your browser sees this, it will blank the screen
$| = 0;


$| = 1; is to make sure to send data to client web browser immediately. It is like a "live" connection.

$| = 0; is to make sure to send data to client web browser only when the buffer is filled.

Such configuration can make the user feel that the response of the web is fast but it is actually just slightly faster.

If you use $| = 1; throughout the HTML code spitting process, your web can be slower as it is wasting the buffer and burst capability of TCP connections. Unless you want to have live output capability such as the ping result from the server, avoid setting it to live output mode.
Read More »

Monday, February 15, 2010

PERL Trick to Make Alternative Row Color

The mod or modular operator in PERL (%) is responsible for this trick.

The following codes show how I did it:


.
.
.
$total_hits++;

if ($total_hits % 2) { $rowcolor = " bgcolor=#FFEEEE"; }
else { $rowcolor = " bgcolor=#FFFFFF"; }
.
.
.


These codes are in a loop to list out all the items. You can place the $rowcolor in the <TR> tag. The rows displayed will be in pink and white alternatively.
Read More »

Saturday, February 13, 2010

PERL codes to check whether a image file Exists

Here are the codes I have been using. The key is to use the "-e" in the if statement. Other than that it is not a hard programming problem:


if (-e "../htdocs/prod/small/$image_id.jpg") {
$img_path = "/prod/small/$image_id.jpg";
}
else {
$img_path = "/img/default_small.gif";
}


Those in red (the relative path to the cgi-bin directory) depend on your server's configuration. One needs to ftp into the server to see the structure.

You can also "elsif" to support more file format rather than just jpg image files. Usually when an image file is not found, I will point it to a default "no photo" image file so that it looks more professional.

You then use the $img_path in the <img src=...> HTML tag.

Hope this helps.
Read More »

Tuesday, February 9, 2010

Randomize Image Display using PERL

From HTML side:

<img src="/cgi-bin/myimage">

From PERL side (myimage):

#!/usr/local/bin/perl

print "Content-type: image/gif\n\n";

$pic[0] = "image0.gif";
$pic[1] = "image1.gif";
$pic[2] = "image2.gif";

$rndm = int(rand()*3);

open(PIC, "./../image/$pic[$rndm]");
binmode(PIC);
binmode(STDOUT);

while (<PIC>) {
print $_;
}
close(PIC);


This is neat. Seldom a programmer reveals this simple but neat secret.
Read More »

Friday, February 5, 2010

How to process Selection/Radio/Checkbox data in PERL?

This corresponds with the previous post:

For Pull-Down Selection:

if ($form_data{'country'} eq "Australia") {
.
.
.
}


For Radio Selection:

if ($form_data{'type'} eq "orange") {
.
.
.
}


For Checkbox Selection:

if ($form_data{'type'} eq "on") {
.
.
.
}





Please check with the previous posts for the the input/selection HTML. Please also note that you need to have the legendary cgi-lib.pl library called before you can use $form_data{'---'} hash table that captures the query strings from your HTML document.


P.S.: Everything is quite straigtforward except the checkbox query string. If the checkbox is checked, the variable will be sent with a "on" data. Those that are not checked will not be defined at all in PERL.
Read More »

Friday, January 22, 2010

Direct Download Link with PERL - CGI

There are times that you need to make sure you record or filter before your visitors download your files. Here are codes if you are running CGI using PERL:


open(FILE, "../file/$fn"); #file is the directory and $fn is the filename
@file=<FILE>;
close(FILE);

print "Content-Type:application/x-download\n";
print "Content-Disposition:attachment;filename=$fn\n\n";
print @file;



Note that you don't need to print the html header :"Content-type: text/html\n\n" before this. You can also add the Content-Length header so that the browser know the size of your file but the size has to be accurate to avoid error.


Read More »

Wednesday, January 20, 2010

PHP vs CGI - PERL vs ASP

What a strange round-up comparison.

I like CGI - PERL combination because Linux server is free to set up if I want to build my own web server. PERL is much powerful than ASP after comparing both programming platform. Many tasks can be completed with minimum amount of codes compared to ASP. Anyway, ASP is obsolete and ASP.NET is just as versatile as PERL programming environment.

I like PHP as it is like the combo of PERL and ASP. It has the server side thing as well as the PERL programming flexibility.

As for ASP, I don't see much benefit of using it beside its ability to make use of default.asp similar to index.html to save user from typing the URI. Calling the root directory is sufficient to run the web site. This is briefly explained in my second post on the 2nd of January 2010.

In conclusion, all three are acceptable to be used as your website programming platform. It is up to you to decide. If you are running a Windows server, you seem to have not much choices. If you are using a Apache based web server, you get to choose either PHP or PERL. Actually I like PERL a lot as it is way flexible and versatile but the /cgi-bin/ path showing on the web address is just too risky and it is too inviting to hacker's attack. Hackers instantly know what you are up to. PHP could be the most popular and hassle-free web programming environment. With the support of free database softwate, MySQL, to run database, it is like a gift to web programmers.




Read More »

Tuesday, January 12, 2010

PERL TCP Socket Codes with LWP (HTTPS/SSL, POST method)

Planned to delay this but what the hack, just let the series continues.

For such connection, LWP is needed:


use LWP::UserAgent; #call up the LWP module
my $ua = LWP::UserAgent->new;

$req = new HTTP::Request POST => "https://www.yourSSLURL.com/script?var=variable";
$req->header('Accept' => 'text/html');

$req->content_type('application/x-www-form-urlencoded');
$req->content("a=a&b=c&c=c");


$res = $ua->request($req);

#to transfer $res->as_string to @HTML array
open (TEMP, ">temp.txt");
print TEMP $res->as_string;
close (TEMP);
open (TEMP, "temp.txt");
@HTML = ;
close(TEMP);
`rm -f temp.txt`; #Use Unix command to remove the temporary file, you can also use randomized filename to avoid duplicates



There you go. Still cannot think of a way to bypass LWP. Maybe someday...




UPDATE - You may see this error if your web server cannot handle LWP SSL:

501 Protocol scheme 'https' is not supported (Crypt::SSLeay not installed) Content-Type: text/plain Client-Date: Sun, 21 Feb 2010 02:31:47 GMT

Client-Warning: Internal response LWP will support https URLs if the Crypt::SSLeay module is installed. More information at .


OR


use Crypt::SSLeay; #LWP will support https URLs if the Crypt::SSLeay module is installed.
More information at .



That means you need to install Crypt::SSLeay PERL module beside LWP.

Here's the instruction at your PERL ppm:

ppm> install http://theoryx5.uwinnipeg.ca/ppms/Crypt-SSLeay.ppd

to install Crypt::SSLeay in your web server.
Read More »

Monday, January 11, 2010

PERL TCP Socket Codes without relying on LWP (Part 2: POST method)

As promised, here are the codes:

replace (GET method):
print S "GET /Login.aspx?a=apple&cat=main HTTP/1.1\nHost:www.theSiteDomainName.com\n\n";



with (POST method):

print S "POST /Login.aspx HTTP/1.1\nHost:www.theSiteDomainName.com\nContent-Length: 16\n\na=apple&cat=main"




Note that you don't need to put the query string in the URI. Instead you need to post the query string as output data. You also need to specify the length of your data. This is a tricky part. The easiest way is to put the data in a word file and check out the file properties (statistics) for the word count.



There are still two other types of TCP connection which I haven't mentioned:



1) HTTPS

2) Send and Receive Cookies



Hope I housekeep my info and post them up when the time is right.
Read More »

Sunday, January 10, 2010

PERL TCP Socket Codes without relying on LWP

I don't quite like to use the modules in PERL as I am always paranoid about its absence in certain hosting companies.

Here are the codes to make a TCP connection and send and receive a HTTP GET query without the LWP module:

use Socket;

my $peer = sockaddr_in(80,inet_aton("www.theSiteDomainName.com"));

socket(S, PF_INET, SOCK_STREAM, getprotobyname("tcp"));

connect(S, $peer) or die "Couldn’t connect!";

print S "GET / HTTP/1.1\nHost:www.theSiteDomainName.com\n\n"; # Make a GET query to root directory of the host server

select STDOUT;

while (<S>) {
$reply .= $_;
if (/<\/html>/) { close(S); }
}

#the reply is stored in the $reply
.
.
.


You can also send a query string to the host script by:
print S "GET /cgi-bin/script.pl?a=$action&cat=main HTTP/1.1\nHost:www.theSiteDomainName.com\n\n";


But for POST query, it is a bit different. Will post up the codes tomorrow!

Today is a Sunny Sunday. I will take some time off to relax. See ya!
Read More »