World Languages
Computer Tips

List of Translation Agencies
Europe Property Investments

Translation Jobs
Translation Resources

Translation Services
Tree planting Accounting Software

 

PHP Programming Notes

 

I compiled these notes for myself while I was learning how to program in PHP. It could be useful for you as you learn PHP and I would recommend that you read my introduction to php programming if you are just beginning. At the bottom of that page there are also a few links to PHP tutorials.

 

Table of Contents for this Page

 

HTML. 4

Tables. 5

For borders on the outside only. 5

Table Layout 5

Meta tags. 6

Comments. 6

Bullets. 6

Wordpress. 6

Moving files etc. 6

Giving WordPress its Own Directory While Leaving the WordPress Index File in the Root Directory. 6

PHP. 7

Variable: 7

Date variable: 7

Time() 8

Time duration. 8

Operators: 8

Forms: 9

How to submit a form using Java: 10

creating files from forms. 11

Conditional Statements: 11

Looping: 12

Arrays. 12

Function your.function.name (optional function arguments) { … }. 18

Spam Protection. 23

Deny Access Referrer Spammers. 24

Regular expressions (RegEx) 25

Run a script at intervals. 26

Refresh page. 26

Security. 29

on A2 – files outside of public html 31

Sessions. 31

Trimming. 31

Javascript 32

Basics. 32

Variables. 32

Foreach loops. 32

Auto redirect after X seconds. 33

Popout window.. 33

Autopopout: 33

SQLite. 34

Grabbing from database. 34

While statement (also WHERE LIKE) 34

Foreach. 35

Updating a table. 35

Combine tables. 35

Various. 35

Importing data. 36

MySQL. 36

Joining tables. 36

Group by. 36

Update table. 36

Grabbing from tables. 37

sql queries within phpmyadmin. 37

Chmoding. 37

Uploading files to webhost sites. 38

Placing application system in different folders. 38

sql.pl file. 39

Full file paths in related html pages (explanation to programmers) 40

Another database. 40

Notes on b.cgi system.. 40

Payment Form.. 40

Drop down list of which form of payment they want 40

Notes on Yuri’s communication system. 41

Limiting the size of uploaded files: 41

MS Access notes. 41

Windows. 41

Registry. 41

how to make new item in registry for right click menu. 41

Debugging. 42

On A2hosting, mostly CGI 42

Cron jobs. 43

My snippets. 43

Header banner 43

Server management 43

logging. 43

Tools. 43

Foreign Scripts. 43

Google Analytics. 43

Clickheat 44

Google plus. 44

Addthis. 44

Bleet 46

OnlyWire’s buttons: 46

For 001: 46

PayPal’s donate button. 46

 

 

program snippets:

<pre> </pre> - seems to put a block of text into a scrollable box! Can probably do the same with pics etc., within a table of defined width.

 

error reporting is defined in php.ini

- more details about ini: http://devzone.zend.com/manual/ini.html

 

http://www.phpjobscheduler.co.uk/ - free script to run any page or whatever at scheduled intervals.


 

HTML

Auto Refresh:

<META HTTP-EQUIV=refresh CONTENT="1; URL=http://machine/doc3.html">

- this does every '1' second – another dude had double quotes around "refresh"


Tables

For borders on the outside only

<table border="0"

style="border-collapse: collapse; border-style: solid; border-width: 10px; border-color: #800000;" width="900" id="AutoNumber2" bgcolor="#800000" cellpadding="0">

Table Layout

Try fixed table layout in CSS?

 

http://www.hotdesign.com/seybold/

 

 

Inside of the table cell with the content, surround the content with a div like so:
<td>
<div style="width:576px;height:400px;overflow-x:hidden;overflow-y:auto">
content
content
content
</div>
</td>

 

Can also add scroll to a table cell?

<td style="overflow-x:hidden; overflow-y:auto; height:100px;">

 


 

http://translationstop.com/lists/?p=subscribe

http://translationstop.com/lists/?p=unsubscribe

edit URL where users can update their details
http://translationstop.com/lists/?p=preferences

 

Meta tags

<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">

Comments

<!-- This is commented out -->

Bullets

<ul class="greenarrow">

<li>...

in CSS:

 

ul.greenarrow {

list-style-image: url('../me/CV/pics/bullet_030.gif')

}

Wordpress

Moving files etc

If you want to test before you change a database name or username, you must temporarily change "siteurl" and "home" in the database table "wp_options" (through phpMyAdmin or similar).

- If you had any kind of rewrites (permalinks) setup you must disable .htaccess and reconfigure permalinks when it goes live.

- more at: http://codex.wordpress.org/Moving_WordPress, also http://help.yahoo.com/l/us/yahoo/smallbusiness/webhosting/wordpress/wordpress-26.html is good

Giving WordPress its Own Directory While Leaving the WordPress Index File in the Root Directory

more at: http://codex.wordpress.org/Giving_WordPress_Its_Own_Directory

PHP

Download PHP 5 (4?? - http://www.php.net/manual/en/installation.php) from http://www.php.net/ and install on computer, to test da scripts…

 

Comments:

/* and this is a

multi-line

comment */

 

Variable:

Every variable has a name. In PHP, a variable name is preceded by a dollar ($) symbol and must begin with a letter or underscore, optionally followed by more letters, numbers and/or underscores. For example, $popeye, $one and $INCOME are all valid PHP variable names, while $123 and $48hrs are invalid.

- case sensitive, so $me is different from $Me or $ME.

 

Printing/Output

- can use 'echo' command, or 'print'

 

Strings and quotations:

String values may be enclosed in either double quotes ("") or single quotes(''). (Quotation within the string itself can be "escaped" with a backslash (\) character.) String values enclosed in double quotes are automatically parsed for special characters and variable names; if these are found, they are replaced with the appropriate value.

 

Join the dots:

 

$a = 'the';

$b = 'games';

$c = 'begin';

$d = 'now';

 

// combine them using the concatenation operator

// this returns 'the games begin now<br />'

$statement = $a.' '.$b.' '.$c.' '.$d.'<br />';

 

Date variable:

// Prints something like: Monday 15th of August 2005 03:12:46 PM

echo date('l dS \of F Y h:i:s A');

time() is a function holding the current unix timestamp, and date() is a function used to format that value. For hours (h above), use capital H to convert to military time.

http://www.w3schools.com/PHP/php_date.asp (also saved in Downloads/Install/PHP/Manual/FUNCTIONS/

Time()

$nextWeek time() + (24 60 60);

                   // 7 days; 24 hours; 60 mins; 60secs
echo 'Now:       'date('Y-m-d') ."\n";
echo 'Next Week: 'date('Y-m-d'$nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: 'date('Y-m-d'strtotime('+1 week')) ."\n";
?>

The above example will output something similar to:

Now: 2005-03-30

Next Week: 2005-04-06

Next Week: 2005-04-06

 

Time duration

echo time_duration(100000000); 
// 3 years, 2 months, 19 hours, 22 minutes, 16 seconds 

echo time_duration(100000000, null, true); 
// 3 years, 2 months, 0 weeks, 0 days, 19 hours, 22 minutes, 16 seconds 

echo time_duration(100000000, 'yMw'); 
// 3 years, 2 months 

echo time_duration(100000000, 'd'); 
// 1157 days 

Operators:

 

http://www.php.net/manual/en/language.operators.arithmetic.php

http://www.php.net/manual/en/language.operators.string.php

 

// equality operator

$result = ($mean == $mode);

 

// not-equal-to operator

$result = ($mean != $mode);

 

// inequality operator

$result = ($mean <> $mode);

- these examples yield TRUE (1) or FALSE (0) statements

- more comparison operators at: http://www.php.net/manual/en/language.operators.comparison.php

 

four logical operators designed to group conditional expressions together – AND (&&), OR (||), XOR (xor) and NOT (!)

XOR returns true if either of two conditions are true, or returns false if both conditions are true

 

Forms:

 

<form action="message.php" method="post">

Enter your message: <input type="text" name="msg" size="30">

<input type="submit" value="Send">

</form> erase: <input type="reset" value="Reset"

name="B2">

 

If not to another php file but within self/the same file, then:

<form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method = "POST">

 

If using the GET approach, can use something like this:

<a href='form.php?MillID=$id'>details</a>, alternatively

="clock2.php?custtime=<?echo $custtime;?>"

 

As you probably already know, the "action" attribute of the <form> tag specifies the name of the server-side script (message.php in this case) that will process the information entered into the form. The "method" attribute specifies how the information will be passed.

 

Then:

 

<body>

<?php

// retrieve form data

$input = $_POST['msg'];

- possibly with “$_POST['msg']”; instead

// use it

echo "You said: <i>$input</i>";

?>

</body>

 

When you enter some data into form.htm (let's say "Boo"), and submit it, the form processor message.php will read it and display it to you ("You said: Boo"). Thus, whenever a form is submitted to a PHP script, all variable-value pairs within that form automatically become available for use within the script, through a special PHP container variable: $_POST. You can then access the value of the form variable by using its "name" inside the $_POST container, as I did in the script above.

 

Obviously, PHP also supports the GET method of form submission. All you need to do is change the "method" attribute to "get", and retrieve values from $_GET instead of $_POST. The $_GET and $_POST variables are actually a special type of PHP animal called an array

- "POST" is the value that sends the data to the processing agent by storing it in the body of the form, while "GET" sends the data by adding it to the URL, separating it from the address with an exclamation mark

 

If you want to call a function within another php file after pressing POST, you can use a hidden value:

<form action="/mydir/myscript.php" method="post">
<input type="hidden" name="func" value="myfunction">
<input type="hidden" name="parameter[]" value="value1">
<input type="hidden" name="parameter[]" value="value2">

 

and in myscript.php:
if (isset($_POST['func'])) {
call_user_func_array($_POST['func'], $_POST['parameter']);
}

- AJAX toolkits can take care of all this, as already mentioned.

 

How to submit a form using Java:

 

Mention the name attribute in the form tag
<form name='myform' action='formmail.pl'>

Suppose you want to submit a form when the user clicks on a hyperlink. The code below shows how to do it.

<form name="myform" action="handle-data.php">
Search: <input type='text' name='query'>
<A href="javascript: submitform()">Search</A>
</form>

<SCRIPT language="JavaScript">
function submitform()
{
  document.myform.submit();
}
</SCRIPT>

Java form validation: http://www.javascript-coder.com/html-form/javascript-form-validation.phtml - saved at c:\Downloads\Reading\HTML Tutorial\javascript_form validation\ with instructions above

 

creating files from forms

<?  
 
// The next line opens a file handle to a file called output.txt
// the file handle is like an alias to the file
// the a in the fopen function means append so entries
// will be appended to the output.txt file
 
$out = fopen("output.txt", "a");
 
// if the file could not be opened for whatever reason, print 
// an error message and exit the program
 
if (!$out) {
    print("Could not append to file");
    exit;
}
 
// fputs writes output to a file.  the syntax is where to write
// followed by what to write
 
// $name is the contents of the name field in the sample form
// \t represents a tab character and \n represents a new line
 
 
fputs($out,"$_POST[name]\t");
fputs($out,"$_POST[yearborn]\t");
fputs($out,"$_POST[favcolor]\t");
fputs($out,"$_SERVER[REMOTE_ADDR]\n");
print("Thanks you for completing our survey.  You have been assimilated.");
 
fclose($out);
 
?>

 

Conditional Statements:

 

$msg = $numTries > 10 ? 'Blocking your account...' : 'Welcome!';

 

here, the ? acts as a shortcut for an IF-ELSE block:

 

if ($numTries > 10) {

$msg = 'Blocking your account...';

}

else {

$msg = 'Welcome!';

}

 

elseif – basically like using 'if', except that, as soon as the condition is met (yields TRUE), it skips the rest and jumps to the end of the block.

 

switch() statement (similar to if-elseif-else, but has default value), see http://www.php.net/manual/en/control-structures.switch.php.

 

Looping:

 

++ is same as + 1 , ie-

$total++ is functionally equivalent to $total = $total + 1.

-- is the opposite (minus 1)

 

while () – like an 'if', but stays within if as long as it is TRUE, after which only THEN does it jump to the next step

 

do-while – same as while() but runs at least ONCE

do {

do this!

} while (condition is true)

- http://www.php.net/manual/en/control-structures.while.php

http://www.php.net/manual/en/control-structures.do.while.php

 

for – to do a while() FOR a certain time etc.

for (initial value of counter; condition; new value of counter) {

do this!

}

- condition: it will remain in for() as long as Condition=TRUE

- http://www.php.net/manual/en/control-structures.for.php

 

Arrays

Array – as opposed to a single value (and, being a list of values, once again each must begin with a letter or underscore, and can optionally be followed by more letters, numbers and underscores)

- first value in array always starts with numerical representation of 0 (not 1)

- useful in forms where a certain entry has many possible values etc.

 

$pizzaToppings = array('onion', 'tomato', 'cheese', 'anchovies', 'ham', 'pepperoni');

- the various elements of the array are accessed via an index number, with the first element starting at zero. So, to access the element 'onion', you would use the notation $pizzaToppings[0], while 'anchovies' would be $pizzaToppings[3]

 

keys in an array - =>

such as - $fruits = array('red' => 'apple', 'yellow' => 'banana', 'purple' => 'plum', 'green' => 'grape');

- The => symbol is used to indicate the association between a key and its value.

ie- $fruits['yellow'] would yield 'banana'

 

array_push() adds a variable to an array, like

- array_push($pasta, 'tagliatelle'); - adds another array value to the 'pasta' array

array_pop($pasta); - REMOVES the last value from the 'pasta' array

array_shift($pasta); - I think this one removes the FIRST value..

array_unshift($pasta, 'tagliatelle'); - ADDS a value to the beginning of the array

 

explode() breaks an array up, implode() pieces it together (with another word, for example – when printing..)

 

sort() returns an array alphabetically A-Z, while rsort() is reverse (Z-A)

 

To print an array, you can use a for() loop…

$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses');

for ($x = 0; $x < sizeof($artists); $x++) {

echo '<li>'.$artists[$x];

}

- note that the sizeof() used to keep the for() statement from going on forever (sizeof often used in arrays)

 

- but PHP4 made the above easier using foreach(), so you don't need sizeof() anymore:

$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n Roses');

foreach ($artists as $a) {

echo '<li>'.$a; }

- works with associative arrays too!

 

array_keys() and array_values() return the keys or values of an associative (=>) array

Some examples:

$arr = array('a'=>1, 'b1'=>2, 'b2'=>3, 'c'=>4, 'd'=>5);

print "Test 1:\n";
foreach ($arr as $key => $val) {
    print "Key $key, Value $val\n"; }

gives:

Test 1:
Key a, Value 1
Key b1, Value 2
Key b2, Value 3
Key c, Value 4
Key d, Value 5

Note: As stated further up the foreach is consuming a lot of memory if used within large arrays - that is - if the array consists of for instance large objects. I had a case where a foreach caused me to run out of the 256 MB memory that PHP is allowed to handle - but changing to a for() statement completly removed both memory and CPU load.

I think I read somewhere that you that you cant put a foreach loop within a foreach loop?

- this is because it COPIES the array data and uses that. The geeks suggested using a for() loop instead.

- apparently important to use Unset with foreach()…

- While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.

Another example:

$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";
 
foreach( $employeeAges as $key => $value){
     echo "Name: $key, Age: $value <br />";
}
(which translates as: "For each element of the $employeeAges associative array I want to refer to the key as $key and the value as $value." – note that you do NOT have to use "key" or "value", but any string name will work…)
produces:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34

- seems that the "as" is like "now do this", where the => returns BOTH the key and the value of the association..

 

Adding Values to the End of an Array

To insert more values into the end of an existing indexed array, use the [] syntax:

$family = array('Fred', 'Wilma');

$family[] = 'Pebbles'; // $family[2] is 'Pebbles'

Assigning a Range of Values

The range( ) function creates an array of consecutive integer or character values between the two values you pass to it as arguments. For example:

$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);

$letters = range('a', 'z'); // $numbers holds the alphabet

$reversed_numbers = range(5, 2); // $numbers = array(5, 4, 3, 2);

count() – returns the number of keys in an array

You can put arrays within arrays using string variables to create multi-dimensional arrays, and get to the particular values by using [square] brackets – such as $value = $multi[2][0]; (the first value of the third string in multi…)

Interpolate multidimensional arrays using curly brackets, such as echo("The value at row 2, column 0 is {$multi[2][0]}\n");

list() copies all the values of an array into variables, such as list($variable, ...) = $array;

extract () and compact() are used to take values or whatever out of an array and perform some magic

 

Working with files:

 

such as printing a file's contents:

 

$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' or die('Could not open file!');

// open file

$fh = fopen($file, 'r') or die('Could not open file!');

// read file contents

$data = fread($fh, filesize($file)) or die('Could not read file!');

// close file

fclose($fh);

// print file contents

echo $data;

 

explanation:

fopen() –

'r' - opens a file in read mode

'w' - opens a file in write mode, destroying existing file contents

'a' - opens a file in append mode, preserving existing file contents

fread() is the number of bytes to be read.

fclose() technically not necessary as PHP does that anyway once the script ends, but can be good practice…

die() kills a script in case of error, like the file path or name is not valid…

 

alternatively, you can use file() to open a file and convert each of its lines into a new value in an array, such as:

$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' or die('Could not read file!');

// read file into array

$data = file($file) or die('Could not read file!');

// loop through array and print each line

foreach ($data as $line) {

echo $line;

 

Don't want the data in an array? Try the file_get_contents() function, new in PHP 4.3.0 and PHP 5.0, which reads the entire file into a string:

$file = '/usr/local/stuff/that/should/be/elsewhere/recipes/omelette.txt' ;

// read file into string

$data = file_get_contents($file) or die('Could not read file!');

// print contents

echo $data;

 

include() and require() also suck data from files into PHP (require shuts the script down if there is an error; include not strict..)

- for example, with a webpage's header(.php) and footer(.php). You can have a single file for each, and just import those at the required location every time. If you ever need to make a global change…

- to include it on another page, just use:

<?php include('header.php'); ?>

require_once() and include_once() are used to make sure the file is opened and read only once, for performance reasons…

 

to write as opposed to read, use fwrite() – you need to use the 'w' variable when opening the file, such as:

fwrite($fh, "Look, Ma, I wrote a file! ") – double quotes result in RETURN (end of line)

- works on binary files http://www.php.net/manual/en/function.fopen.php

- PHP allows file_put_contents(), which uses a string

 

Checking the status of files, such as

file_exists() – does it?

is_dir() - returns a Boolean indicating whether the specified path is a directory

is_file() - returns a Boolean indicating whether the specified file is a regular file

is_link() - returns a Boolean indicating whether the specified file is a symbolic link

is_executable() - returns a Boolean indicating whether the specified file is executable

is_readable()- returns a Boolean indicating whether the specified file is readable

is_writable()- returns a Boolean indicating whether the specified file is writable

filesize() - gets size of file

filemtime() - gets last modification time of file

filamtime() - gets last access time of file

fileowner() - gets file owner

filegroup() - gets file group

fileperms() - gets file permissions

filetype() - gets file type

 

So, to print a file into html file from a binary file, you might:

 

$data = file('/usr/local/stuff/that/should/be/elsewhere/omelette.txt') or die('Could not read file!');

/* first line contains title: read it into variable */

$title = $data[0];

// remove first line from array

array_shift($data);

?>

 

<h2><?php echo $title; ?></h2>

 

<?php

/* iterate over content and print it */

foreach ($data as $line) {

echo nl2br($line);

 

- nl2br() function converts regular text linebreaks into the HTML equivalent, the <br /> tag

 

Function your.function.name (optional function arguments) { … }

 

- the function can print the result, or RETURN () it (to be used in another function or string etc.)

- note that the Return statement terminates the function (?)

 

for the optional arguments, can set default values, such as $name="John Doe" as opposed to just $name to avoid script errors (such as if a value or argument is not defined..)

 

func_num_args()

func_get_args()

$arg

 

- $Variables defined within functions cannot be called upon or do not apply outside of the function (you need to have them defined "globally", like a default)

- unless you define them as global, such as

global $variable;

- however, this global setting only applies after the function runs…

- some variable as super global, meaning they always apply (I guess they are part of the php language), such as:

$_SERVER, $_POST and $_GET

(http://www.php.net/manual/en/language.variables.predefined.php, and http://www.php.net/manual/en/language.variables.scope.php)

 

Referencing: function setDay(&$day)

- by using the & before the $variable, it can get overridden (7th file lesson of easy course) - http://www.zend.com/manual/language.references.php

 

Class

 

Like a separate object or little program you can use. It defines an object, but you can alter the definitions/properties later.

 

To create a class, say:

class Object { … }

To create a new object based on that class, say:

$changed.object = new Object; (the "new" is the special PHP command).

- classes are by default Public, but can also be redefined as Private or Protected, depending on how you want to make it possible to change any of the properties

such as, during the defining stage of variables at the beginning of classes:

public $property1;

private $property2;

or

public function you.function() etc.

To change the individual properties of your object, you use:

$changed.object->name = "new propery";

- which would change the $name property within the original Object.

where: $changed.object->action(); would perform the function "action" defined within Object, and apply it to the new/changed object.

- in effect, the -> is used to connect to the original class, whereby the $ is simply omitted or understood.

 

$this – used to access variables and functions which are local ONLY to the class they are in (defines them as "private" within the class(?))

_construct() – is used to give all future constructions of an object a particular property. Basically assigning default values to given properties(variables?).

 

extends – can add properties and functions to a new (child) class based on a previous (parent) class, such as:

Class new.object extends object {…}

- but if you do not want properties to be "extendible" to child classes, simple stop that possibility by defining the parent class as Final:

final class object {..}

 

If a child class does not have a constructor, it automatically loads the constructor of the parent class (?)

 

MySQL

 

mysql_fetch_row() – used to fetch data from a row of a table..

list() – similar to the above

mysql_fetch_assoc() - to represent each row as an associative array of field-value pairs

mysql_fetch_object() - returns each row as an object with properties corresponding to the field names

- Row values can thus be accessed using standard

object->property notation

mysql_fetch_array() – combination of the fetch row and fetch assoc above (http://www.php.net/manual/en/function.mysql-fetch-array.php)

ext/mysqli – in PHP5 – ie, would use mysqli_fetch_row() instead (and so on with the rest of above) – is faster and more powerful

- can use the new function in this case, similar to child classes above, construct new db tables and pass on properties etc.

mysql_num_rows() – used to determine how many rows are in a table

mysql_free_result() – erases the data from ram etc. after it is fetched, to not slow down the system etc.

mysql_close() – close the db connection once done…

 

SQLite

 

lighter and easier, and uses the same commands as mysql: http://sqlite.org/lang.html

- apparently incorporated in PHP5, otherwise go to http://sqlite.org/download.html

- no copyright problems, totally open source…

http://sqlite.org/sqlite.html for command line instructions

- In order to achieve simplicity, SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, stored procedures, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth. If you need some of these features and do not mind the added complexity that they bring, then SQLite is probably not the database for you. SQLite is not intended to be an enterprise database engine. It is not designed to compete with Oracle or PostgreSQL.

- In manifest typing, the datatype is a property of the value itself, not of the column in which the value is stored. SQLite thus allows the user to store any value of any datatype into any column regardless of the declared type of that column. (There are some exceptions to this rule: An INTEGER PRIMARY KEY column may only store integers. And SQLite attempts to coerce values into the declared datatype of the column when it can.)

- variable-length records – (If you store a single character in a VARCHAR(100) column, then only a single byte of disk space is consumed.)

- check out: http://sqlite.org/download.html – have I downloaded the sqlite program? – to run sqlite3 shortcuts…

http://sqlite.org/sqlite.html (already read?)

- The SQLite source code contains no license since it is not governed by copyright. Instead of a license, the SQLite source code offers a blessing:

May you do good and not evil

May you find forgiveness for yourself and forgive others

May you share freely, never taking more than you give.

 

sqlite_query()

sqlite_fetch_array()

sqlite_fetch_object()

sqlite_fetch_all() - retrieves the complete set of records as an array of arrays; each element of the outer array represents a record, and is itself structured as an array whose elements represent fields in that record.

- good because it loads the table all at once and then automatically closes it while processing continues, instead of loading each row etc, one at a time…

sqlite_fetch_single() – good if you are only interested in data from a particular (single) column (use the while() function to circulate through many records…)

sqlite_close()

SQLiteResult()

 

If you want to restructure tables, just make a copy of a db, create a new one, and import the old one back into it, such as:

For example, suppose you have a table named "t1" with columns names "a", "b", and "c" and that you want to delete column "c" from this table. The following steps illustrate how this could be done:

BEGIN TRANSACTION;

CREATE TEMPORARY TABLE t1_backup(a,b);

INSERT INTO t1_backup SELECT a,b FROM t1;

DROP TABLE t1;

CREATE TABLE t1(a,b);

INSERT INTO t1 SELECT a,b FROM t1_backup;

DROP TABLE t1_backup;

COMMIT;

 

SQL Commands: to download:

 

Select

Select fieldname, fieldname, fieldname
from tablename;

good list at: file:///C:/Downloads/Reading/PHP%20Tutorial/SQL/sql_quickref.asp.htm

 

Copy column(s) from one table INTO another:

SELECT Column1, Column2, Column3,

INTO Table2

FROM Table1

 

Sessions

 

http://www.php.net/manual/en/ref.session.php

 

Cookes: setcookie()

http://www.php.net/manual/en/features.cookies.php

http://www.php.net/manual/en/function.setcookie.php

 

- sessions are necessary for login type websites, since each subsequent webpage visited within that login framework would have a session validation thing before entering the page, otherwise anyone could punch in the exact web address of the other pages, as such bypassing the login page..

 

XML

 

SimpleXML works easily with PHP5

- http://www.php.net/manual/en/ref.simplexml.php

 

Debugging and error messages

 

http://www.php.net/manual/en/ref.errorfunc.php#errorfunc.constants

 

E_ALL - to see all fatal and non-fatal errors generated by your script

error_reporting() – to control which errors are displayed to the user, such as:

error_reporting(E_ERROR); - report only fatal errors

error_reporting(~E_ERROR); - report no fatal errors

 

You can (and should) turn off display_errors, stipulate an error_log file and switch on log_errors

 

set_error_handler() - http://www.php.net/set-error-handler

 

- some errors caused by bad input data, for which you should use: input validation routine

empty(), isset(), trim() ; is_array(), sizeof()

is_numeric() – make sure the input is a number

intval() – extract the integer part of a value

strlen() function - returns the length of a string

checkdate() – make sure an inputted date is valid (ie- not Feb 29..)

 

- mysql doesn't tell errors but will often just convert wrong input into another value…

 

TCL

 

download: http://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html (do I already have?)

Examples: http://www.tcl.tk/about/dos2unix.html, http://www.tcl.tk/about/netserver.html

- try to get tcl/sqlite packages, and copy from it… - or more explanations etc.

- look up where tcl is used to make webpages

 

JAVA – (http://www.prototypejs.org/learn?)

 

http://www.prototypejs.org/blog – apparently where people upload examples and scripts?

http://www.json.org/

http://www.prototypejs.org/assets/2008/4/22/prototype_update_helper.js – update helper (with the new version 1.6 I downloaded)

http://www.getfirebug.com/ - for debugging while viewing in Firefox (?..)

http://www.prototypejs.org/api – general documentation

- apparently Java and Javascript totally different – research the two?

 

- The onUninitialized, onLoading, onLoaded, and onInteractive callbacks are not implemented consistently by all browsers. In general, it's best to avoid using these.

 

AJAX – not sure what this is, but seems like a subpart of Java or something?

- Ajax.Updater - Element.update() method – something about automatically updating code in a website?

 

Spam Protection

 

From WordPress:

When a spam-bot comes in, it hits the file directly and usually does not leave a referrer. This allows for some nifty detection and action direct from the server. If you are not familiar with Apache directives, then write the following in your root directory .htaccess file::

RewriteEngine On

RewriteCond %{REQUEST_METHOD} POST

RewriteCond %{REQUEST_URI} .wp-comments-post\.php*

RewriteCond %{HTTP_REFERER} !.*yourdomain.com.* [OR]

RewriteCond %{HTTP_USER_AGENT} ^$

RewriteRule (.*) http://%{REMOTE_ADDR}/$ [R=301,L]

This will:

1.      Detect when a POST is being made

2.      Check to see if the post is on wp-comments-post.php

3.      Check if the referrer is in your domain or if no referrer

4.      Send the spam-bot BACK to its originating server's IP address.

NOTE 1: In the 4th line, change yourdomain.com to your domain.xxx without the www or any prefix for that matter.

NOTE 2: There is a slim chance that someone's browser will not send the referral, but this is extremely rare.

This essentially deflects the spam-bot back on itself.

Deny Access Referrer Spammers

Many bloggers show referrer's to their site or links from which people came to visit their site. Spammers exploit this and indiscriminately spam blogs (even bloggers who do not have this feature enabled) with referral links pointing to their spammy sites. They end up wasting your resources, polluting your legitimate referrer's list and slowing down access for your readers.

In an effort to economize their resources, spammers often send out comment spam bots with their spam referrers for that two-in-one-shot effect. Consequently, you can block quite a few comment spam bots by blocking the referrer spam.

Once you know which referrer URL you'd like to block, and believe me you'll know, you can keep them out by adding the following into your .htaccess file:

SetEnvIfNoCase Via evil-spam-proxy spammer=yes
SetEnvIfNoCase Referer evil-spam-domain.com spammer=yes
SetEnvIfNoCase Referer evil-spam-keyword spammer=yes
SetEnvIfNoCase Via pinappleproxy spammer=yes
SetEnvIfNoCase Referer doobu.com spammer=yes
SetEnvIfNoCase Referer poker spammer=yes
 
Order allow,deny
allow from all
deny from env=spammer

The aforementioned .htaccess rules

You can add this to the top of any PHP page, putting the actual IP address where the xxx or yyy is.

<?php
$block = array("xxx.xxx.xxx.xxx", "yy.yy.y.yyy");
 
if (in_array ($_SERVER['REMOTE_ADDR'], $block)) {
    header("Location: http://google.com/");
    exit();
}
?>

 

Regular expressions (RegEx)

^ start of string – ie the first character in a string of characters

$ end of string

[a-z] letters a-z inclusive in lower case

[A-Z] letters A-Z inclusive in upper case

[0-9] numbers 0-9 inclusive

[^0-9] no occurrences of numbers 0-9 inclusive

( ) – round brackets for an exact string (not jumbled etc.) - only these can be used for 'grouping'

? zero or one of the preceding character(s) - ie- colou?r matches colour or color.

* zero or more of preceding character(s)

+ one or more of preceding character(s)

{2} 2 of preceding character(s)

{2,} 2 or more of preceding character(s)

{2,4} 2 -- 4 of preceding character(s) –ie- \b[1-9][0-9]{2,4}\b matches a number between 100 and 99999 ('\b' means start or end or something like that)

. any character - should use sparingly cause apparently sucks a lot of processor power

(a|b) a OR b

\s empty space (known as whitespace)

 

For our example, how about something like?

{2}/$ - the last two characters before the last / ??

 

10-29-03, 05:01 AM

here's a method that uses "wildcards" and also deals with case sensitive issues.

 

 

<?

$url = strtolower($_SERVER['HTTP_HOST']);

if (substr($url, -20) == 'subdomain.domain.org') {

header("location: /politics/");

exit;

}

?>

 

 

essentially, make HTTP_HOST lowercase (in case people type odd things into their browsers). then, compare the last 20 characters (subdomain.domain.org). if it matches, then send it to /politics.

 

this way avoids the "expensive" (really nothing with this little code) regex parsing, and does the job of "wildcard" matching.

 

So, .* would be a wild card, cause . is any character, and the * after it means that this any character can appear any number of times (including zero – otherwise use +)..

 

http://www.powergrep.com/ - some big powerful search (&replace) tool?

Run a script at intervals

 

Sample script:

1.           <?php
2.           ignore_user_abort(); // run script in background
3.           set_time_limit(0); // run script forever
4.           $interval=60*15; // do every 15 minutes...
5.           do{
6.              // add the script that has to be ran every 15 minutes here
7.              // ...
8.              sleep($interval); // wait 15 minutes
9.           }while(true);
10.       ?>

Refresh page

Refresh parts of a page with php, use iframes or AJAXresearch "frameset" – I guess a frame within a page? - update the target frame with javascript: http://developer.apple.com/internet/javascript/iframe.html

http://www.thescripts.com/forum/thread561233.html

http://www.thescripts.com/forum/post2198507-5.html

http://www.phppeanuts.org/site/index_php/Pagina/229/pntRef/0/pntScd/d/14.+AJAX+and+Tabs.html

http://www.tizag.com/ajaxTutorial/ - maybe?

http://www.w3schools.com/Ajax/Default.Asp

http://aleembawany.com/2005/09/01/ajax-instant-tutorial/

http://ajaxpatterns.org/Periodic_Refresh

Next:

http://www.dhtmlgoodies.com/index.html?page=ajax

Did you download ajax, i.e. the Simple Ajax Code Kit from SACK ? - http://www.twilightuniverse.com/resources/code/sack/

checkout prototype

Javascript part:

<iframe id="quicksee" src="somePage.html"></iframe>

<input type="button" value="refresh" onClick="document.getElementById('quicksee').contentWindow.location.reload()">

setTimeout("document.getElementById('quicksee').contentWindow.location.reload()", 30 * 1000); // ? – apparently not tested

document.getElementById("refresh").innerHTML=some html here – another dude said

Frameset: (I guess simple, bonehead html)

<html>

<head>

<title>Frame Sets</title>

</head>

<frameset rows="95,*" framespacing="0" border="0">

<frame src="refresh.html">

<frame src="norefresh.html">

</frameset>

<noframes>

You are using an old browser.

<body>

</body>

</noframes>

</html>

Ajax:

function loadXMLDoc(url)
{
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest()
  xmlhttp.open("GET",url,true)
  xmlhttp.send(null)
  xmlhttp.onreadystatechange=state_Change
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
    if (xmlhttp)
    {
    xmlhttp.open("GET",url,true)
    xmlhttp.send()
    xmlhttp.onreadystatechange=state_Change
    }
  }
}

function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
  {
  // if "OK"
      if (xmlhttp.status==200)
      {
      document.getElementById('THEDIVYOUWANTTOCHANGESNAME').innerHTML=xmlhttp.responseText;
      }
  }
  
} // Just stick in the name of the div which has the content you want replaced, simple as. It's been a while since i modified it and i know it's been stripped back, so if anyone thinks it needs anything else let me know, but i don't think it does.

- combine the above with:

window.setTimeout( "loadXMLDoc( \"Your URL here\" );", 3000 ); // will reload every 3 seconds (but looks like only entire page, boohoo)

- Use a div tag with id=”output” where you want to see the output and use div with onclick=”loadurl(”xxxx”) where you wanna set the clickable link, that’s easy…

- It's inevitable that users will leave their browser pointing at websites which they're not actually using. The rising popularity of tabbed browsing - now supported by all the major browsers - only exarcebates the problem. You don't want to keep refreshing the page for idle users, so use Heartbeat to detect if the user is still paying attention. - http://ajaxpatterns.org/Heartbeat

- investigate the jsTools.module in the downloads area which I believe has a tool to help with this. the dynamicload part of JStools, which does what you seek with AJAX, i think. - dynamicload IS the way to go, I have blocks refreshing and working fine. But documentation is non existing, so does anyone know how to include the code in node / page template?

 

Security

sla.ckers.org

www.0x000000.com

ha.ckers.org

www.gnucitizen.org

www.owasp.org

www.cert.org

www.sans.org

www.securityfocus.com


 

Other stuff to download:

- "We need to view the list of references, add new articles and journals, edit and delete existing records. There are a lot of database management tools. In particular, PHP5 comes with SQLite Admin. "

- check up on converting dbase to sqlite, possibly mysql. – once get that going with Vadim's perl script, make webpage offering free convert, and then to sell the software for 100bucks… - learn how to call cgi scripts from php or html etc. Make sure the site is not hackable so that some dude can't automate. maybe captcha? Must upload etc., and then can download somehow. file size limit. some temp folder which erases after a while… (or registration and send by email (try zip first – or ready for downloading, to show how fast it works. Would need to erase after certain time period. Make sure they download one file before uploading another.)? – erase right afterwards) – maybe I could find a perl script myself? – find out what my cpu speed limit is on hypermart? I guess users will need to register, and then a temp folder be created just for them, and users with the folders be deleted after some time. Consider setting up different user rights if some wanna pay to increase the file limit…

- download about security…

 


To download:

http://weblogs.java.net/blog/gmurray71/archive/2006/08/restricting_acc.html ajax security

 

on A2 – files outside of public html

 

Site files need to be in the public_html directory. However you can create symlinks from your public_html directory to other locations outside of your public_html directory.

 

ln -s target link_name

 

For example to symlink test.php to /home/user/scripts/test.php you would use the following command in your public_html directory:

 

ln -s /home/user/scripts/test.php test.php

 

Sessions

At the top of each page which you wanna include in the session:

<?php

session_start();

$_SESSION[‘varname’] = “debabrata”; // the variable you wanna save in the session – probably just the very first time it is defined. In subsequent pages you would just call on the variable in the usual manner, such as:

echo "$_SESSION[‘varname’]";

//YOUR CODE HERE

session_destroy(); // only if you wanna stop the session

Session("name") = Null – if you only wanna kill one variable…

?>

Trimming

If you need to trim a string from the beginning and end of a string, then this function maybe prove handy.[otherwise, trimming is generally used to remove any number of individual characters]

<?php
function lrclean($str,$rm) {
  
$i = strlen($rm);
  do {
    if (
substr($str,0,$i) == $rm) {$str = substr($str,$i);}
  } while (
substr($str,0,$i) == $rm);

  do {
    if (
substr($str,-$i,$i) == $rm) {$str = substr($str,0,-$i);}
  } while (
substr($str,-$i,$i) == $rm);
  
  return 
$str;
}

// prints 'text'
echo lrclean('xyztextxyz','xyz');
?>

Javascript

Basics

Variables

var x=5;

 

If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables.

These statements:

x=5;

 

y=x-5;
z=y+5;

 

Let's consider a situation where you plan to display the name of the visitor on the page. To do this you would first have to get the visitor's name (we'll shortly see how to achieve this), store it in a variable and send the result to the document.write() method. Here we'll examine how we can pass variables to JavaScript methods.

document.write("Your name is " + vis_name);

 

function writeSentence(argument1,argument2) {
document.write('The '+argument1+' is '+argument2+'.<br />'); }

var a = 'table';
var b = 'chair';
var c = 'red';
var d = 'blue';
writeSentence(a,c);
writeSentence(b,c);
b = 'other ' + b;
writeSentence(b,d);

 

Foreach loops

var quote= new Array(5) 
quote[0]="I like JavaScript."; 
quote[1]="I used to like Java."; 
quote[2]="JavaScript rules."; 
quote[3]="Help! JavaScript Error!"; 
quote[4]="Just Kidding.";

Notice that when we do this, we leave off the semiclon at the end of the array definition, and use semicolons at the end of each element we define.

So far, it has only made things more complicated. However, this array can now be used as part of a loop, using the value of the index numbers as a variable:

var x=0; 
for (x=0; x<5; x++)
 
{
 
alert(quote[x]);
 
}

I THINK ALSO:

var person={fname:"John",lname:"Doe",age:25}; 

for (x in person)
{
document.write(person[x] + " ");
}

Some samples in javascript after </form> (validation) in 11079 Nootka Reforestation job.

Auto redirect after X seconds

<script language="JavaScript">

setTimeout('window.location="c_relat.php?idproject=<?=$idproject?>"',10000);

</script>

<center>You will be automatically redirected in 10 seconds.</center>

Popout window

001:

<script src="../../samples/includes/script.js" type="text/javascript" language="javascript"></script>

Creating combined: (can use file:///C:/Web/PHP_Portable/Program/www/localhost/Clients/001/travel-Europe/caravan-design/buy-a-camper-van-motorhome-caravan-for-sale.html as a template)

<script src="../../javascript/popups.js" type="text/javascript" language="javascript"></script>

[above is above /head, below is at the click point – but I think the below script might include the above necessities, or some other combined script, or make one.. You do the ../ as many time as it takes to get to the localhost level (translationstop root)]

<a href="javascript:popup('Terms_and_Conditions','http://001yourtranslationservice.com/Terms.and.conditions.htm', 'yes', 800, 650, 200, 5);" class="text"><strong>Terms and Conditions</strong></a>

 

Autopopout:

[the following drawn from SEO page]

 

<script src="temp/tender.js" type="text/javascript"></script>

 

<span id="Rank" style="position:absolute; left:522px; top:1256px; width:398px; height:320px; border:1px none #000000; z-index:1; visibility: hidden;" class="commentbox"><div class="dialog"><div class="hd"><div class="c"></div></div><div class="bd"><div class="c"><div class="s">

 

<p>&quot;Rank&quot; is a page's position on google's search results. Because google is the most popular search engine covering 65% of the market (as explained above), this table focuses on google's results and rankings. These rankings will differ on other search engines.</p>

</div></div></div><div class="ft"><div class="c"></div></div></div></span>

 

At the point of mouseover:

 

<a class="txCOM" href="#" onMouseOver="MM_showHideLayers('CZ','','show')" onMouseOut="MM_showHideLayers('CZ','','hide')"> <dd align="center"><img src="pics/seo/yellow-ball.gif" width="14" height="14" border="0"></a>

SQLite

Grabbing from database

require_once("config.php"); <then copy config.php from Keta’s dbase thing, for example>

 

While statement (also WHERE LIKE)

 

$sql = "SELECT * FROM mills

WHERE Typeofmill LIKE '$_Type'

AND Region LIKE '$_Region'

ORDER BY Nameofmill

LIMIT $Offset,100";

$prepstatement = $db->prepare($sql);

$prepstatement->execute();

 

while($row = $prepstatement->fetch()) {

 

$id = $row["MillID"];

$name = $row["Nameofmill"]; }

 

Foreach

 

(note that you cannot have a Foreach within a Foreach, in which case you'd want to use a While as the main dude outside)

 

$sql = 'SELECT * FROM links';

$result = $db->query($sql);

$rowarray = $result->fetchall(PDO::FETCH_ASSOC);

 

foreach($rowarray as $row)

{

$page_url = $row[pagefrom];

$link_url = $row[linkto];

Updating a table

 

$sqlupdate = "update table set ";

$sqlupdate .= "field = '$new.value', ";

$sqlupdate .= "field2 = '$new.value2', ";

$sqlupdate .= "where id = '$id'";

 

Combine tables

Good instructions in SQLite Tutorial.htm in c:\Downloads\Reading\PHP Tutorial\SQlite\ - includes pivot tables, joins, unions and all the fancy shmancy

 

Try standard SQL:

SELECT * FROM table1,table2 WHERE table1.fieldname1 = table2.fieldname2

but maybe UNION instead of the =

Various

sqlite>.headers ON - to show the headers with a query result

 


Importing data

Create an .csv text file where the fields are separated by some character, such as ; . Make sure that this character is not used anywhere else in the text file, besides separation. You can export from Excel as Tab Delimited Text, for example, open it in Word to s&r ^t with ; and change the ending to .csv.

Create database with table in sqliteadmin and then import data.

MySQL

Joining tables

$query="SELECT preg.idproject,preg.iduser,preg.ptype

FROM preg,pinfo WHERE (pinfo.user='$idsession' AND preg.idproject=pinfo.id) ORDER by idproject";

$res=mysql_query($query);

$query="SELECT idproject,iduser,ptype

FROM preg LEFT JOIN pinfo ON preg.idproject=pinfo.id WHERE pinfo.user='$idsession' ORDER by idproject";

$res=mysql_query($query);

Group by

(to prevent repetitive listings…)

$query="SELECT pinfo.title,projects.idproject FROM pinfo,projects where (pinfo.id=projects.idproject&&pinfo.user='$idsession') GROUP by pinfo.id";

Update table

Get and post in the usual methods:

$comments=$_POST['comment'];

$projectID=$_GET['projectID'];

$fileID=$_GET['fileID'];

 

Then

$query="UPDATE filestatus SET comments='$comments' WHERE (projectID='$projectID' AND fileID='$fileID')";

connect();

$result=mysql_query($query);

 

where

function connect()

{

require('_config.inc.php');

$link=mysql_connect($dbhost, $dbuser, $dbpass)

or die("Could not connect");

mysql_select_db($dbname) or die("Could not select database _connect");

return $link;

}

Grabbing from tables

$result = mysql_query("SELECT * from pinfo WHERE id='$idproject'");

 

while($row = mysql_fetch_array($result))

{

echo $row['FirstName'] . " " . $row['LastName'];

echo "<br />";

}

 

$query="select files.id,files.realname,users.nick from files,users where files.name=\"$file\" and files.idproject=\"$idproject\" and files.userid=users.id";

 

$result=mysql_query($query);

$frow=mysql_fetch_array($result)

 

idfile=$frow[0]… etc

sql queries within phpmyadmin

UPDATE phplist_user_user SET htmlemail='1' WHERE htmlemail='0';

Chmoding

 

you have to chmod it owner 7 group 1 user 1 (711). which basically means that the owner of the file (you) can read, write, & execute it. a group member or end user can only execute it.

 

For the b.cgi application form file, use 755.

For clear understend type the command "ls". It show list of files and

access rights. 755 = rwx-r-x-r-x, 7(rwx) - for owner (you), 5(r-x) - for

group, 5(r-x) - for other. Always set 7 for you. Group have no much sense.

Other - is a visitors of your pages.

 

604 (read only for users, mean download)

 

Uploading files to webhost sites

 

Simply F5 using Total Commander, then can File – Change Attributes..

You might also consider Save As the file (in HTML editor) for UNIX format.

 

Placing application system in different folders

 

> okay, uploaded it to kenax.hypermart.net. I have some questions:

> 

> - I wanted to put all of your work into a folder "newsystem", because I

> didn't want your files (for example index.htm in the base directory) to

> copy over what I already have. But then I realised it does not work

 

Usually I set folder path in the top of script.

It's easy to change it if you wanna place software in another folder or

subfolder: $siteurl = "http://$ENV{'HTTP_HOST'}"; $siteroot =

"$ENV{'DOCUMENT_ROOT'}"; $tempdir = "$siteroot/temp"; $database =

"$siteroot/database"; $cgiurl = "$siteurl$ENV{'SCRIPT_NAME'}";

 

In real this variables is:

HTTP_HOST=kenaxx.hypermart.net

$siteurl = "http://kenaxx.hypermart.net"

 

DOCUMENT_ROOT=/home/users/web/b1194/hy.kenaxx

$siteroot="/home/users/web/b1194/hy.kenaxx"

 

$tempdir="/home/users/web/b1194/hy.kenaxx/temp"

 

$database = "/home/users/web/b1194/hy.kenaxx/database"

 

SCRIPT_NAME=/cgi-bin/b.cgi

$cgiurl = "http://kenaxx.hypermart.net/cgi-bin/b.cgi"

 

> because it refers to files in the base CGI folder, as opposed to the CGI

> folder relative to the location of the file. Can CGI files function if

> they are located within another folder, or do they have to be located in

> the base CGI directory? Either way, I'd like to separate

 

Seems like on hyp it is possible to place scripts in any folder

 

> your stuff from mine and always carefully control every upgrade you send

> me with any changes you make to the files before uploading them.

 

Good idea.

 

> I realise this may throw a lot of work on you and I apologise for that.

> Perhaps you will be able to figure out a good solution, or search and

> replace certain text within the files to change the path names. I am

> open to your suggestions.

 

Add new variable:

$vadimfolder="/newsystem";

And change other like here:

$siteurl = "http://$ENV{'HTTP_HOST'}$vadimfolder";

$siteroot = "$ENV{'DOCUMENT_ROOT'}$vadimfolder";

$tempdir = "$siteroot$vadimfolder/temp";

$database = "$siteroot$vadimfolder/database";

 

But below keep unchanged

$cgiurl = "$siteurl$ENV{'SCRIPT_NAME'}";

 

On this way you can move or copy scripts to other folder in short time

only change $vadimfolder. Or move it back to root - $vadimfolder="";

 

sql.pl file

 

> Also, I'd like such files as sql.pl to be in a password protected

> folder, such as "CGI-protected". Please rewrite that file so that it

> would work in such a directory, and write all such important files and

> move them in there.

 

You can move it in any folder. It need only right address of database

folder. If you place files like: /database/*.dbf /CGI-protected/sql.pl

then database address is as before - "../database". This mean 1) one

folder up from the current folder of the script, 2) open folder

"database". If you place files like: /newsystem/database/*.dbf

/CGI-protected/sql.pl then database address is as before -

"../newsystem/database"

Full file paths in related html pages (explanation to programmers)

The application all runs out of

http://kenax.hypermart.net/newsystem/cgi-bin/b.cgi

and the html pages are connected to that.

I know there is a script in this file above which describes the root directory of all that it refers to. Therefore, if you use something like

<link href="style.css" rel="stylesheet" type="text/css">

or

<td width="53%" background="img/t_bg_lines2.gif">

 

it will assume it is located somewhere else. Therefore, for all the work on these sites, it is better to describe the entire file path. The files you are working on are located in

 

http://kenax.hypermart.net/newsystem/temp/

 

so the above links should actually be stated as:

 

<link href="http://kenax.hypermart.net/newsystem/temp/style.css" rel="stylesheet" type="text/css">

or

<td width="53%" background="http://kenax.hypermart.net/newsystem/temp/img/t_bg_lines2.gif">

Another database

 

The decision is easy - just give it the range in counter.

I.e.: set the field VALUE in table COUNTER.dbf to 100000 or more (it is 8

digits integer).

 

Notes on b.cgi system

Payment Form

Drop down list of which form of payment they want

 

Found in the b.cgi file, starting from line 333 (Dec. 20, 2005), with the following script:

 

$p = '<OPTION VALUE="1"> Bank 1 ' . "\n";

$p .= '<OPTION VALUE="2"> Bank 2 ' . "\n";

$p .= '<OPTION VALUE="3"> Cheque ' . "\n";

$p .= '<OPTION VALUE="4"> Western Union ' . "\n";

$p .= '<OPTION VALUE="5"> MoneyGramm ' . "\n";

$p .= '<OPTION VALUE="6"> PayPal ' . "\n";

$p .= '<OPTION VALUE="7"> iKobo.com ' . "\n";

Notes on Yuri’s communication system

Limiting the size of uploaded files:

 

There is in the file ./communicate/c_conf.php the variable "$maxuplsize".

Now $maxuplsize is 1MB (1024000 in bytes). You can set another.

 

MS Access notes

Erased some queries etc. and stumbled on the following form, whose record source was the following (can prove useful..) - SELECT [Paying People].[Planter ID], Planter.[First Name], Planter.[Last Name], Planter.SIN, Planter.[How to Pay], [Paying People].[When Paid], [Paying People].[How Much Paid], [Paying People].[How Paid], [Paying People].Comments FROM Planter INNER JOIN [Paying People] ON Planter.[Planter ID]=[Paying People].[Planter ID];

Windows

Registry

how to make new item in registry for right click menu

To add extensions of your choice to the list: create a file, add the content below, save it as whatever.reg, and run it.

Note: Replace .png with the file extension you want to add and replace whatever with anything you want.

Windows Registry Editor Version 5.00
 
[HKEY_CLASSES_ROOT\.png\ShellNew]
"NullFile"=""

 

Debugging

On A2hosting, mostly CGI

Path to PERL /usr/bin/perl

Path to sendmail /usr/sbin/sendmail

 

- Operating system is LINUX and cgi scripts should be uploaded as such, but not sure if is necessary.

- Make sure to CHMOD 755 (executable).

- The line "Content-type: text/html" is special piece of text that must be the first thing sent to the browser by any CGI script. If you do not add this header to your script, the browser will reject the output of the script.

How do I invoke the Perl source debugger? - The "-d" flag will invoke the Perl source debugger and should be used when you have tried all other troubleshooting techniques and are still confused. This program is very good with identifying syntax errors. Through the command line, issue "perl -d " to execute your Perl script with the Perl source debugger.

How do I find the path to a particular program? - This can easily be done through SSH. Once you have established a connection to your account via SSH, you can use the "whereis" utility to find the path to the program you are trying to locate. For example, if you wanted to find the path to the "grep" program, you would type the following from the command line: "whereis grep". The program would then return any and all possible paths to this particular program.

How do I execute my Perl scripts through SSH/shell? - Issue the command "perl scriptname" from the command line, where "scriptname" is the relative or absolute path to the Perl script. If problems with the execution of the script are encountered, they will be reported on the terminal by the Perl Debugger. Use "perl -c scriptname" to test the syntax.

Is there a list of steps for debugging my Perl script(s)? - Below is a list of steps to go through to troubleshoot any problematic Perl scripts. These are the same troubleshooting methods employed by technical support at A2 Hosting:

1.                   Check the permissions on the script. It must be set executable.

2.                   Try running the script via SSH/shell to see if you get an errors by typing 'perl scriptname'

3.                   Make sure you saved the files in UNIX style text format as opposed to DOS. This will cause syntax errors.

4.                   You can also download your error logs through the control panel for possible additional information.

How do I use an SSH key to access the server? –

· Select 'SSH2 DSA' as the type of key to generate.

· Click 'Generate'.

· Optional: Enter a Key Passphrase and confirm the passphrase

· Copy the key in the 'Public key for pasting...' window to the clipboard.

· Select a place to save your public key (~/.ssh/id_dsa.pub is a good place).

· Select a place to save your private key (~/.ssh/id_dsa.priv is good).

· Follow steps 3 to 5 in the Mac/Linux instructions.

Permissions:

For this login method to work properly, the authorized_keys file is required to have the permissions set to 600, and the .ssh directory must be set to 700. This can be done from the command line with the following commands:

chmod 600 ~/.ssh/authorized_keys and chmod 700 ~/.ssh

 

Cron jobs

 

My snippets

Header banner

Use the one for Travel Chicks. Could be good template for pages too.

Server management

logging

- The log file I'm looking at is in /usr/local/apache/domlogs/kenaxx/ftp.translationstop.com-ftp_log

(there's a symbolic link to that directory at /home/kenaxx/access_logs).

Tools

I uploaded one of my tools, kwyk.php to the kenax.net root.

Foreign Scripts

Google Analytics

[above /head>: ]

 

<script type="text/javascript">

 

var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-20188968-1']);

_gaq.push(['_trackPageview']);

 

(function() {

var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

})();

 

</script>

Clickheat

Copy and paste the code below on your pages, just before the end of the page (before </body> tag). Change 001 to something else for a different group name (such as pages on another domain..):

 

<script type="text/javascript" src="http://translationstop.com/clickheat/js/clickheat.js"></script><noscript><p><a href="http://www.labsmedia.com/clickheat/index.html">Traffic analysis</a></p></noscript><script type="text/javascript"><!--
clickHeatSite = '';clickHeatGroup = '001';clickHeatServer = 'http://translationstop.com/clickheat/click.php';initClickHeat(); //-->
</script>

Google plus

to customize new size etc: http://www.google.com/webmasters/+1/button/

 

Standard small setup which seems to go okay with Addthis:

 

<!-- Place this render call where appropriate, above </header>-->

<script type="text/javascript">

(function() {

var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;

po.src = 'https://apis.google.com/js/plusone.js';

var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);

})();

</script>

 

<!-- Place this tag where you want the +1 button to appear -->

<g:plusone size="small" annotation="inline" width="200"></g:plusone>

* add that if wanna custom, otherwise default is 450.

 

Addthis

 

<!-- AddThis Button BEGIN -->

<div class="addthis_toolbox addthis_default_style">

<a href="http://www.addthis.com/bookmark.php?v=250&amp;username=kenax" class="addthis_button_compact">Share</a>

<span class="addthis_separator">|</span>

<a class="addthis_button_preferred_1"></a>

<a class="addthis_button_preferred_2"></a>

<a class="addthis_button_preferred_3"></a>

<a class="addthis_button_preferred_4"></a>

</div>

<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>

<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=kenax"></script>

<!-- AddThis Button END -->

 

Together:

 

<table style="width: 100%">

<tr>

<td style="width: 84px">&nbsp;</td>

<td>

<!-- Place this tag where you want the +1 button to appear -->

<g:plusone size="small" annotation="inline" width="200"></g:plusone>

<br>

<!-- AddThis Button BEGIN -->

<div class="addthis_toolbox addthis_default_style">

<a href="http://www.addthis.com/bookmark.php?v=250&amp;username=kenax" class="addthis_button_compact">Share</a>

<span class="addthis_separator">|</span>

<a class="addthis_button_preferred_1"></a>

<a class="addthis_button_preferred_2"></a>

<a class="addthis_button_preferred_3"></a>

<a class="addthis_button_preferred_4"></a>

</div>

<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>

<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=kenax"></script>

<!-- AddThis Button END -->

</td>

</tr>

</table>

 

Bleet

<a href="http://bleetbox.com/chat/"><img src="http://bleetbox.com/favicon.ico" width="16px" height="16px" style="vertical-align:middle;" /> Bleet about this page</a>

OnlyWire’s buttons:

For 001:

<a href="http://onlywire.com/submit?u=(insert url)&t=(insert title)&tags=(insert tags)" class="owbutton" title="Bookmark & Share this Article" target="_blank" style="display:inline-block !important; white-space:nowrap !important; padding:1px !important;text-decoration:none !important;line-height:12px !important;border:1px solid #CCCCCC !important;border-radius:6px !important;-webkit-border-radius:6px !important;-moz-border-radius:6px !important;background-color:#FFFFFF;">

<span style="display:inline-block !important;margin-right:0px !important;border-radius:4px !important;-webkit-border-radius:4px !important;-moz-border-radius:4px !important;background-color:#0095C8;"><img src="http://onlywire.com/images/onlywire_logo_small.png" style="height:15px !important;padding:0 !important;border:none !important;vertical-align:middle !important;display:inline !important;"></span>

<span style="display:inline-block !important;vertical-align:middle !important;font-weight:bold !important;padding-right:3px !important;padding-left:3px !important;color:#000000;font-size:12px;font-family:Arial, Helvetica, sans-serif;">Bookmark & Share</span>

</a>

PayPal’s donate button

 

<form action="https://www.paypal.com/cgi-bin/webscr" method="post">

<input type="hidden" name="cmd" value="_s-xclick">

<input type="hidden" name="hosted_button_id" value="QYP522F9H5UKG">

<input type="image" src="https://www.paypalobjects.com/WEBSCR-640-20110306-1/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">

<img alt="" border="0" src="https://www.paypalobjects.com/WEBSCR-640-20110306-1/en_US/i/scr/pixel.gif" width="1" height="1">

</form>

 

 

Hope it helped y'all!

 

Share |


Some of my other sites which might interest you:

 

All my computer tips
Introduction to PHP
Email archives on putting together a database (online and offline)
Website design (this and below services I can provide)
Programming
Search Engine Optimization



World Languagesa
Computer Tips

List of Translation Agencies
Europe Property Investments

Translation Jobs
Translation Resources

Translation Services
Tree planting Accounting Software


Copyright © KENAX, el Kosman - All Rights Reserved Worldwide.

contact