...Last update on 28/03/2005.
Php
Why Php ?

Because it's portable, simple to implement, there is heaps of info. about it and it's a fair language. However in the future i'll tend tu use perl insteadbecause i think it's faster.

  1. Performance
  2. Security
  3. Session
  4. Error
  5. Mail
  6. Webmaster
  7. Http Authentification
  8. XLS-MIME
  9. Rewrite
  10. @ and Mysql
  11. General
  12. Dates
  13. Html - Javascript - Css
  14. Design
  15. Javascript
  16. Font
  17. Html
  18. Upload
  19. Your Site
  20. SSI, shtml, Banner
  21. Http Post Request
  22. Encryption
  23. Meta Tags
  24. Exec
  25. Basic
- usefull:

mysql_insert_id() = LAST_INSERT_ID()
mysql_unbuffered_query() for optimisation

With HTML (Hosting tip):

- pear install apc
- opcode cache
- <<* Cache policy:
- cache control header into tags

* compression (not all) for long text !!

* Zend (must have - increase perf up to 70 %)

* server Zeus if you can afford.

- include OR require ?? just think about the name !!

mysql_free_result($sql);

It never hurts to free mysql results. They are always freed at the end of the script,but I like to put this in there anyways, just an old habbit and every little bit helps. (This is a saying from someone, i actually don t do that.)

1. Always initialize your variables.
2. Turn register_globals off in php.ini.
3. Set your error level to E_ALL in php.ini while debugging, to help check forany holes.
4. Use the built-in arrays.

Items 2 and 3 will be set to those values as a default shortly. After the release of PHP 4.0.7, PHP 4.1.0 will be made available with these changes.

- $_SERVER reserved Variables:
Php

ex:. $_SERVER['SCRIPT_NAME']

make sure the form can only be filled and submitted trought your site. Shouldn't really be a problem but in some cases its essential.

WEb sec

- GET AND POST :

Forms may be submitted either with Method="post" or Method="get". For "post", the form input is passed via standard input to the application. For "get", the form input is added to the URL, e.g.

test berkeley

With "get" requests, your computer monitor shows the values selected in the URL, so someone with good eyesight can see what you entered as long as it is on the screen.

Also, with "get" requests, the URL in the web access log for this site and possibly the web "referer" log on the next site you visit will show the values selected, raising privacy and confidentiality issues.

- Use one account, e.g. "webowner", to own the web pages and scripts, and another, e.g. "webrun", to run the serve

For security purposes, it is best:

* to turn off automatic directory listings
* to turn off following symbolic links by the server
* to turn off the "exec" form of server side includes

The "referer" field passed to CGIs comes from the browser, and is therefore not trustworthy

Perl has a "taint mode" which is very helpful in avoiding security problems.

Shell scripts are very difficult to code securely, and should be avoided.

PHP is difficult to use securely with the default configuration, and difficult to use when configured securely.

C has the best performance, but is harder to code and you must watch out for buffer overflows (use length checking routines such as fgets() and strncpy() instead of gets() and strcpy()).

To improve trustworthiness and guard against replay attacks:

* check the host returning the cookie or hidden variable is the same one it was sent to
* provide for session time outs
* provide a way for users to log out, terminating the session
* encrypt the session id

Unfortunately, there are a number of vulnerabilities in which cookies may be tampered with or stolen by other web pages. Do not use them for sensitive information.

Replaying logins

Even after your CGI or the browser decides a session has timed out, it may be possible for an attacker to use the back button or a cache copy to go back to the login page and re-login. To prevent this, create a random key for each login page, save it on the server and pass it to the browser in a hidden variable, and only allow the random key to be used once to log on.

Consider:

show pl
test berkeley, passwd
Passwd
passwd

The first is an attempt to display the source of the program "show.pl", to get clues about the application; the others are attempts to get the /etc/passwd file.

Prevention: Don't allow "../" in input and check the names of any files to be displayed.

Embedded Script Attack

Web discussion sites generally defend against embedded script attacks. This occurs when someone entering text into a web blog or other discussion forum, includes active content which will do nasty things to unsuspecting reader of the blog or forum.

For example, user A adds text to the blog:

Hi, I think that is great!

Then when user B accesses the page, the code is executed on user B's machine and does its damage.

Neither user A nor user B have any privileged access to the server; however user A used the web server to carry out an attack on user B's computer and the computers of other readers of the site.

try it out:

ISO-18859-1?

The above solution to embedded script attacks assumes the IS0-18859-1 character set. There are character sets in which "<" has two representations which are interpreted as the beginning of an HTML tag. In order to be safe, have the server specify the character set, e.g.:

See "Understanding Malicious Content Mitigation for Web Developers" Malicious code , for more details.

For more information on CSS, see "The Cross Site Scripting FAQ", xss faq or "The Open Web Application Security Project", owasp", page 53 of the pdf.

Always, always use taint mode with Perl CGI scripts. It is painful when you first start to use it, but it is essential for secure CGIs.

- CHECK into securityTut/studyinscarlet.txt

There are other problems; read the paper for full, gory details. Shaun Clowes lists several changes to the php.ini file which will make PHP secure:

* set register_globals off
* set safe_mode on
* set open_basedir
* set display_errors off, log_erros on
* set allow_url_fopen off

- Your EMAILS:

spam

Techie tip - in UNIX, who can change the config. file with these permissions?

# ls -ld / /usr /usr/serv /usr/serv/jerry \
/usr/serv/jerry/conf \
/usr/serv/jerry/conf/httpd.conf

" EsacpeShellCmd() escapes any characters in a string thatmight be used to trick a shell command into executingarbitrary commands. This function should be used to makesure that any data coming from user input is escaped before this data is passed to the exec() or system() functions, or to the backtick operator. "

" EscapeShellArg() adds single quotes around a string and quotes/escapes any existing single quotes allowing you to pass a string directly to a shell function and having it be treated as a single safe argument. This function should be used to escape individual arguments to shell functions coming from user input. "

Additional Tip: When user requests pages need authentication, a lot of web sites do not automatically return to originally requested page after successful login. I really don't like this and I guess others also does not like this, too. I suggest to implement login/authentication so that user can go back directly to the page requested. Implementation is not hard at all. Send URL encoded REQUEST_URI as query to login script when redirect to login script. Display the URI again if user send valid user name and password. If there are login button or link in pages, send current URI. (Unreliable HTTP_REFERER could be used also)

Secure php
-- few functions for security:

strip_tags(), str_replace() and stripslashes()
Example: $login = @strip_tags($login);
Example: $login = @stripslashes($login);

Check the referrer
Make sure the login script checks the HTTP_REFERER to see where the request came from. It should come from your HTML form, on the same server. If not, reject the login attempt. Though, I must tell you the HTTP_REFERER is easy to "spoof", or fake, so this security measure is easy bypass. It will only stop simple spam bots, or the most amateur of attackers.

Combine hashes, for better password encryption
Instead of just using SHA-1 on a password, use it combined with MD5, and stored that combination in the database.
Use your imagination. A lame, but simple example:
$encryptedone = sha1($password);
$encryptedtwo = md5($password);
$encrypted = $encryptedone + $encryptedtwo;

AND the mysql_real_escape_string function to avoid mysql tricks.

Php freaks

NOTE: If you are using the $_SESSION superglobal array like we are in this tutorial, you must clear the array values first, then run session_destroy.

Here's how we use session_destroy():

There's a function in PHP called session_id() that allows you to display the current session ID or utilize it however you need. Here is the demo script in the source file:

- at the beginning of the script:

error_reporting(E_ALL);
ini_set("display_errors","On");

Examples:
;
; - Show all errors, except for notices
;
;error_reporting = E_ALL & ~E_NOTICE
;
; - Show only errors
;
;error_reporting = E_COMPILE_ERROR|E_ERROR|E_CORE_ERROR
;
; - Show all errors except for notices
;
error_reporting = E_ALL & ~E_NOTICE

All PHP expressions can also be called with the "@" prefix, which turns off error reporting for that particular expression. If an error occurred during such an expression and the track_errors feature is enabled, you can find the error message in the global variable $php_errormsg.

Phpfreaks

but better download that : phpmailer-1.72.tar.gz

Ex:

Note: !!! IF YOU DO NOT HAVE THE CHOICE, You can use this class however i do not recommend it it can be damn fucking slow depending on where you are and your mail server is !!. But you can still use it in the background too.

I advice you to use the NET::SMTP class using PERL and run a script which send emails in the background using that EXEC() method in PHP. Check out my perl Tut.

Cron job :

Add shell script to have run hourly, daily, weekly or monthly into the appropriate directory:

* /etc/cron.hourly/
* /etc/cron.daily/
* /etc/cron.weekly/
* /etc/cron.monthly/

These are preconfigured schedules. To assign a very specific schedule add a line to the /etc/crontab file. Cron entries may also be added to a crontab formatted file located in the directory /var/spool/cron/.

Scheduling access and control:

* The administrator can allow users to use this facility with specific controlby using the /etc/cron.deny and /etc/cron.allow files.
* The at facility may be controlled with the /etc/at.deny and /etc/at.allow files.

Cron Tutorial

Automate tasks which should be done periodically. Update a database, backup your web pages and more. Users can have their list of tasks, called a crontab, for cron to execute.

exemple:

37 0 1 * * /home/username/runinvoices
59 17 20 * * /home/username/backupsite

The first entry is executed on the ust of each month (0:37AM), the second on the 20th (17:59 PM).

2. View Current Crontab.
Specify the -l option to have crontab list the current crontabfor the user you are logged in as.

~$ crontab -l

3. Create Or Modify A Crontab
Crontab files are manipulated using the crontab Linux command. First,log in to your web hosting account.

~$ crontab myfile

~$ crontab -r

The -r option removes your current crontab file.

~$ crontab -e

Specifying the -e option will launch the default editor (usally vi) to modify theactual crontab file. After the user exists the editor, the crontab file is updated.

59 17 1,10,20,30 * * /home/username/backupsite

This would execute the ask on the ust, the 10th, the 20th and on the 30th of each month, at 17:59PM.

59 17 * * 1-5 /home/username/backupsite

This would execute the cron job on weekdays only.

59 */6 * * * /home/username/backupsite

Here, the tasks is executed every 4 hours (24/6 =4).

hese techniques can be used on all the crontab fields

How to backup your MySQL tables and data every night using a bash script and cron ?

Bash Shell Script (mysqlbackup)

Example:

Sitepoint

Apache HTTP Authentication with PHP:

When installed as an Apache module, PHP provides two special global variables:
$PHP_AUTH_USER and $PHP_AUTH_PW. These contain the username and password that accompanied the current HTTP request, respectively. Using PHP¡¯s header() function, you can then respond with an HTTP 401 error when the username, password, or both are incorrect.

------------------
.htaccess
-----------------
looks better to me !

-------------------------------
Higherpass

File Download Security

Want to prevent people from linking to your downloads? This script will force a page to be loaded before the download starts. HTML header statements are used to trigger the download of the file. PHP is used to push the file to the browser.

HTML headers must be sent before any output is sent to the browser. PHP uses the header function to pass raw HTML headers. For this example we're going to get the filename from the URL www.yourdomain.com/download.php?file=download.zip.

or FROM Zend :

Another MIME Trick

While we're on the subject of Content-type headers, let me introduce a trick for launching a Microsoft Excel file inside a browser. You don't need to know the specification for Excel documents. Excel accepts tab-delimited files and converts them behind the scenes. Using the techniques described above, you can launch Excel inside a browser running on Windows.

The following script creates a big table of powers. The first 10 powers of the numbers from 1 to 99 are shown in an Excel spreadsheet. The script really generates a set of tab-separated numbers, but the browser imports it into Excel, which runs in an OLE container in the browser. The success of this method depends on the software loaded on the computer. It usually works with a computer running Windows and Internet Explorer.

A little TIP :

In php,

header("Location: somePagedsendThemTo.htm.");

will ONLY work if you DO NOT output anything to the browser before you send the header.

If there is a blank space anywhere on your opening

So what is mod_rewrite?

mod_rewrite is an Apache module which takes care of rewriting URLs, thus transforming: http://www.yoursite.com/script.php?category_id=1 into http://www.yoursite.com/script/cat_1/

Actually for every php functions, it s very usefull for optimal perf if you don't need error reporting.

HTTP GET variables: $_GET

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_GET_VARS

HTTP POST variables: $_POST

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_POST_VARS

Session variables: $_SESSION

Note: Introduced in 4.1.0. In earlier versions, use $HTTP_SESSION_VARS.

session_is_registered() returns TRUE if there is a global variable with the name name registered in the current session.

Note: If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use isset() to check a variable is registered in $_SESSION.

Strtotime

To Check : TIMESTAMP (I think it 's better to get familiar with this instead of using different tricks which cost without using it !)

$dateopen= date("Y-m-d H:i:s",mktime(date('H'),date('i'),date('s'),$_POST['txtDateOpenM'],$_POST['txtDateOpenD'],$_POST['txtDateOpenY']));

$dateclose= date("Y-m-d H:i:s",mktime(date('H') + $_POST['txtDateCloseH'],date('i') + $_POST['txtDateCloseHm'],date('s'),$_POST['txtDateOpenM'] + $_POST['txtDateCloseM'],$_POST['txtDateOpenD'] + $_POST['txtDateCloseD'],$_POST['txtDateOpenY']));

$datedeadline=date ("Y-m-d H:i:s",strToTime("+".$_POST['txtDeadlineM']." month ".$_POST['txtDeadlineD']." days ".$_POST['txtDeadlineH']." hours ".$_POST['txtDeadlineHm']." minutes",$dateclose));

and check GMT with gmdate();

var_dump(checkdate(2, 29, 2001)); return true or false.

TIMESTAMP is the solution.
echo (strtotime('2004-09-21 10:00:00') < time())?'oui':'non';

A lot of HTML resources right there and it s usefull.
faqs.org

CSS: w3.org

All the shit from IE can be dealt with HTC:
Msdn

javascript and html trick :

Open new window, resized if javascript, not resized if no javascript :

I don't like javascript coz not portable. Sometimes usefull however when there no other choices; Example: focus with CSS does not work with this fu..g IE so let's do a javascript turn over:

focus
JAVASCRIPT:

- OR DHTML: only for IE 5 or later.

HTC file:
Introduced in Microsoft Internet Explorer 5, HTML Components (HTCs) provide a mechanism to implement components in script as Dynamic HTML (DHTML) behaviors. Saved with an .htc extension, an HTC is an HTML file that contains script and a set of HTC-specific elements that define the component. This section contains a table that lists these elements and the members they support.

here is mine:

- Optimizing JavaScript for Download Speed:
peachpit

I ain't no designer but it's interesting to ba able able to use few tips to make a website though if u lack designer !

- Photoshop:
Good tuts

And for commercial use, may be better use the gimp on Linux ... free licence. But who knows what u are using !! ( :-) let s stay legal !!).

Open Window:

netmecha

Many Webmasters prefer the clean look of a sans-serif font to the default serif font used by most browsers. We use a sans-serif font on all NetMechanic pages for exactly that reason. By far the most popular option for a sans-serif font is Arial. Arial is a standard Windows font, and is now also installed on most Macintosh machines.

Basic Notes - Useful Tips

Always add a trailing slash to subfolder references. If you link like this:
w3school, you will generate two HTTP requests to the server, because the server will add a slash to the address and create a new request like this: w3school

HTML CHAR:
w3.org

ex: EURO : €
losenge: ◊

My example:

Rq: About the size:

- /etc/php.ini
check for upload_max_filesize= 50 M

And :

Shekhar Govindarajan
26-Oct-2003 09:38
To upload large files, besides setting upload_max_filesize, you must also set post_max_size in php.ini or using ini_set() function. Keep the value to more than the maximum expected size of the upload. This is because, you may be sending other post data along with the upload file. For example:

post_max_size = 601M

This should be a safe setting if you want to upload files of around 600 MB (as specified by upload_max_filesize = 600M)

While uploading large files, you should also increase the values for max_execution_time and max_input_time directives. Else your script will timeout or timeout before being able to parse the entire input/uploaded data.

Anybrowser

bignosebird

106.ibm

ssi

106 ibm:

- Server parsed HTML files can be enabled with the following lines in httpd.conf:

AddType text/html .shtml
AddHandler server-parsed .shtml
- with SSI enabled using the +Includes option in your directory directive:

- The includes module (mod_include) does all the server-side parsing. Look for

LoadModule includes_module modules/mod_include.so

- Ex:

INTO home.shtml:

And into /home/httpd/cgi-bin/banner.cgi :

And into /home/httpd/html/images/ :
all the banners

- NOTE:

If you want to include SSI files you use the PHP virtual() function not include() in PHP.

ex: virtual('/cgi-bin/banner.cgi');

- NEXT to come: the http needing pass and the http with browser detection.

Php.net

It's an additional module, i create another one bymyself using common functions.

codeproject

The HTTP-EQUIV tags

- Expires

This is used when the content on the page would expire. If a spider detects this, it would either delete the page from the search engine database, or re-index the page onthe expiry date.

- Cache-Control

Tells the browser how to handle its caching of that page.

* PUBLIC - may be cached in publicly shared caches.
* PRIVATE - cached only in a private cache.
* NO-CACHE - do not cache the page.
* NO-STORE - may be cached but not archived.

Content-Type

This causes the browser to load the correct character set before loading the page.

Content-Style-Type

This is how styles are defined in the page.

Content-Language

This of course, is the language the page is in.

Refresh

This tag causes the page to refresh and load the specified page after a specified amount of time. The delay is in seconds.

Set-Cookie

This allows the page to set a cookie to expire on a certain date.

About Nnamd

- CHINESE:

just add this :

AND into httpd.conf apache - comment the line which set the default charset !

php net

We saw before how to handle file I/O while uploading and downloading files, but if we only wanna do deleting and creating file instead of moving :

fopen() and fwrite() ...

bool unlink ( string filename [, resource context])

The quiquest way to run a task in tha background ! :

@exec("/home/httpd/cgi-bin/gmail.pl 'Here Yeah' >/dev/null &");

- FOREACH

Since it is nowhere really documented, here an example for the new foreach-function: (Someone said that, not me, but i picked it up, might believe it , who knows !)

$arr is an array or a hash.

- SWITCH

is_numeric() better than >= 0 pour toute entree de formulaire.