<node>$_SERVER
<node>IP INFO
<node>current page
<node>arrays
<node>cookies
<node>count
<node>explode/implode
<node>in_array
<node>sort
<node>ascii
<node>Cookie
<node>Database
<node>Backup
<node>connect
<node>script
<node>create
<node>Tips
<node>Date
<node>Nulls
<node>number of recs
<node>query
<node>CONCAT
<node>count
<node>Delete
<node>find orphans
<node>GROUP BY
<node>inner join
<node>insert record
<node>insert Record
<node>insert table
<node>Insert Using select
<node>TABLE
<node>fields
<node>view record
<node>Reset autonumber
<node>sql
<node>Update
<node>variables
<node>Date
<node>add day
<node>current date
<node>future date
<node>getdate
<node>mdy to ymd
<node>mktime
<node>mysql
<node>valid date
<node>ymd to mdy
<node>email
<node>mail
<node>mail script
<node>return path
<node>Verify
<node>files
<node>Copy,Move,Kill
<node>directory
<node>downloads
<node>exists
<node>file ntype
<node>open files
<node>read
<node>read lines
<node>single character
<node>string
<node>whole file
<node>Write
<node>Permissions
<node>read directory
<node>updating html
<node>upload
<node>formating
<node>breaks
<node>number
<node>screenResolution
<node>url
<node>Forms
<node>box sizes
<node>check boxes
<node>process file
<node>combo
<node>For
<node>Pass Code
<node>radio Buttons
<node>submit
<node>Text Area
<node>graphics
<node>Create Button
<node>font
<node>header
<node>download
<node>redirect
<node>LANGUAGE
<node>case – switch
<node>DATE
<node>explode/implode
<node>for
<node>foreach
<node>function
<node>headers sent
<Treepad version 3.0>
dt=
<node>PHP
0
<end node> 5P9i0s8y19Z
dt=
<node>$_SERVER
1
if ($_SERVER["HTTPS"]!="on") {header("location:https://www.longspeakbsa.org/swd/LoginForm.php");exit; }
URL INFO [USE parse_url under langueage
'PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.
'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
Note:
PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.
'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.
'HTTPS'
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
Set to a non-empty value if the script was queried through the HTTPS protocol.
Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.
'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
if($_SERVER['REMOTE_ADDR']=="127.0.0.1"){ $server='localhost';$user='greatone';$password='gr38t0n3';$database='angel'; $_SESSION['LEVEL']=10;}
else{ $server="localhost";$user="angelde_flunky1";$password="wied55";$database="angelde_a1"; }
'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.
Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().
'REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'REMOTE_USER'
The authenticated user.
'REDIRECT_REMOTE_USER'
The authenticated user if the request is internally redirected.
'SCRIPT_FILENAME'
The absolute pathname of the currently executing script.
Note:
If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.
'SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_PORT'
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
'SERVER_SIGNATURE'
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.
Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.
'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST'
When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
When doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When doing HTTP authenticated this variable is set to the authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.
<end node> 5P9i0s8y19Z
dt=
<node>IP INFO
2
[IP address value computed]
function Dot2LongIP ($IPaddr)
{
if ($IPaddr == "") {
return 0;
} else {
$ips = split ("\.", "$IPaddr");
return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
}
}
==============================
[Get ip address and calling page]
$ref=@$HTTP_REFERER;
if($ref!="http://www.newbeeswelcome.com/beeheard.php"){
echo "Server has failed"; exit;
}
$ip=$_SERVER['REMOTE_ADDR'];
if(Dot2LongIP($ip)>1109000000){
echo 'Record Is Saved';exit;
}
[MYSQL]
CREATE TABLE `iptable` (
`ipid` mediumint(9) NOT NULL auto_increment,
`ip` varchar(19) NOT NULL,
`datecreate` date NOT NULL,
PRIMARY KEY (`ipid`),
KEY `ip` (`ip`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
<end node> 5P9i0s8y19Z
dt=
<node>current page
3
Sometimes, you might want to get the current page URL that is shown in the browser URL window. For example if you want to let your visitors submit a blog post to Digg you need to get that same exact URL. There are plenty of other reasons as well. Here is how you can do that.
Add the following code to a page:
[simple redirect]
<?php if ($_SERVER["HTTPS"] != "on"){ header("location:https://www.softwarewebdesign.com/WHS/FBLA1"); exit; } ?>
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
You can now get the current page URL using the line:
<?php
echo curPageURL();
?>
Sometimes it is needed to get the page name only. The following example shows how to do it:
<?php
function curPageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
echo "The current page name is ".curPageName();
?>
Tags: PHP CURRENT URL SERVER BROWSER
<end node> 5P9i0s8y19Z
dt=
<node>arrays
1
key()
key() returns the index element of the current array position.
All elements use [] not commas like vb
$menu[10][10][10] for php
print_r ($Names);
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
<end node> 5P9i0s8y19Z
dt=
<node>cookies
2
Use json_encode / json_decode to get / set arrays in cookies.
Test array
$cardArray=array(
'CARD 1'=>array('FRONT I', 'BACK I'),
'CARD 2'=>array('FRONT 2', 'BACK 2')
);
convert and write the cookie
$json = json_encode($cardArray, true);
setcookie('cards', $json);
the saved string looks like this
{"CARD 1":["FRONT I","BACK I"],"CARD 2":["FRONT 2","BACK 2"]}
get the cookie back
$cookie = $_COOKIE['cards'];
$cookie = stripslashes($cookie);
$savedCardArray = json_decode($cookie, true);
show the restored array
echo '<pre>';
print_r($savedCardArray);
echo '</pre>';
====================================
THIS IS TRASH BELOW IT WOULD NOT WORK FOR ME.
How is proper way to store an array in a cookie? in PHP Code example:
$number_ticket=2;
$info[7][5]=1;
$info[8][5]=1;
php arrays cookies
Serialize data:
setcookie('cookie', serialize($info), time()+3600);
Then unserialize data:
$data = unserialize($_COOKIE['cookie']);
After data, $info and $data will have the same content.
<end node> 5P9i0s8y19Z
dt=
<node>count
2
$m is an array
$num=count($m)
<end node> 5P9i0s8y19Z
dt=
<node>explode/implode
2
$pastor=array('Dary Northrop','Jeff Lucas','Frank Estep','Darren Fred','Doug Miller', 'Barb Myers', 'Reza Reza');
while (list ($key, $val) = each ($pastor)){
reset($pastor)
**************************
Use implode() and explode() to pass the contents of a single
dimensional
array from one page/script to another using a form:
First, implode() an array of strings on the first page. Example:
$yourarray[0] = "foo";
$yourarray[1] = "bar";
$string = implode("|", $yourarray); //$string looks like this: foo|bar
// Send $string on to the next page:
echo "<input type=hidden name=string value=$string>";
On the second page/script, explode() $string to get your array back:
$seconddarray = explode("|", $string);
<end node> 5P9i0s8y19Z
dt=
<node>in_array
2
function scan_dir($dir) {
$ignored = array('.', '..', '.svn', '.htaccess');
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file, $ignored)) continue;
$filedate=date('Y-m-j', filemtime($dir . '/' . $file));
$files[$file]=$filedate." ".$files[$file];
//$files[$file] = filemtime($dir . '/' . $file);
}
arsort($files);
//$files = array_keys($files);
return ($files) ? $files : false;
}
<end node> 5P9i0s8y19Z
dt=
<node>sort
2
Reverse sort
rsort($bulletin);
<end node> 5P9i0s8y19Z
dt=
<node>ascii
1
ord($string); Returns the ASCII value of the first character of string .
160 is the square box space
0 0 000 null
1 1 001 start of heading
2 2 002 start of text
3 3 003 end of text
4 4 004 end of transmission
5 5 005 enquiry
6 6 006 acknowledge
7 7 007 bell
8 8 010 backspace
9 9 011 horizontal tab
10 A 012 new line
11 B 013 vertical tab
12 C 014 new page
13 D 015 carriage return
14 E 016 shift out
15 F 017 shift in
16 10 020 data link escape
17 11 021 device control 1
18 12 022 device control 2
19 13 023 device control 3
20 14 024 device control 4
21 15 025 negative acknowledge
22 16 026 synchronous idle
23 17 027 end of trans. block
24 18 030 cancel
25 19 031 end of medium
26 1A 032 substitute
27 1B 033 escape
28 1C 034 file separator
29 1D 035 group separator
30 1E 036 record separator
31 1F 037 unit separator
32 20 040 space
33 21 041 !
34 22 042 "
35 23 043 #
36 24 044 $
37 25 045 %
38 26 046 &
39 27 047 '
40 28 050 (
41 29 051 )
42 2A 052 *
43 2B 053 +
44 2C 054 ,
45 2D 055 –
46 2E 056 .
47 2F 057 /
48 30 060 0
49 31 061 1
50 32 062 2
51 33 063 3
52 34 064 4
53 35 065 5
54 36 066 6
55 37 067 7
56 38 070 8
57 39 071 9
58 3A 072 :
59 3B 073 ;
60 3C 074 <
61 3D 075 =
62 3E 076 >
63 3F 077 ?
64 40 100 @
65 41 101 A
66 42 102 B
67 43 103 C
68 44 104 D
69 45 105 E
70 46 106 F
71 47 107 G
72 48 110 H
73 49 111 I
74 4A 112 J
75 4B 113 K
76 4C 114 L
77 4D 115 M
78 4E 116 N
79 4F 117 O
80 50 120 P
81 51 121 Q
82 52 122 R
83 53 123 S
84 54 124 T
85 55 125 U
86 56 126 V
87 57 127 W
88 58 130 X
89 59 131 Y
90 5A 132 Z
91 5B 133 [
92 5C 134 \
93 5D 135 ]
94 5E 136 ^
95 5F 137 _
96 60 140 `
97 61 141 a
98 62 142 b
99 63 143 c
100 64 144 d
101 65 145 e
102 66 146 f
103 67 147 g
104 68 150 h
105 69 151 i
106 6A 152 j
107 6B 153 k
108 6C 154 l
109 6D 155 m
110 6E 156 n
111 6F 157 o
112 70 160 p
113 71 161 q
114 72 162 r
115 73 163 s
116 74 164 t
117 75 165 u
118 76 166 v
119 77 167 w
120 78 170 x
121 79 171 y
122 7A 172 z
123 7B 173 {
124 7C 174 |
125 7D 175 }
126 7E 176 ~
127 7F 177 DEL
<end node> 5P9i0s8y19Z
dt=
<node>Cookie
1
SET ONLY ONE ARRAY IN EACH COOKIE
$cardArray=array(
'CARD 1'=>array('FRONT I', 'BACK I'),
'CARD 2'=>array('FRONT 2', 'BACK 2')
);
convert and write the cookie
$json = json_encode($cardArray);
setcookie('cards', $json);
the saved string looks like this
{"CARD 1":["FRONT I","BACK I"],"CARD 2":["FRONT 2","BACK 2"]}
get the cookie back
$cookie = $_COOKIE['cards'];
$cookie = stripslashes($cookie); NOTE THIS!!!!!!!!!!!!!!!!!!!!!!!!!!!!
$savedCardArray = json_decode($cookie, true);
show the restored array
echo '<pre>';
print_r($savedCardArray);
echo '</pre>';
outputs
Array
(
[CARD 1] => Array
(
[0] => FRONT I
[1] => BACK I
)
[CARD 2] => Array
(
[0] => FRONT 2
[1] => BACK 2
)
)
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.
setcookie("user_id","GreatOne",time()+60*60*24*700 ,"/","softwarewebdesign.com");
setcookie("password_id","Agriculture",time()+60*60*24*700 ,"/","softwarewebdesign.com");
if($_COOKIE["user_id"]!= "GreatOne" || $_COOKIE["password_id"]!="Agriculture"){ header("location:index.php");exit; }
print_r($_COOKIE);exit;
$json = json_encode($cardArray);
setcookie('cards', $json);
<end node> 5P9i0s8y19Z
dt=
<node>Database
1
appostrophe
$Article=mysql_real_escape_string($Article);
or
WHERE — $business=str_replace("'",chr(92).chr(92).chr(92)."'",$businessname); which adds the ///'
<html>
<head>
<title>Listing every database, table, and field</title>
</head>
<body>
<?php
$user = "java2s";
$pass = "password";
$db = "java2s";
$link = mysql_connect( "mysql153.secureserver.net", $user, $pass );
if ( ! $link )
die( "Couldn't connect to MySQL" );
$db_res = mysql_list_dbs( $link );
while ( $db_rows = mysql_fetch_row( $db_res ) ) {
print "<b>$db_rows[0]</b>\n";
if ( !@mysql_select_db( $db_rows[0], $link ) ) {
print "<dl><dd>couldn't connect — " . mysql_error() ." </dl>";
continue;
}
$tab_res = mysql_list_tables( $db_rows[0], $link );
print "\t<dl><dd>\n";
while ( $tab_rows = mysql_fetch_row( $tab_res ) ){
print "\t<b>$tab_rows[0]</b>\n";
$query_res = mysql_query( "SELECT * from $tab_rows[0]" );
$num_fields = mysql_num_fields( $query_res );
print "\t\t<dl><dd>\n";
for ( $x=0; $x<$num_fields; $x++ ){
print "\t\t<i>";
print mysql_field_type( $query_res, $x );
print "</i> <i>";
print mysql_field_len( $query_res, $x );
print "</i> <b>";
print mysql_field_name( $query_res, $x );
print "</b> <i>";
print mysql_field_flags( $query_res, $x );
print "</i><br>\n";
}
print "\t\t</d1>\n";
}
print "\t</d1>\n";
}
mysql_close( $link );
?>
</body>
</html>
<end node> 5P9i0s8y19Z
dt=
<node>Backup
2
Execute a database backup query from PHP file
Below is an example of using SELECT INTO OUTFILE query for creating table backup :
<?php
include 'config.php';
include 'opendb.php';
$tableName = 'mypet';
$backupFile = 'backup/mypet.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysql_query($query);
include 'closedb.php';
?>
To restore the backup you just need to run LOAD DATA INFILE query like this :
<?php
include 'config.php';
include 'opendb.php';
$tableName = 'mypet';
$backupFile = 'mypet.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysql_query($query);
include 'closedb.php';
?>
It's a good idea to name the backup file as tablename.sql so you'll know from which table the backup file is
Run mysqldump using system() function
The system() function is used to execute an external program. Because MySQL already have built in tool for creating MySQL database backup (mysqldump) let's use it from our PHP script
<?php
include 'config.php';
include 'opendb.php';
$backupFile = $dbname . date("Y-m-d-H-i-s") . '.gz';
$command = "mysqldump –opt -h $dbhost -u $dbuser -p $dbpass $dbname | gzip > $backupFile";
system($command);
include 'closedb.php';
?>
**********************************************
<?php
function datadump ($table) {
$result .= "# Dump of $table \n";
$result .= "# Dump DATE : " . date("d-M-Y") ."\n\n";
$query = mysql_query("select * from $table");
$num_fields = @mysql_num_fields($query);
$numrow = mysql_num_rows($query);
for ($i =0; $i<$numrow; $i++) {
$result .= "INSERT INTO ".$table." VALUES(";
for($j=0; $j<$num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = ereg_replace("\n","\\n",$row[$j]);
if (isset($row[$j])) $result .= "\"$row[$j]\"" ; else $result .= "\"\"";
if ($j<($num_fields-1)) $result .= ",";
}
$result .= ");\n";
}
return $result . "\n\n\n";
}
?>OK, now you add the last bit to the script:
<?php
$table1 = datadump ("table1");
$table2 = datadump ("table2");
$table3 = datadump ("table3");
$content = $table1 . $table2 . $table3;
$file_name = "MySQL_Database_Backup.sql";
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=$file_name");
echo $content;
exit;
?>See this part:
$table1 = datadump ("table1");
$table2 = datadump ("table2");
$table3 = datadump ("table3");
$content = $table1 . $table2 . $table3;
That is where you need to specify the tables you want to backup.
Lets say you had 3 tables called links, categories and users. You would need to add:
$links = datadump ("links");
$categories = datadump ("categories");
$users = datadump ("users");
And then to the $content area add:
$content = $links . $categories . $users;
<end node> 5P9i0s8y19Z
dt=
<node>connect
2
$db = mysql_pconnect('localhost', 'GreatOne', 'yardbird');
if (!$db)
{
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
mysql_select_db('steve');
The results are based on the users that are set up in the database manager
<end node> 5P9i0s8y19Z
dt=
<node>script
3
<?php # Script 6.5 – mysql_connect.php
// This file contains the database access information. This file also establishes a connection to MySQL and selects the database.
// Set the database access information as constants.
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PASSWORD', 'password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'sitename');
// Make the connnection and then select the database.
$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() );
mysql_select_db (DB_NAME) OR die ('Could not select the database: ' . mysql_error() );
?>
<end node> 5P9i0s8y19Z
dt=
<node>create
2
CREATE DATABASE content;
USE content;
—content is name of database
# Cat
CREATE TABLE Cat(
food VARCHAR(30) NOT NULL,
catid INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (catid)
);
# Fish
CREATE TABLE Fish(
food VARCHAR(30) NOT NULL,
fishid INT(11) NOT NULL AUTO_INCREMENT,
hardware TEXT NOT NULL,
PRIMARY KEY (fishid),
UNIQUE foodhard (food, hardware(60))
);
<end node> 5P9i0s8y19Z
dt=
<node>Tips
3
# database: Tips
# Questions
CREATE TABLE Questions(
questionid INT(11) NOT NULL AUTO_INCREMENT,
keywords VARCHAR(255) NOT NULL,
question VARCHAR(255) NOT NULL,
PRIMARY KEY (questionid),
UNIQUE questionkey (question)
);
# Reply
CREATE TABLE Reply(
replyid INT(11) NOT NULL AUTO_INCREMENT,
questionid INT(11) NOT NULL,
reply TEXT NOT NULL,
PRIMARY KEY (replyid)
);
# user1
CREATE TABLE user1(
userid INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(16) NOT NULL,
passwd VARCHAR(16) NOT NULL,
email VARCHAR(100) NOT NULL,
PRIMARY KEY (userid),
UNIQUE usernameKEY (username)
);
<end node> 5P9i0s8y19Z
dt=
<node>Date
2
NOW() must be used with datetime field
ADDDATE('1998-01-02', INTERVAL 31 DAY);
SELECT invoices.customerid, `last_name` , `first_name`, COUNT(`last_name`) AS dog,
count(if(`date`< ADDDATE(NOW(), INTERVAL -365 DAY), 1, null)) AS year1, count(if(`date`>= ADDDATE(NOW(), INTERVAL -365 DAY), 1, null)) AS year0, count(if(`date`< ADDDATE(NOW(), INTERVAL -730 DAY), 1, null)) AS year2
FROM `invoices`
INNER JOIN `customer` ON customer.customerid = invoices.customerid
GROUP BY invoices.customerid, `last_name` , `first_name`
ORDER BY year0,year1
<end node> 5P9i0s8y19Z
dt=
<node>Nulls
2
Select * from table1groups left join table1 on table1groups.musgraveid=table1.musgraveid Where table1.musgraveid IS NULL LIMIT 0, 30
<end node> 5P9i0s8y19Z
dt=
<node>number of recs
2
$result=mysql_query($query);
$num= mysql_numrows($result);
<end node> 5P9i0s8y19Z
dt=
<node>query
2
$query="SELECT * FROM category";
$result=mysql_query($query);
$num=mysql_numrows($result);
for($i=1;$i<=$num;++$i){
$row=mysql_fetch_array($result);
$catid=$row['categoryid'];
}
<end node> 5P9i0s8y19Z
dt=
<node>CONCAT
3
APENDING data before and after a field.
UPDATE `iwspackage` SET iwspackageimg=CONCAT('package',packageid,'.jpg');
UPDATE ads SET img1=CONCAT(adid,'a.jpg'), img2=CONCAT(adid,'b.jpg') , img3=CONCAT(adid,'c.jpg') , img4=CONCAT(adid,'d.jpg'), pdf=CONCAT(adid,'.pdf') WHERE adid>7;
UPDATE `machinery` SET `inspection_report`=CONCAT(machineryid,'.pdf'),`prim_img`=CONCAT(machineryid,'a.jpg'),`imgb`=CONCAT(machineryid,'b.jpg'),`imgc`=CONCAT(machineryid,'c.jpg'),`imgd`=CONCAT(machineryid,'d.jpg'),`imge`=CONCAT(machineryid,'e.jpg')
<end node> 5P9i0s8y19Z
dt=
<node>count
3
SELECT hide,count(hide) as dog FROM `invoice` GROUP BY hide LIMIT 0, 30
SELECT invoices.customerid, `last_name` , `first_name`, COUNT(`last_name`) AS dog,
count(if(`date`< ADDDATE(NOW(), INTERVAL -365 DAY), 1, null)) AS year1, count(if(`date`>= ADDDATE(NOW(), INTERVAL -365 DAY), 1, null)) AS year0, count(if(`date`< ADDDATE(NOW(), INTERVAL -730 DAY), 1, null)) AS year2
FROM `invoices`
INNER JOIN `customer` ON customer.customerid = invoices.customerid
GROUP BY invoices.customerid, `last_name` , `first_name`
ORDER BY year0,year1
<end node> 5P9i0s8y19Z
dt=
<node>Delete
3
Left Join
DELETE FROM `cart` USING `cart` LEFT JOIN orders ON cart.sessionid=orders.sessionid WHERE orderid IS NULL AND updated<'2006-01-01'
<end node> 5P9i0s8y19Z
dt=
<node>find orphans
3
Child to parent
Select * from table1groups left join table1 on table1groups.musgraveid=table1.musgraveid LIMIT 0, 30
Select * from table1groups left join table1 on table1groups.musgraveid=table1.musgraveid Where table1.musgraveid IS NULL LIMIT 0, 30
<end node> 5P9i0s8y19Z
dt=
<node>GROUP BY
3
SELECT category,categories.categoryid, COUNT(ads.categoryid) AS junk FROM categories LEFT JOIN ads ON categories.categoryid=ads.categoryid GROUP BY category ORDER BY category
SELECT products.productname, soldout, restock, count( orderedproducts.productid )
FROM categories, products, orderedproducts, orders
WHERE filled = 'Y'
AND orders.orderid = orderedproducts.orderid
AND orderedproducts.productid = products.productid
AND categories.catid = products.catid
AND orders.date>='2010-04-01' AND orders.date<='2010-04-30'
GROUP BY productname
SELECT * FROM `orderedproducts INNER JOIN orders ON orders.orderid=orderedproducts.orderid WHERE orders.date>='2010-04-01' AND orders.date<='2010-04-30'
<end node> 5P9i0s8y19Z
dt=
<node>inner join
3
SELECT YEAR(date),category,item,SUM(invoice_cart.quantity),Sum(invoice_cart.price*invoice_cart.quantity) FROM invoices INNER JOIN (invoice_cart INNER JOIN (items INNER JOIN item_category ON items.categoryid=item_category.categoryid) ON items.itemid=invoice_cart.itemid) ON invoices.invoiceid=invoice_cart.invoiceid WHERE service=1 OR service=2 GROUP BY YEAR(date),category,item";
<end node> 5P9i0s8y19Z
dt=
<node>insert record
3
INSERT INTO hear_about (hear) VALUES
('AOL'),('Yahoo'),('MSN'),('Google'),('Other Website'),('Newsletter'), ('Friend or real estate agent'),('Fence Post'),('Homes & Land'),('Real Estate Book'),('Rodeo News'),('Direct mail'),('Metrowest Newspaper')
<end node> 5P9i0s8y19Z
dt=
<node>insert Record
3
$query = "insert into books values
('".$isbn."', '".$author."', '".$title."', '".$price."')";
$result = mysql_query($query);
if ($result)
echo mysql_affected_rows().' book inserted into database.';
?>
<end node> 5P9i0s8y19Z
dt=
<node>insert table
3
$result = mysql_query($query);//run query
if ($result)
echo 'Question Table is Done/n';
$query="CREATE TABLE Reply (
replyid int PRIMARY KEY auto_increment,
questionid int NOT NULL,
reply text NOT NULL
)";
<end node> 5P9i0s8y19Z
dt=
<node>Insert Using select
3
INSERT INTO exportregistration( `registrationid` , `groupid` , `event` , `dateof` , `lastname` , `firstname` , `address` , `city` , `state` , `zip` , `home_phone` , `email` , `special_email` , `relationid` , `arrived` )
SELECT `registrationid` , `groupid` , `event` , `date` , `lastname` , `firstname` , `address` , `city` , `state` , `zip` , `home_phone` , `email` , `special_email` , `relationid` , `arrived`
FROM EVENTS INNER JOIN event_registration ON events.eventid = event_registration.eventid ORDER BY date, lastname, firstname
<end node> 5P9i0s8y19Z
dt=
<node>TABLE
3
[Add More Fields]
ALTER TABLE warehouse
ADD fire_protection tinyint(4) NOT NULL default '0' AFTER interstate,
ADD fire_water tinyint(4) NOT NULL default '0' AFTER fire_protection,
ADD fire_inertgas tinyint(4) NOT NULL default '0' AFTER fire_water,
ADD fire_CO2 tinyint(4) NOT NULL default '0' AFTER fire_inertgas;
[rename fields]
ALTER TABLE `warehouse` CHANGE `AMPERAGE` `amperage` SMALLINT(6) DEFAULT '0' NOT NULL
RENAME TABLE current_db.tbl_name TO other_db.tbl_name;
ALTER TABLE orders
ADD `responsecode` tinyint(4) NOT NULL default '0',
ADD `responsesubcode` tinyint(4) NOT NULL default '0',
ADD `reasoncode` tinyint(4) NOT NULL default '0',
ADD `reasontext` varchar(255) NOT NULL default '',
ADD `authcode` varchar(20) NOT NULL default '',
ADD `avscode` varchar(5) NOT NULL default '',
ADD `transid` tinyint(4) NOT NULL default '0';
[EMPTY TABLE]
TRUNCATE TABLE table
<end node> 5P9i0s8y19Z
dt=
<node>fields
4
<?php
// database constants
// make sure the information is correct
define("DB_SERVER", "localhost");
define("DB_USER", "root");
define("DB_PASS", "password");
define("DB_NAME", "tutorials");
// connection to the database
$dbhandle = mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");
// select a database to work with
$selected = mysql_select_db(DB_NAME, $dbhandle)
or die("Could not select examples");
// return all available tables
$result_tbl = mysql_query( "SHOW TABLES FROM ".DB_NAME, $dbhandle );
$tables = array();
while ($row = mysql_fetch_row($result_tbl)) {
$tables[] = $row[0];
}
$output = "<?xml version=\"1.0\" ?>\n";
$output .= "<schema>";
// iterate over each table and return the fields for each table
foreach ( $tables as $table ) {
$output .= "<table name=\"$table\">";
$result_fld = mysql_query( "SHOW FIELDS FROM ".$table, $dbhandle );
while( $row1 = mysql_fetch_row($result_fld) ) {
$output .= "<field name=\"$row1[0]\" type=\"$row1[1]\"";
$output .= ($row1[3] == "PRI") ? " primary_key=\"yes\" />" : " />";
}
$output .= "</table>";
}
$output .= "</schema>";
// tell the browser what kind of file is come in
header("Content-type: text/xml");
// print out XML that describes the schema
echo $output;
// close the connection
mysql_close($dbhandle);
?>
<end node> 5P9i0s8y19Z
dt=
<node>view record
3
$row=mysql_fetch_array($result);
$userid=$row['userid'];
<end node> 5P9i0s8y19Z
dt=
<node>Reset autonumber
2
Problem One:
If I have entered 10 records, and deleted 9th, 10th records. The next auto increment value will be 11, not 9.
Solution:
Run a query:
ALTER TABLE tablename AUTO_INCREMENT = 1
This will reset the next auto increment value to current largest value in the auto increment column + 1. So, the auto increment value of next inserted record will start from 9.
Problem Two:
If I have entered 10 records, and deleted center records – 4th, 5th. I want to insert next record as 4th not 11th.
Solution:
Run the following query:
SET insert_id = 4;
INSERT INTO tablename VALUES (’blah’, ‘…’);
This will add the next record into record 4th.
The SET insert_id = #(where # is the next auto increment value you want to use) will reset the next auto increament value, the next query(INSERT) you run will use your choice of value.
Note: only effective for the immediate next query, one time.
<end node> 5P9i0s8y19Z
dt=
<node>sql
2
DROP TABLE IF EXISTS `renters`;
CREATE TABLE IF NOT EXISTS `renters` (
`renterid` mediumint(5) NOT NULL AUTO_INCREMENT,
`last_name` varchar(50) NOT NULL DEFAULT '',
`first_name` varchar(50) NOT NULL DEFAULT '',
`address` varchar(50) NOT NULL DEFAULT '',
`city` varchar(25) NOT NULL DEFAULT '',
`zipcode` varchar(10) NOT NULL DEFAULT '',
`phone` varchar(20) NOT NULL DEFAULT '',
`cellphone` varchar(20) NOT NULL DEFAULT '',
`email` varchar(100) NOT NULL DEFAULT '',
`birthday` date NOT NULL DEFAULT '0000-00-00',
`username` varchar(20) NOT NULL DEFAULT '',
`password` varchar(20) NOT NULL DEFAULT '',
`lastlogin` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`logintimes` tinyint(4) NOT NULL DEFAULT '0',
`level` tinyint(2) NOT NULL DEFAULT '0',
PRIMARY KEY (`renterid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
<end node> 5P9i0s8y19Z
dt=
<node>Update
2
Update adds Set shortadd='$shortadd',longadd='$longadd',contact1='$contact1',contact2='$contact2',contact3='$contact3',subtopicid=$subtopicid,locationid=$locationid,city='$city',postdate='$date1' Where addid=$addid";
[increment]
update my_table set field = (field+10);
[CONCAT STRING]
UPDATE products SET artimg=CONCAT(productid,'.jpg')
<end node> 5P9i0s8y19Z
dt=
<node>variables
2
TINYINT=-127 TO 128
SMALLINT=-32768 TO 32767 OR 0 TO 65535
MEDIUMINT=0 TO 16777215
INT= 0 TO (2^32)-1
BIGINT=0 TO (2^64)-1
VARCHAR=1 TO 255
TINYTEXT=255
TEXT=65535
MEDIUMTEXT=16,777,215
LONGTEXT=4,294,967,295
<end node> 5P9i0s8y19Z
dt=
<node>Date
1
MUST USE DATE, GETDATE ONLY SEEMS TO WORK WITH CURRENT DATE=====
echo date("Y-m-d H:i:s");
format character Description Example returned values
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
F A full textual representation of a month, such as January or March January through December
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
I (capital i) Whether or not the date is in daylights savings time 1 if Daylight Savings Time, 0 otherwise.
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
O Difference to Greenwich time (GMT) in hours Example: +0200
r RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
s Seconds, with leading zeros 00 through 59
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
t Number of days in the given month 28 through 31
T Timezone setting of this machine Examples: EST, MDT …
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
z The day of the year (starting from 0) 0 through 365
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 43200
Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().
Example 1. date() examples
****************************************
a "am" or "pm"
A "AM" or "PM"
B Swatch Internet time
d day of the month, 2 digits with leading zeros; i.e. "01" to "31"
D day of the week, textual, 3 letters; i.e. "Fri"
F month, textual, long; i.e. "January"
g hour, 12-hour format without leading zeros; i.e. "1" to "12"
G hour, 24-hour format without leading zeros; i.e. "0" to "23"
h hour, 12-hour format; i.e. "01" to "12"
H hour, 24-hour format; i.e. "00" to "23"
i minutes; i.e. "00" to "59"
I (capital i) "1" if Daylight Savings Time, "0" otherwise.
j day of the month without leading zeros; i.e. "1" to "31"
l (lowercase 'L') day of the week, textual, long; i.e. "Friday"
L boolean for whether it is a leap year; i.e. "0" or "1"
m month; i.e. "01" to "12"
M month, textual, 3 letters; i.e. "Jan"
n month without leading zeros; i.e. "1" to "12"
r RFC 822 formatted date; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (added in PHP 4.0.4)
s seconds; i.e. "00" to "59"
S English ordinal suffix, textual, 2 characters; i.e. "th", "nd"
t number of days in the given month; i.e. "28" to "31"
T Timezone setting of this machine; i.e. "MDT"
U seconds since the epoch
w day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday)
Y year, 4 digits; i.e. "1999"
y year, 2 digits; i.e. "99"
z day of the year; i.e. "0" to "365"
Z timezone offset in seconds (i.e. "-43200" to "43200"). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive
<?php
// Prints something like: Wednesday
echo date("l");
// Prints something like: Wednesday 15th of January 2003 05:51:38 AM
echo date("l dS of F Y h:i:s A");
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
?>
You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash. Example 2. Escaping characters in date()
<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>
It is possible to use date() and mktime() together to find dates in the future or the past. Example 3. date() and mktime() example
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Note: This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight savings time.
Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines. Example 4. date() Formatting
<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day z '); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // It is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m is month
$today = date("H:i:s"); // 17:16:17
?>
<end node> 5P9i0s8y19Z
dt=
<node>add day
2
$date = date('m/d/Y',strtotime($date.' + 2 days'));
[compare difference]
$date = date('Y-m-d',strtotime(date('Y-m-d').' + 10 days'));
$priority="";if(strtotime($date)>strtotime($daterequested)) $priority="!";
[Subraction]
$date = date('Y-m-d',strtotime(date('Y-m-d'))-(10*24*60*60));
<?php
echo (strtotime("2009-09-28")-strtotime(date("Y-m-d H:i:s")))/3600;
echo"<br>";
echo (31*24);
?>
<end node> 5P9i0s8y19Z
dt=
<node>current date
2
$now=date('Y-m-j');
echo date("Y-m-d h:i:sa");
mysql
MySQL FORMAT (yyyy-mm-dd)
<end node> 5P9i0s8y19Z
dt=
<node>future date
2
Finding a Past or Future Date
Written by: Gareth Downes-Powell
Article Date: 26th January 2003
In this guide we`re going to look at how to add a certain period onto a date. As an example, we`re going to find the date 30 days from the 26th January 2003.
To work with dates list this we have to use the PHP mktime() function, which creates a timestamp. A timestamp is a number which represents the number of seconds since January 1st 1970. The format for the mktime command is:
$timestamp = mktime(hour,minute,second,month,day,year)
So, to turn our date, 26/01/2003 into a timestamp, we first need to split the date into its individual units:
<?php
$date = "26/01/2003";
$dateSplit = explode("/",$date);
$day = $dateSplit[0];
$month = $dateSplit[1];
$year = $dateSplit[2];
?>
Now, $day contains "26", $month contains "01" and $year contains "2003"
Next, we can put these date parts into the mktime function to generate a timestamp.
<?php
$timestamp = mktime(0,0,0,$month,$day,$year);
?>
$timestamp will not contain the number of seconds between January 1st 1970 and 26th January 2003 ( which is 1043539200 )
To find the date 30 days ahead, we simply have to calculate the number of seconds in a day, multiply that by 30, and add the value to the timestamp.
<?php
$oneDay = 24 * 60 * 60;
$total = 30 * $oneDay;
$newTimestamp = $timestamp + $total;
?>
Now we have a timestamp that represents the date 30 days on from 26/01/2003. All that needs to be done now is to convert the timestamp back into date format, which we do with the php date() command, as shown below.
<?php
$date = date("d/m/Y",$newTimestamp);
echo $date;
?>
When run in a browser, you`ll see the following date displayed: 25/02/2003
And this is the date 30 days from our target date, 26/01/2003. Using this technique you can find any future or past date, by converting the article into seconds and adding it, or taking it away from, the target date timestamp.
<end node> 5P9i0s8y19Z
dt=
<node>getdate
2
getdate
(PHP 3, PHP 4 )
getdate — Get date/time information
Description
array getdate ( [int timestamp])
Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given, as the following associative array elements:
Table 1. Key elements of the returned associative array
Key Description Example returned values
"seconds" Numeric representation of seconds 0 to 59
"minutes" Numeric representation of minutes 0 to 59
"hours" Numeric representation of hours 0 to 23
"mday" Numeric representation of the day of the month 1 to 31
"wday" Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
"mon" Numeric representation of a month 1 through 12
"year" A full numeric representation of a year, 4 digits Examples: 1999 or 2003
"yday" Numeric representation of the day of the year 0 through 366
"weekday" A full textual representation of the day of the week Sunday through Saturday
"month" A full textual representation of a month, such as January or March January through December
0 Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). System Dependent, typically -2147483648 through 2147483647.
Example 1. getdate() example
<?php
$today = getdate();
echo $today['year'];
print_r($today);
?>
The output will look similar to:
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
<end node> 5P9i0s8y19Z
dt=
<node>mdy to ymd
2
function convertdate($date1){
$p=strpos($date1,'/');
if ($p != 0){
$q=strpos($date1,'/',$p+1);
$m=substr($date1,0,$p);
$d=substr($date1,$p+1,$q-$p-1);
$y=substr($date1,$q+1);
}
$p=strpos($date1,'-');
if ($p != 0){
$q=strpos($date1,'-',$p+1);
$m=substr($date1,0,$p);
$d=substr($date1,$p+1,$q-$p-1);
$y=substr($date1,$q+1);
}
$new = mktime(0, 0, 0, $m, $d, $y);
$this= date('Y-m-j',$new);
return $this;
}
<end node> 5P9i0s8y19Z
dt=
<node>mktime
2
int mktime ( [int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year [, int $is_dst]]]]]]] )
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
<end node> 5P9i0s8y19Z
dt=
<node>mysql
2
Update adds Set durationdays=ADDDATE(now(),INTERVAL 30 DAY) WHERE addid=15
Date and Time Functions
This section describes the functions that can be used to manipulate temporal values. See section 6.2.2 Date and Time Types for a description of the range of values each date and time type has and the valid formats in which values may be specified.
Here is an example that uses date functions. The following query selects all records with a date_col value from within the last 30 days:
mysql> SELECT something FROM tbl_name
WHERE TO_DAYS(NOW()) – TO_DAYS(date_col) <= 30;
(Note that the query will also select records with dates that lie in the future.)
Functions that expect date values usually will accept datetime values and ignore the time part. Functions that expect time values usually will accept datetime values and ignore the date part.
Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query will always produce the same result. This principle also applies to CURDATE(), CURTIME(), UTC_DATE(), UTC_TIME(), UTC_TIMESTAMP(), and any of their synonyms.
The return value ranges in the following function descriptions apply for complete dates. If a date is a “zero'' value or an incomplete date such as '2001-11-00', functions that extract a part of a date may return 0. For example, DAYOFMONTH('2001-11-00') returns 0.
ADDDATE(date,INTERVAL expr type)
ADDDATE(expr,days)
When invoked with the INTERVAL form of the second argument, ADDDATE() is a synonym for DATE_ADD(). The related function SUBDATE() is a synonym for DATE_SUB().
mysql> SELECT DATE_ADD('1998-01-02', INTERVAL 31 DAY);
-> '1998-02-02'
mysql> SELECT ADDDATE('1998-01-02', INTERVAL 31 DAY);
-> '1998-02-02'
As of MySQL 4.1.1, the second syntax is allowed, where expr is a date or datetime expression and days is the number of days to be added to expr.
mysql> SELECT ADDDATE('1998-01-02', 31);
-> '1998-02-02'
ADDTIME(expr,expr2)
ADDTIME() adds expr2 to expr and returns the result. expr is a date or datetime expression, and expr2 is a time expression.
mysql> SELECT ADDTIME("1997-12-31 23:59:59.999999", "1 1:1:1.000002");
-> '1998-01-02 01:01:01.000001'
mysql> SELECT ADDTIME("01:00:00.999999", "02:00:00.999998");
-> '03:00:01.999997'
ADDTIME() was added in MySQL 4.1.1.
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context:
mysql> SELECT CURDATE();
-> '1997-12-15'
mysql> SELECT CURDATE() + 0;
-> 19971215
CURRENT_DATE
CURRENT_DATE()
CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE().
CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context:
mysql> SELECT CURTIME();
-> '23:50:26'
mysql> SELECT CURTIME() + 0;
-> 235026
CURRENT_TIME
CURRENT_TIME()
CURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME().
CURRENT_TIMESTAMP
CURRENT_TIMESTAMP()
CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW().
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03');
-> '2003-12-31'
DATE() is available as of MySQL 4.1.1.
DATEDIFF(expr,expr2)
DATEDIFF() returns the number of days between the start date expr and the end date expr2. expr and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');
-> 1
mysql> SELECT DATEDIFF('1997-11-31 23:59:59','1997-12-31');
-> -30
DATEDIFF() was added in MySQL 4.1.1.
DATE_ADD(date,INTERVAL expr type)
DATE_SUB(date,INTERVAL expr type)
These functions perform date arithmetic. As of MySQL Version 3.23, INTERVAL expr type is allowed on either side of the + operator if the expression on the other side is a date or datetime value. For the – operator, INTERVAL expr type is allowed only on the right side, because it makes no sense to subtract a date or datetime value from an interval. (See examples below.) date is a DATETIME or DATE value specifying the starting date. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a `-' for negative intervals. type is a keyword indicating how the expression should be interpreted. The following table shows how the type and expr arguments are related: type Value Expected expr Format
SECOND SECONDS
MINUTE MINUTES
HOUR HOURS
DAY DAYS
MONTH MONTHS
YEAR YEARS
MINUTE_SECOND 'MINUTES:SECONDS'
HOUR_MINUTE 'HOURS:MINUTES'
DAY_HOUR 'DAYS HOURS'
YEAR_MONTH 'YEARS-MONTHS'
HOUR_SECOND 'HOURS:MINUTES:SECONDS'
DAY_MINUTE 'DAYS HOURS:MINUTES'
DAY_SECOND 'DAYS HOURS:MINUTES:SECONDS'
DAY_MICROSECOND 'DAYS.MICROSECONDS'
HOUR_MICROSECOND 'HOURS.MICROSECONDS'
MINUTE_MICROSECOND 'MINUTES.MICROSECONDS'
SECOND_MICROSECOND 'SECONDS.MICROSECONDS'
MICROSECOND 'MICROSECONDS'
The type values DAY_MICROSECOND, HOUR_MICROSECOND, MINUTE_MICROSECOND, SECOND_MICROSECOND, and MICROSECOND are allowed as of MySQL 4.1.1. MySQL allows any punctuation delimiter in the expr format. Those shown in the table are the suggested delimiters. If the date argument is a DATE value and your calculations involve only YEAR, MONTH, and DAY parts (that is, no time parts), the result is a DATE value. Otherwise, the result is a DATETIME value:
mysql> SELECT '1997-12-31 23:59:59' + INTERVAL 1 SECOND;
-> '1998-01-01 00:00:00'
mysql> SELECT INTERVAL 1 DAY + '1997-12-31';
-> '1998-01-01'
mysql> SELECT '1998-01-01' – INTERVAL 1 SECOND;
-> '1997-12-31 23:59:59'
mysql> SELECT DATE_ADD('1997-12-31 23:59:59',
-> INTERVAL 1 SECOND);
-> '1998-01-01 00:00:00'
mysql> SELECT DATE_ADD('1997-12-31 23:59:59',
-> INTERVAL 1 DAY);
-> '1998-01-01 23:59:59'
mysql> SELECT DATE_ADD('1997-12-31 23:59:59',
-> INTERVAL '1:1' MINUTE_SECOND);
-> '1998-01-01 00:01:00'
mysql> SELECT DATE_SUB('1998-01-01 00:00:00',
-> INTERVAL '1 1:1:1' DAY_SECOND);
-> '1997-12-30 22:58:59'
mysql> SELECT DATE_ADD('1998-01-01 00:00:00',
-> INTERVAL '-1 10' DAY_HOUR);
-> '1997-12-30 14:00:00'
mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
-> '1997-12-02'
mysql> SELECT DATE_ADD('1992-12-31 23:59:59.000002',
-> INTERVAL '1.999999' SECOND_MICROSECOND);
-> '1993-01-01 00:00:01.000001'
If you specify an interval value that is too short (does not include all the interval parts that would be expected from the type keyword), MySQL assumes you have left out the leftmost parts of the interval value. For example, if you specify a type of DAY_SECOND, the value of expr is expected to have days, hours, minutes, and seconds parts. If you specify a value like '1:10', MySQL assumes that the days and hours parts are missing and the value represents minutes and seconds. In other words, '1:10' DAY_SECOND is interpreted in such a way that it is equivalent to '1:10' MINUTE_SECOND. This is analogous to the way that MySQL interprets TIME values as representing elapsed time rather than as time of day. Note that if you add to or subtract from a date value something that contains a time part, the result is automatically converted to a datetime value:
mysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 DAY);
-> '1999-01-02'
mysql> SELECT DATE_ADD('1999-01-01', INTERVAL 1 HOUR);
-> '1999-01-01 01:00:00'
If you use really malformed dates, the result is NULL. If you add MONTH, YEAR_MONTH, or YEAR and the resulting date has a day that is larger than the maximum day for the new month, the day is adjusted to the maximum days in the new month:
mysql> SELECT DATE_ADD('1998-01-30', interval 1 month);
-> '1998-02-28'
Note from the preceding example that the keyword INTERVAL and the type specifier are not case-sensitive.
DATE_FORMAT(date,format)
Formats the date value according to the format string. The following specifiers may be used in the format string: Specifier Description
%M Month name (January..December)
%W Weekday name (Sunday..Saturday)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, etc.)
%Y Year, numeric, 4 digits
%y Year, numeric, 2 digits
%X Year for the week where Sunday is the first day of the week, numeric, 4 digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, 4 digits; used with %v
%a Abbreviated weekday name (Sun..Sat)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%m Month, numeric (00..12)
%c Month, numeric (0..12)
%b Abbreviated month name (Jan..Dec)
%j Day of year (001..366)
%H Hour (00..23)
%k Hour (0..23)
%h Hour (01..12)
%I Hour (01..12)
%l Hour (1..12)
%i Minutes, numeric (00..59)
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%T Time, 24-hour (hh:mm:ss)
%S Seconds (00..59)
%s Seconds (00..59)
%f Microseconds (000000..999999)
%p AM or PM
%w Day of the week (0=Sunday..6=Saturday)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%% A literal `%'.
All other characters are just copied to the result without interpretation. The %f format specifier is available as of MySQL 4.1.1. As of MySQL Version 3.23, the `%' character is required before format specifier characters. In earlier versions of MySQL, `%' was optional. The reason the ranges for the month and day specifiers begin with zero is that MySQL allows incomplete dates such as '2004-00-00' to be stored as of MySQL 3.23.
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');
-> 'Saturday October 1997'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00', '%H:%i:%s');
-> '22:23:00'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
'%D %y %a %d %m %b %j');
-> '4th 97 Sat 04 10 Oct 277'
mysql> SELECT DATE_FORMAT('1997-10-04 22:23:00',
'%H %k %I %r %T %S %w');
-> '22 22 10 10:23:00 PM 22:23:00 00 6'
mysql> SELECT DATE_FORMAT('1999-01-01', '%X %V');
-> '1998 52'
DAY(date)
DAY() is a synonym for DAYOFMONTH(). It is available as of MySQL 4.1.1.
DAYNAME(date)
Returns the name of the weekday for date:
mysql> SELECT DAYNAME('1998-02-05');
-> 'Thursday'
DAYOFMONTH(date)
Returns the day of the month for date, in the range 1 to 31:
mysql> SELECT DAYOFMONTH('1998-02-03');
-> 3
DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, … 7 = Saturday). These index values correspond to the ODBC standard.
mysql> SELECT DAYOFWEEK('1998-02-03');
-> 3
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366:
mysql> SELECT DAYOFYEAR('1998-02-03');
-> 34
EXTRACT(type FROM date)
The EXTRACT() function uses the same kinds of interval type specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic.
mysql> SELECT EXTRACT(YEAR FROM "1999-07-02");
-> 1999
mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03");
-> 199907
mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:02:03");
-> 20102
mysql> SELECT EXTRACT(MICROSECOND FROM "2003-01-02 10:30:00.00123");
-> 123
FROM_DAYS(N)
Given a daynumber N, returns a DATE value:
mysql> SELECT FROM_DAYS(729669);
-> '1997-10-07'
FROM_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it doesn't take into account the days that were lost when the calendar was changed.
FROM_UNIXTIME(unix_timestamp)
FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context:
mysql> SELECT FROM_UNIXTIME(875996580);
-> '1997-10-04 22:23:00'
mysql> SELECT FROM_UNIXTIME(875996580) + 0;
-> 19971004222300
If format is given, the result is formatted according to the format string. format may contain the same specifiers as those listed in the entry for the DATE_FORMAT() function:
mysql> SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(),
-> '%Y %D %M %h:%i:%s %x');
-> '2003 6th August 06:22:58 2003'
GET_FORMAT(DATE | TIME | TIMESTAMP, 'EUR' | 'USA' | 'JIS' | 'ISO' | 'INTERNAL')
Returns a format string. This function is useful in combination with the DATE_FORMAT() and the STR_TO_DATE() functions, and when setting the server variables DATE_FORMAT, TIME_FORMAT, and DATETIME_FORMAT. The three possible values for the first argument and the five possible values for the second argument result in 15 possible format strings (for the specifiers used, see the table in the DATE_FORMAT() function description): Function call Result
GET_FORMAT(DATE,'USA') '%m.%d.%Y'
GET_FORMAT(DATE,'JIS') '%Y-%m-%d'
GET_FORMAT(DATE,'ISO') '%Y-%m-%d'
GET_FORMAT(DATE,'EUR') '%d.%m.%Y'
GET_FORMAT(DATE,'INTERNAL') '%Y%m%d'
GET_FORMAT(TIMESTAMP,'USA') '%Y-%m-%d-%H.%i.%s'
GET_FORMAT(TIMESTAMP,'JIS') '%Y-%m-%d %H:%i:%s'
GET_FORMAT(TIMESTAMP,'ISO') '%Y-%m-%d %H:%i:%s'
GET_FORMAT(TIMESTAMP,'EUR') '%Y-%m-%d-%H.%i.%s'
GET_FORMAT(TIMESTAMP,'INTERNAL') '%Y%m%d%H%i%s'
GET_FORMAT(TIME,'USA') '%h:%i:%s %p'
GET_FORMAT(TIME,'JIS') '%H:%i:%s'
GET_FORMAT(TIME,'ISO') '%H:%i:%s'
GET_FORMAT(TIME,'EUR') '%H.%i.%S'
GET_FORMAT(TIME,'INTERNAL') '%H%i%s'
ISO format is ISO 9075, not ISO 8601.
mysql> SELECT DATE_FORMAT('2003-10-03', GET_FORMAT(DATE, 'EUR')
-> '03.10.2003'
mysql> SELECT STR_TO_DATE('10.31.2003', GET_FORMAT(DATE, 'USA'))
-> 2003-10-31
mysql> SET DATE_FORMAT=GET_FORMAT(DATE, 'USA'); SELECT '2003-10-31';
-> 10-31-2003
GET_FORMAT() is available as of MySQL 4.1.1. See See section 5.5.6 SET Syntax.
HOUR(time)
Returns the hour for time. The range of the return value will be 0 to 23 for time-of-day values:
mysql> SELECT HOUR('10:05:03');
-> 10
However, the range of TIME values actually is much larger, so HOUR can return values greater than 23:
mysql> SELECT HOUR('272:59:59');
-> 272
LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the month. Returns NULL if the argument is invalid.
mysql> SELECT LAST_DAY('2003-02-05'), LAST_DAY('2004-02-05');
-> '2003-02-28', '2004-02-29'
mysql> SELECT LAST_DAY('2004-01-01 01:01:01');
-> '2004-01-31'
mysql> SELECT LAST_DAY('2003-03-32');
-> NULL
LAST_DAY() is available as of MySQL 4.1.1.
LOCALTIME
LOCALTIME()
LOCALTIME and LOCALTIME() are synonyms for NOW().
LOCALTIMESTAMP
LOCALTIMESTAMP()
LOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW().
MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. dayofyear must be greater than 0 or the result will NULL.
mysql> SELECT MAKEDATE(2001,31), MAKEDATE(2001,32);
-> '2001-01-31', '2001-02-01'
mysql> SELECT MAKEDATE(2001,365), MAKEDATE(2004,365);
-> '2001-12-31', '2004-12-30'
mysql> SELECT MAKEDATE(2001,0);
-> NULL
MAKEDATE() is available as of MySQL 4.1.1.
MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute, and second arguments.
mysql> SELECT MAKETIME(12,15,30);
-> '12:15:30'
MAKETIME() is available as of MySQL 4.1.1.
MICROSECOND(expr)
Returns the microseconds from the time or datetime expression expr as a number in the range from 0 to 999999.
mysql> SELECT MICROSECOND('12:00:00.123456');
-> 123456
mysql> SELECT MICROSECOND('1997-12-31 23:59:59.000010');
-> 10
MICROSECOND() is available as of MySQL 4.1.1.
MINUTE(time)
Returns the minute for time, in the range 0 to 59:
mysql> SELECT MINUTE('98-02-03 10:05:03');
-> 5
MONTH(date)
Returns the month for date, in the range 1 to 12:
mysql> SELECT MONTH('1998-02-03');
-> 2
MONTHNAME(date)
Returns the name of the month for date:
mysql> SELECT MONTHNAME('1998-02-05');
-> 'February'
NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context:
mysql> SELECT NOW();
-> '1997-12-15 23:50:26'
mysql> SELECT NOW() + 0;
-> 19971215235026
PERIOD_ADD(P,N)
Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the format YYYYMM. Note that the period argument P is not a date value:
mysql> SELECT PERIOD_ADD(9801,2);
-> 199803
PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values:
mysql> SELECT PERIOD_DIFF(9802,199703);
-> 11
QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4:
mysql> SELECT QUARTER('98-04-01');
-> 2
SECOND(time)
Returns the second for time, in the range 0 to 59:
mysql> SELECT SECOND('10:05:03');
-> 3
SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes, and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context:
mysql> SELECT SEC_TO_TIME(2378);
-> '00:39:38'
mysql> SELECT SEC_TO_TIME(2378) + 0;
-> 3938
STR_TO_DATE(str,format)
This is the reverse function of the DATE_FORMAT() function. It takes a string str, and a format string format, and returns a DATETIME value. The date, time, or datetime values contained in str should be given in the format indicated by format. For the specifiers that can be used in format, see the table in the DATE_FORMAT() function description. All other characters are just taken verbatim, thus not being interpreted. If str contains an illegal date, time, or datetime value, STR_TO_DATE() returns NULL.
mysql> SELECT STR_TO_DATE('03.10.2003 09.20', '%d.%m.%Y %H.%i')
-> 2003-10-03 09:20:00
mysql> SELECT STR_TO_DATE('10rap', '%crap')
-> 0000-10-00 00:00:00
mysql> SELECT STR_TO_DATE('2003-15-10 00:00:00', '%Y-%m-%d %H:%i:%s')
-> NULL
STR_TO_DATE() is available as of MySQL 4.1.1.
SUBDATE(date,INTERVAL expr type)
SUBDATE(expr,days)
When invoked with the INTERVAL form of the second argument, SUBDATE() is a synonym for DATE_SUB().
mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
-> '1997-12-02'
mysql> SELECT SUBDATE('1998-01-02', INTERVAL 31 DAY);
-> '1997-12-02'
As of MySQL 4.1.1, the second syntax is allowed, where expr is a date or datetime expression and days is the number of days to be subtracted from expr.
mysql> SELECT SUBDATE('1998-01-02 12:00:00', 31);
-> '1997-12-02 12:00:00'
SUBTIME(expr,expr2)
SUBTIME() subtracts expr2 from expr and returns the result. expr is a date or datetime expression, and expr2 is a time expression.
mysql> SELECT SUBTIME("1997-12-31 23:59:59.999999", "1 1:1:1.000002");
-> '1997-12-30 22:58:58.999997'
mysql> SELECT SUBTIME("01:00:00.999999", "02:00:00.999998");
-> '-00:59:59.999999'
SUBTIME() was added in MySQL 4.1.1.
SYSDATE()
SYSDATE() is a synonym for NOW().
TIME(expr)
Extracts the time part of the time or datetime expression expr.
mysql> SELECT TIME('2003-12-31 01:02:03');
-> '01:02:03'
mysql> SELECT TIME('2003-12-31 01:02:03.000123');
-> '01:02:03.000123'
TIME() is available as of MySQL 4.1.1.
TIMEDIFF(expr,expr2)
TIMEDIFF() returns the time between the start time expr and the end time expr2. expr and expr2 are time or date-and-time expressions, but both must be of the same type.
mysql> SELECT TIMEDIFF('2000:01:01 00:00:00', '2000:01:01 00:00:00.000001');
-> '-00:00:00.000001'
mysql> SELECT TIMEDIFF('1997-12-31 23:59:59.000001','1997-12-30 01:01:01.000002');
-> '46:58:57.999999'
TIMEDIFF() was added in MySQL 4.1.1.
TIMESTAMP(expr)
TIMESTAMP(expr,expr2)
With one argument, returns the date or datetime expression expr as a datetime value. With two arguments, adds the time expression expr2 to the date or datetime expression expr and returns a datetime value.
mysql> SELECT TIMESTAMP('2003-12-31');
-> '2003-12-31 00:00:00'
mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');
-> '2004-01-01 00:00:00'
TIMESTAMP() is available as of MySQL 4.1.1.
TIME_FORMAT(time,format)
This is used like the DATE_FORMAT() function, but the format string may contain only those format specifiers that handle hours, minutes, and seconds. Other specifiers produce a NULL value or 0. If the time value contains an hour part that is greater than 23, the %H and %k hour format specifiers produce a value larger than the usual range of 0..23. The other hour format specifiers produce the hour value modulo 12:
mysql> SELECT TIME_FORMAT('100:00:00', '%H %k %h %I %l');
-> '100 100 04 04 4'
TIME_TO_SEC(time)
Returns the time argument, converted to seconds:
mysql> SELECT TIME_TO_SEC('22:23:00');
-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
TO_DAYS(date)
Given a date date, returns a daynumber (the number of days since year 0):
mysql> SELECT TO_DAYS(950501);
-> 728779
mysql> SELECT TO_DAYS('1997-10-07');
-> 729669
TO_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582), because it doesn't take into account the days that were lost when the calendar was changed.
UNIX_TIMESTAMP()
UNIX_TIMESTAMP(date)
If called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' GMT) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' GMT. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or YYYYMMDD in local time:
mysql> SELECT UNIX_TIMESTAMP();
-> 882226357
mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');
-> 875996580
When UNIX_TIMESTAMP is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp'' conversion. If you pass an out-of-range date to UNIX_TIMESTAMP() it returns 0, but please note that only basic checking is performed (year 1970-2037, month 01-12, day 01-31). If you want to subtract UNIX_TIMESTAMP() columns, you may want to cast the result to signed integers. See section 6.3.5 Cast Functions.
UTC_DATE
UTC_DATE()
Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context:
mysql> SELECT UTC_DATE(), UTC_DATE() + 0;
-> '2003-08-14', 20030814
UTC_DATE() is available as of MySQL 4.1.1.
UTC_TIME
UTC_TIME()
Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context:
mysql> SELECT UTC_TIME(), UTC_TIME() + 0;
-> '18:07:53', 180753
UTC_TIME() is available as of MySQL 4.1.1.
UTC_TIMESTAMP
UTC_TIMESTAMP()
Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context:
mysql> SELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0;
-> '2003-08-14 18:08:04', 20030814180804
UTC_TIMESTAMP() is available as of MySQL 4.1.1.
WEEK(date [,mode])
The function returns the week number for date. The two-argument form of WEEK() allows you to specify whether the week starts on Sunday or Monday and whether the return value should be in the range 0-53 or 1-52. When mode argument is omitted the value of a default_week_format server variable (or 0 in MySQL 4.0 or earlier) is assumed. See section 5.5.6 SET Syntax. The following table demonstrates how the mode argument works: Value Meaning
0 Week starts on Sunday; return value range is 0 to 53; week 1 is the first week that starts in this year
1 Week starts on Monday; return value range is 0 to 53; week 1 is the first week that has more than 3 days in this year
2 Week starts on Sunday; return value range is 1 to 53; week 1 is the first week that starts in this year
3 Week starts on Monday; return value range is 1 to 53; week 1 is the first week that has more than 3 days in this year
4 Week starts on Sunday; return value range is 0 to 53; week 1 is the first week that has more than 3 days in this year
5 Week starts on Monday; return value range is 0 to 53; week 1 is the first week that starts in this year
6 Week starts on Sunday; return value range is 1 to 53; week 1 is the first week that has more than 3 days in this year
7 Week starts on Monday; return value range is 1 to 53; week 1 is the first week that starts in this year
The mode value of 3 can be used as of MySQL 4.0.5. The mode value of 4 and above can be used as of MySQL 4.0.17.
mysql> SELECT WEEK('1998-02-20');
-> 7
mysql> SELECT WEEK('1998-02-20',0);
-> 7
mysql> SELECT WEEK('1998-02-20',1);
-> 8
mysql> SELECT WEEK('1998-12-31',1);
-> 53
Note: In Version 4.0, WEEK(date,0) was changed to match the calendar in the USA. Before that, WEEK() was calculated incorrectly for dates in USA. (In effect, WEEK(date) and WEEK(date,0) was incorrect for all cases.) Note that if a date falls in the last week of the previous year, MySQL will return 0 if you don't use 2, 3, 6, or 7 as the optional mode argument:
mysql> SELECT YEAR('2000-01-01'), WEEK('2000-01-01',0);
-> 2000, 0
One might argue that MySQL should return 52 for the WEEK() function, because the given date actually occurs in the 52nd week of 1999. We decided to return 0 instead as we want the function to return “the week number in the given year.'' This makes the usage of the WEEK() function reliable when combined with other functions that extract a date part from a date. If you would prefer the result to be evaluated with respect to the year that contains the first day of the week for the given date, you should use 2, 3, 6, or 7 as the optional mode argument.
mysql> SELECT WEEK('2000-01-01',2);
-> 52
Alternatively, use the YEARWEEK() function:
mysql> SELECT YEARWEEK('2000-01-01');
-> 199952
mysql> SELECT MID(YEARWEEK('2000-01-01'),5,2);
-> '52'
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday):
mysql> SELECT WEEKDAY('1998-02-03 22:23:00');
-> 1
mysql> SELECT WEEKDAY('1997-11-05');
-> 2
WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.
mysql> SELECT WEEKOFYEAR('1998-02-20');
-> 8
WEEKOFYEAR() is available as of MySQL 4.1.1.
YEAR(date)
Returns the year for date, in the range 1000 to 9999:
mysql> SELECT YEAR('98-02-03');
-> 1998
YEARWEEK(date)
YEARWEEK(date,start)
Returns year and week for a date. The start argument works exactly like the start argument to WEEK(). Note that the year in the result may be different from the year in the date argument for the first and the last week of the year:
mysql> SELECT YEARWEEK('1987-01-01');
-> 198653
Note that the week number is different from what the WEEK() function would return (0) for optional arguments 0 or 1, as WEEK() then returns the week in the context of the given year.
<end node> 5P9i0s8y19Z
dt=
<node>valid date
2
checkdate(int month, int day, int year) will return true if it is a date.
<end node> 5P9i0s8y19Z
dt=
<node>ymd to mdy
2
function convertmdy($date1){
$p=strpos($date1,'/');
if ($p != 0){
$q=strpos($date1,'/',$p+1);
$y=substr($date1,0,$p);
$m=substr($date1,$p+1,$q-$p-1);
$d=substr($date1,$q+1);
}
$p=strpos($date1,'-');
if ($p != 0){
$q=strpos($date1,'-',$p+1);
$y=substr($date1,0,$p);
$m=substr($date1,$p+1,$q-$p-1);
$d=substr($date1,$q+1);
}
$new = mktime(0, 0, 0, $m, $d, $y);
$this= date('m/j/y',$new);
return $this;
}
<end node> 5P9i0s8y19Z
dt=
<node>email
1
$body="pLAYHOUSE INDEX PAGE CHECK"; $to="steve@softwarewebdesign.com";
$from="stevew@thinairnet.com";
$replyto=$from;
$subject="Playhouse web has been viewed…";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
/* additional headers */
//$headers .= "To: ".$FirstName." ".$LastName."<".$to.">\r\n";
$headers .= "From: ".$from."\r\n";
//$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
//$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
mail($to, $subject, $body, $headers);
$body="<html><body><table><tr>".$display."</body></html>";
$from="CommercialRentals.biz <steve@cyber-shoppes.net>";
$replyto=$from;
$subject="Your Commercial Rental has been viewed…";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
/* additional headers */
//$headers .= "To: ".$FirstName." ".$LastName."<".$to.">\r\n";
$headers .= "To: <".$email.">\r\n";
$headers .= "From: ".$from."\r\n";
$headers .= 'Cc: birthdayarchive@example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck@example.com' . "\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
mail($to, $subject, $body, $headers);
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "To: <".$email.">\r\n";
$headers .= "From: ".$from."\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
<end node> 5P9i0s8y19Z
dt=
<node>mail
2
$sql="SELECT * FROM email_messages WHERE messageid = 2";
$mes=dbq($sql,$tmp,1,3);
$body=$mes["body"];
$subject=$mes["subject"];
$from="sfennell@tcccorp.net";
$sql="SELECT * FROM project_assign WHERE projectid=$PID AND sent=0";
$result=dbq($sql,$num,1,1);
for($i=1;$i<=$num;$i++){
$row=mysql_fetch_array($result);$subcontractorid=$row["subcontractorid"];$assignid=$row["assignid"];
$sql="SELECT company,email FROM subcontractor WHERE subcontractorid=$subcontractorid";
$row9=dbq($sql,$tmp,1,3);
$to=$row9[1]; //$to="projects@cyber-shoppes.net";
//$to="steve@cyber-shoppes.net"; // Test to
$replyto=$mes["replyto"];
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ".$from."\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
$headers .="bcc:stevew@thinairnet.com,lori@dagamawebstudio.com\r\n";
//$dis=$to;
//echo $to."==".$subject."==".$body."==".$headers;
mail($to, $subject, $body, $headers);
$sql="UPDATE project_assign SET sent=1 WHERE assignid=$assignid";
dbq($sql,$tmp,1,0);
<end node> 5P9i0s8y19Z
dt=
<node>mail script
3
$body="<html><head></head><style>body{font-family:verdana}</style><body>";
$body.="<font color='blue'>".$firstname." ".$lastname."</font> has viewed the eatfree coupon on <b>".date('m/j/Y')."</b>";
$body.="<p>This email is in response of a survey the was fill out on newbeeswelcome.com.";
$body.="</body></html>";
//$from="steve@cyber-shoppes.net";$to=$from;
$from="info@newbeeswelcome.com";$to=$from;
//$to="steve@cyber-shoppes.net"; // Test to
$replyto="info@newbeeswelcome.com";
$subject=$firstname." ".$lastname." has viewed the eat free coupon…";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "To: <".$to.">\r\n";
$headers .= "From: ".$from."\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
mail($to, $subject, $body, $headers);
***********************
<?php
# Simple mail sender with PHP v1.0
# Copyright 2001 Advanced Internet Technologies
# Created 03 Aug 2001 Last modified 03 Aug 2001
#——————————————————————————-
# COPYRIGHT NOTICE
# Copyright 2001 Advanced Internet Technologies All Rights Reserved
#
# This script may be used and modified free of charge by anyone so long as
# this copyright notice and the comments above remain intact. By using this
# code you agree to indemnify Advanced Internet Technologies from any
# liability that might arise from its use.
#
# Selling this code without prior written consent is expressely forbidden.
#
# Obtain permission before redistributing this software over the Internet or
# in any other medium. In all cases, copyright and header must remain intact.
#——————————————————————————-
if (strtoupper($REQUEST_METHOD) != "POST") {
die("Only POST method is allowed");
}
if (!strlen($HTTP_POST_VARS)) {
die("No data was provided");
}
$form = array();
reset($form);
while (list($key, $value) = each($HTTP_POST_VARS)) {
$form[htmlspecialchars(urldecode($key))] = htmlspecialchars(urldecode($value));
}
# MODIFY the following section to suit your needs
$recipient = 'someone@yourdomain.com';
$subject = stripslashes($form[subject]);
$message = stripslashes($form[message]);
# END MODIFY fields
if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$",$form[sender])) {
$sender = $form[sender];
} else {
die("Invalid sender specified");
}
$header = "From: $sender\nReply-To: $sender\n";
$result = mail($recipient, $subject, $message, $header);
if (!$result) {
die("Error sending mail");
} else {
if ($form[thank_url]) {
header("Location: $form[thank_url]");
exit;
} else {
print "Mail sent";
}
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>return path
3
The ini_set('sendmail_from', $your_from_addr) solution only works when the PHP mailer script is running under Windows. To do a similar solution for *nix OS's, pass the string "-r $your_from_addr" to mail() as the fifth parameter.
<end node> 5P9i0s8y19Z
dt=
<node>Verify
2
<?php
function checkhtml($var){
$var2=strip_tags($var);
if($var2!=$var){ echo "Mail Server Crashed";exit; }
if(strpos("|".$var,"http:")>0){ echo "Mail Server Crashed";exit; }
$var=addslashes($var);
return $var;
}
$fullname=$_POST['fullname'];
$fullname=checkhtml(trim($fullname));
$company=$_POST['company'];
$company=checkhtml(trim($company));
$address=$_POST['address'];
$address=checkhtml(trim($address));
$city=$_POST['city'];
$city=checkhtml(trim($city));
$state=$_POST['state'];
$state=checkhtml(trim($state));
$zipcode=$_POST['zipcode'];
$zipcode=checkhtml(trim($zipcode));
$country=$_POST['country'];
$country=checkhtml(trim($country));
$EmailAddress=$_POST['EmailAddress'];
$EmailAddress=checkhtml(trim($EmailAddress));
$phone=$_POST['phone'];
$phone=checkhtml(trim($phone));
$heard_about_you_this_way=$_POST['heard_about_you_this_way'];
$heard_about_you_this_way=checkhtml(trim($heard_about_you_this_way));
$comments=$_POST['comments'];
$comments=checkhtml(trim($comments));
$body="<table>
<tr><td>fullname: <td>$fullname
<tr><td>company: <td>$company
<tr><td>address: <td>$address
<tr><td>city: <td>$city
<tr><td>state: <td>$state
<tr><td>zipcode: <td>$zipcode
<tr><td>country: <td>$country
<tr><td>EmailAddress: <td>$EmailAddress
<tr><td>phone: <td>$phone
<tr><td>heard_about_you_this_way: <td>$heard_about_you_this_way
<tr><td>comments: <td>$comments</table>";
$redirect=$_POST["redirect"];
$subject=$_POST["subject"];$to="susan@somethingwithpizzaz.com"; $to="projects@softwarewebdesign.com";
if($email!=""){ $from=$email;$replyto=$from; }
else { $from="susan@somethingwithpizzaz.com";$replyto=$from; }
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ".$from."\r\n";
$headers .= "Reply-To: ".$replyto."\r\n";
mail($to, $subject, $body, $headers);
header("Location:$redirect");
?>
<end node> 5P9i0s8y19Z
dt=
<node>files
1
$ext = pathinfo($path, PATHINFO_EXTENSION);
If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.
If options is not specified, returns all available elements.
Return Values ¶
If the options parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
The above example will output:
/www/htdocs/inc
lib.inc.php
php
lib.inc
================================
file_exists()
filesize()
<end node> 5P9i0s8y19Z
dt=
<node>Copy,Move,Kill
2
copy($source,$destination);
unlink($source);
rename($oldfile,$newfile);
from MenuCreat.php_________________
$whichfile is the tempalte number
if($createfile==true && strpos($file0,"ttp://")==0){
$fnd=strpos($file0,"?");
if($fnd>0)$file0=substr($file0,0,$fnd);
if(!file_exists($destinationfolder.$file0)){
//echo "==".$destinationfolder.$menu[$K][1]."<br>";
copy($templatefolder.$template.$whichfile.".php",$destinationfolder.$file0);
}
}
<end node> 5P9i0s8y19Z
dt=
<node>directory
2
[top dir]
dirname(__FILE__)
mkdir('/home/benge/photos/gallery1/extra_large', 0777);
Check for existence
if(is_dir($dirname))
[working directory]
if($ID==""){
$dir1=getcwd();$k=1;
while ($k>0){
$k1=$k;
$k=strpos($dir1,"/",$k+1);
}
$dir1=substr($dir1,$k1+1,strlen($dir1)-$k1);
$sql="SELECT userid FROM users WHERE userpath='$dir1'";
$row9=dbq($sql,$num,1,3);
$HTTP_SESSION_VARS['USERID']=$row9;$ID=$row9;
}
<end node> 5P9i0s8y19Z
dt=
<node>downloads
2
if(is_dir($folder2)==false) { mkdir($folder2);copy($folder1."/".$book,$folder2."/".$book); }
$filesize=filesize($folder2."/".$book);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header ( "Content-Type: application/pdf" );
header("Content-Disposition: attachment; filename=\"$booktitle\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$filesize);
$file=$folder2."/".$book;
readfile($file);
<end node> 5P9i0s8y19Z
dt=
<node>exists
2
if(file_exists($upfile))unlink($upfile);
<end node> 5P9i0s8y19Z
dt=
<node>file ntype
2
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>
<end node> 5P9i0s8y19Z
dt=
<node>open files
2
Mode Description
r Read Only mode, with the file pointer at the start of the file.
r+ Read/Write mode, with the file pointer at the start of the file.
w Write Only mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.
w+ Read/Write mode. Truncates the file (effectively overwriting it). If the file doesn't exist, fopen will attempt to create the file.
a Append mode, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.
a+ Read/Append, with the file pointer at the end of the file. If the file doesn't exist, fopen will attempt to create the file.
$fp = fopen("junk.txt", "r");
fclose($fp);
NO QUOTATION MARKS AROUND FILE NAMES
<end node> 5P9i0s8y19Z
dt=
<node>read
3
<?php
if (!($fp = fopen("junk.txt", "r")))
exit("Unable to open the input file.");
while (!feof($fp))
{
$c = fgetc($fp);
print $c;
}
fclose($fp);
?>
*****************************
The fseek function may be used to position the file pointer at a particular point in the file. For example, the following could be used to position the file pointer at the sixth character in the file.
fseek($fp, 5);
**********************************************
Reading Words
The fscanf function is used for reading a word at a time from a file. Unlike the C/C++ equivalent of the fscanf function, if it hasn't read all the words on the line, the file pointer is positioned at the next line in the file. The function takes a variable number of parameters, but the first two parameters are mandatory. The first parameter is the file handle, the second parameter is a c-style format string. Any parameters passed after this are optional, but if used will contain the values of the format string.
Consider the following entries in a file called, "list.txt".
list.txt
Dave Programmer 34
Sue Designer 21
Lisa Programmer 29
Nigel User 19
The following reads a line from the file, and assigns the values to the variables $name, $title, and $age, where "%s %s %d" is the format string to read two strings (%s), and one integer (%d).
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
The variable, $buffer, will contain the number of values it was able to assign. The following example reads the file listed above until the end of file has been reached.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Using fscanf with Optional Variables</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
$listFile = "list.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open $listFile.");
while (!feof($fp))
{
// Assign variables to optional arguments
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
if ($buffer == 3)
print "$name $title $age<br>\n";
}
fclose ($fp);
?>
</p>
</body>
</html>
<end node> 5P9i0s8y19Z
dt=
<node>read lines
4
Reading Lines
The fgets function is used to read a line at a time. The function takes two parameters, the file handle, and the number of bytes to read. The function reads data up to a new line, or the number of bytes specified (whichever comes first), and returns the line read. The following is an example of using the fgets function.
<?php
if (!($fp = fopen("junk.txt", "r")))
exit("Unable to open the input file.");
while (!feof($fp))
{
$buffer = fgets($fp, 1024);
print "$buffer<br>\n";
}
fclose($fp);
?>
<end node> 5P9i0s8y19Z
dt=
<node>single character
4
Reading a Character
The fgetc() function is used to read a single character from a file.
Note: After a call to this function the file pointer has moved to the next character.
Example
The example below reads a file character by character, until the end of file is true:
<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file.");
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
fclose($f);
?>
<end node> 5P9i0s8y19Z
dt=
<node>string
4
file_get_contents
(PHP 4 >= 4.3.0, PHP 5)
file_get_contents – Reads entire file into a string
Description ¶
string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
This function is similar to file(), except that file_get_contents() returns the file in a string, starting at the specified offset up to maxlen bytes. On failure, file_get_contents() will return FALSE.
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Note:
If you're opening a URI with special characters, such as spaces, you need to encode the URI with urlencode().
Parameters ¶
filename
Name of the file to read.
use_include_path
Note:
As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger include path search.
context
A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.
offset
The offset where the reading starts on the original stream.
Seeking (offset) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.
maxlen
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
Return Values ¶
The function returns the read data or FALSE on failure.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Errors/Exceptions ¶
An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.
Examples ¶
Example #1 Get and output the source of the homepage of a website
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
Example #2 Searching within the include_path
<?php
// <= PHP 5
$file = file_get_contents('./people.txt', true);
// > PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
Example #3 Reading a section of a file
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
The above example will output something similar to:
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
=====================================================================
file_put_contents
(PHP 5)
file_put_contents – Write a string to a file
Description ¶
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
Parameters ¶
filename
Path to the file where to write the data.
data
The data to write. Can be either a string, an array or a stream resource.
If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().
You can also specify the data parameter as a single dimension array. This is equivalent to file_put_contents($filename, implode('', $array)).
flags
The value of flags can be any combination of the following flags, joined with the binary OR (|) operator.
Available flags Flag Description
FILE_USE_INCLUDE_PATH Search for filename in the include directory. See include_path for more information.
FILE_APPEND If file filename already exists, append the data to the file instead of overwriting it.
LOCK_EX Acquire an exclusive lock on the file while proceeding to the writing.
context
A valid context resource created with stream_context_create().
Return Values ¶
This function returns the number of bytes that were written to the file, or FALSE on failure.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Examples ¶
Example #1 Simple usage example
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Example #2 Using flags
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>
<end node> 5P9i0s8y19Z
dt=
<node>whole file
4
Reading the Whole File
The fread function reads a number of bytes from a file, up to the end of the file (whichever comes first). The filesize function returns the size of the file in bytes, and can be used with the fread function, as in the following example.
<?php
$listFile = "junk.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
print "$buffer<br>\n";
fclose($fp);
?>
<end node> 5P9i0s8y19Z
dt=
<node>Write
3
Writing to Files
The fwrite function is used to write a string, or part of a string to a file. The function takes three parameters, the file handle, the string to write, and the number of bytes to write. If the number of bytes is omitted, the whole string is written to the file. If you want the lines to appear on separate lines in the file, use the \n character. Note: Windows requires a carriage return character as well as a new line character, so if you're using Windows, terminate the string with \r\n.
The following example logs the visitor to a file, then displays all the entries in the file.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Statistics File</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<p>
<?php
$logFile = "stats.txt";
// Open the file in append/read mode
$fp = fopen($logFile, "a+");
// Create a string containing the user details
$userDetails = $HTTP_USER_AGENT;
if (isset($HTTP_REFERER))
$userDetails = $userDetails . " $HTTP_REFERER <br>\r\n";
else
$userDetails = $userDetails . "<br>\r\n";
// Write the user details to the file
fwrite($fp, "$userDetails");
// Move to the start of the file
rewind($fp);
$entries = 0;
// Display each line in the file
while(!feof($fp))
{
$buffer = fgets($fp, 1024);
if ($buffer != "")
{
print $buffer;
$entries++;
}
}
// Show a summary
print "There are $entries entries in the log file<br>";
fclose ($fp);
?>
</p>
</body>
</html>
<end node> 5P9i0s8y19Z
dt=
<node>Permissions
2
$entry="myfile.php";
chmod( $entry, 0777 );
chmod( $entry, 0644 );
<end node> 5P9i0s8y19Z
dt=
<node>read directory
2
$imagedirectory="../banners/";
[Create image viewer]
<?php
$imagedirectory="../stylists/";
$dir = opendir($imagedirectory);
while ($file = readdir($dir)){
//for ($i=1; $i<=500; $i++){
// $file = readdir($dir);
$fullpath=$current_dir.$file;
/*
$filedate=date('Y-m-j', filemtime($fullpath));
if(trim($file)!='.' && trim($file)!='..'){
$fsize=filesize($fullpath)/1000;
$fsize=(int)$fsize;$fsize=$fsize/1000;
$message[]=$filedate."|".$file."@".$fsize;
}
*/
echo "<div style='float:left;padding:20px;'><img src='$fullpath'><br>$file</div>";
}
closedir($dir);
?>
=====================
$dir = opendir($imagedirectory);
while ($file = readdir($dir)){
if(strpos($file,".")!=0){
$file1.=chr(34).$file.chr(34).",";$file2.=chr(34).chr(34).",";
}
}
==================================================
while ($file = readdir($dir)){
//for ($i=1; $i<=500; $i++){
// $file = readdir($dir);
$fullpath=$current_dir.$file;
$filedate=date('Y-m-j', filemtime($fullpath));
if(trim($file)!='.' && trim($file)!='..'){
$fsize=filesize($fullpath)/1000;
$fsize=(int)$fsize;$fsize=$fsize/1000;
$message[]=$filedate."|".$file."@".$fsize;
}
}
closedir($dir);
<end node> 5P9i0s8y19Z
dt=
<node>updating html
2
<?php
session_start();
?>
<html><head>
<script language='JavaScript1.1'>
//Form variables on update
function checkform(){
var error = 0;
var error_message = 'Errors have occured during the process of your form!\nPlease make the following corrections:\n\n';
var TopicId = document.frmInput.TopicId.value;
var Topic = document.frmInput.Topic.value;
if (error == 1){
alert(error_message);
return false;
} else {
return true;
}
}
</script>
<!–L–><body><!–H–>
<?php
SWITCH($ACTION){
case 1:
$buffer=$_POST['hometext'];
$logFile = "homepage.txt";
// Open the file in write/read mode
$fp = fopen($logFile, "r+");
// Create a string containing the user details
// Write the user details to the file
fwrite($fp, $buffer);
// Move to the start of the file
//rewind($fp);
fclose($fp);
$logFile = "../index.html";
if (!($fp = fopen($logFile, "r+")))
exit("Unable to open the home page file.");
while (!feof($fp))
{
$buffer1 = fgets($fp, 1024);
if(strpos($buffer1,"Start Import Body")>0)break;
$totalfile.=$buffer1;
}
$buffer=str_replace(chr(13),'<p>',$buffer);$buffer="<p>".$buffer;
$buffer1.=$buffer."</table></body></html>";
fwrite($fp,$buffer1);
fclose($fp);
echo "<body onload=setTimeout(\"location.href='../index.html'\",2000)>";
echo 'You have Updated the Home Page. Please refresh the page if changes are not visible.';
break;
default:
$listFile = "homepage.txt";
if (!($fp = fopen($listFile, "r")))exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile));
fclose($fp);
//Print the Form up
$display = "Home Page Update
<form name='frmInput' method='post' action='HomeForm.php?ACTION=1' onSubmit='return checkform();'>
Description: <textarea name='hometext' rows=30, cols=75>".$buffer."</textarea><br>";
$display.="<input type='submit' value=' S A V E '></form>";
echo $display;
}
?>
</body></html>
<end node> 5P9i0s8y19Z
dt=
<node>upload
2
<?php # Script 11.7 – add_file.php
// This page allows users to upload files to the server.
// Set the page title and include the HTML header.
$page_title = 'Upload a File';
include ('includes/header.html');
if (isset($_POST['submit'])) { // Handle the form.
require_once ('../mysql_connect.php'); // Connect to the database.
// Function for escaping and trimming form data.
function escape_data ($data) {
global $dbc;
if (ini_get('magic_quotes_gpc')) {
$data = stripslashes($data);
}
return mysql_real_escape_string (trim ($data), $dbc);
} // End of escape_data() function.
// Check for a description (not required).
if (!empty($_POST['description'])) {
$d = escape_data($_POST['description']);
} else {
$d = '';
}
// Add the record to the database.
$query = "INSERT INTO uploads (file_name, file_size, file_type, description, upload_date) VALUES ('{$_FILES['upload']['name']}', {$_FILES['upload']['size']}, '{$_FILES['upload']['type']}', '$d', NOW())";
$result = @mysql_query ($query);
if ($result) {
// Create the file name.
$extension = explode ('.', $_FILES['upload']['name']);
$uid = mysql_insert_id(); // Upload ID
$filename = $uid . '.' . $extension[1];
// Move the file over.
if (move_uploaded_file($_FILES['upload']['tmp_name'], "../uploads/$filename")) {
echo '<p>The file has been uploaded!</p>';
} else {
echo '<p><font color="red">The file could not be moved.</font></p>';
// Remove the record from the database.
$query = "DELETE FROM uploads WHERE upload_id = $uid";
$result = @mysql_query ($query);
}
} else { // If the query did not run OK.
echo '<p><font color="red">Your submission could not be processed due to a system error. We apologize for any inconvenience.</font></p>';
}
mysql_close(); // Close the database connection.
} // End of the main Submit conditional.
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288">
<fieldset><legend>Fill out the form to upload a file:</legend>
<p><b>File:</b> <input type="file" name="upload" /></p>
<p><b>Description:</b> <textarea name="description" cols="40" rows="5"></textarea></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
</form><!– End of Form –>
<?php
include ('includes/footer.html'); // Include the HTML footer.
?>
<end node> 5P9i0s8y19Z
dt=
<node>formating
1
<?php
print "<table border=\"1\">\n";
for ( $y=1; $y<=12; $y++ ) {
print "<tr>\n";
for ( $x=1; $x<=12; $x++ ) {
print "\t<td>";
print ($x*$y);
print "</td>\n";
}
print "</tr>\n";
}
print "</table>";
?>
\" means embeded quote
\n breaks to new line
\t indents line
<end node> 5P9i0s8y19Z
dt=
<node>breaks
2
$outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t"
.$sparkqty." spark plugs\t\$".$total
."\t". $address."\n";
<end node> 5P9i0s8y19Z
dt=
<node>number
2
<?php
number_format (1234.567);
//Returns the number 1,235
number_format (1234.567, 2);
//Returns the number 1,234.57
number_format (1234.567, 2, ',', ' ');
//Returns the number 1 234,57
number_format (1234.567, 1, 'a', 'b');
//Returns the number 1b234a6
<end node> 5P9i0s8y19Z
dt=
<node>screenResolution
2
http://www.tainyan.com/tipstricks/entry-38/how-to-detect-the-screen-resolution-of-the-visitor-in-both-client-side-and-server-side.html
For client side, there is very simple way to get it by using javascript as javascript running in client's machine. But you cannot detect the client's resolution directly in server side as server side script running in server. So, you may ask, what you have to do if you need to know client's screen resolution in server side? That's easy. What you need to do is just communicate between client and server.
Detecting the client's screen resolution
use screen.width to get screen width use screen.height to get screen height
?12345678
function ShowScreenResolution(){ var w = screen.width; var h = screen.height; alert( "Your screen resolution is " + w + 'x' + h); }
——————————————————————————–
Server Side
In server side script, I check the session in page load whether width and height data exist or not. If not exist, I injected the JavaScript code to sent back the screen size when visitor load the page first time. Then I maintain the data in session. Following is JavaScript code to inject when page load. Put it within body tags of your page if width and height data does not exist in session value. Don't forget to omit the JavaScript code after you put data into session. Otherwise, your page will be refresh again and again.
?123 <script type="text/javascript"> location.replace('http://www.yourdomain.com/index.php?w=' + screen.width + '&h=' + screen.height ); </script>
Put data into session.
?12 $_SESSION['width'] = $_GET['w']; // store session data $_SESSION['height'] = $_GET['h']; // store session data
Check session whether you need to inject the JavaScript code or not.
?1234 if ($_SESSION['width']!=null){ //echo javascript-code; }
The best way to post back data is using Ajax. So user may not notice when the page refresh in first visit.
add_action('genesis_meta', 'add_head');
function add_head() {
if($_SESSION["WIDTH"]=="" && $_GET["W"]==""){
?>
<script>
alert("testing");
//location.href="/?W="+screen.width+"&H="+screen.height;
</script>
<?php
}
}
//add_action('genesis_before_post_content', 'include_page');
<end node> 5P9i0s8y19Z
dt=
<node>url
2
function MakeHyperlink($c){
if(strpos(strtolower($c),"href=")>0) return $c;
//$text = ereg_replace("[(www.)]+[^<>[:space:]]+[[:alnum:]/]","<A HREF='#' onclick=\"LoadPopup('http://\\0',800,800);\">\\0</a>", $c);
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<A HREF='#' onclick=\"LoadPopup('\\0',800,800);\">\\0</a>", $c);
if(strpos(strtolower($c),"mailto:")>0) return $text;
//$text = ereg_replace("[[:alpha:]]+@[^<>[:space:]]+[[:alnum:]/]","<A HREF='mailto:\\0'>\\0</a>", $text);
$text=ereg_replace('[A-Za-z0-9_]([-._]?[A-Za-z0-9])*@[A-Za-z0-9]([-.]?[A-Za-z0-9])*\.[A-Za-z]+','<a href="mailto:\\0?subject=Email%20from%20web%20site">\\0</a> ',$text);
return $text;
}
<end node> 5P9i0s8y19Z
dt=
<node>Forms
1
<form method=post name=upform action="/cgi-bin/some-script.cgi" enctype="multipart/form-data">
pass variables form
<form name='search' method='post' action='searchResults.php'
<FORM name="cquestionsform" action="submitcquestions1.php" method="post" onsubmit="if(checkAllFields()){return true;}else{return false;}">>
<end node> 5P9i0s8y19Z
dt=
<node>box sizes
2
size=16 maxlength=16
<end node> 5P9i0s8y19Z
dt=
<node>check boxes
2
Assign values to each check box name to save the result in a mysql database
<input type='checkbox' value='o_prop_tax' name='select[0]' checked>Property Taxes<br>
<input type='checkbox' value='o_insure' name='select[1]'>Insurance<br>
For detemining only check results such as file deletes.
<input type='checkbox' value='musica.mp3' name='select[]' checked>musica.mp3<br>
<input type='checkbox' value='musicb.mp3' name='select[]'>musicb.mp3<br>
if($fuel_sales=='on')$fuel_sales=1; // this box is checked
if($fuel_sales=='')$fuel_sales=0; // this box is unchecked
<?php
foreach($_POST['delfile'] as $value) {
unlink('../message/'.$value);
echo "<BR>You deleted file " . $value , "\n";
}
?>
********************************************************
foreach($_POST['delfile'] as $value) {
unlink($PA.$value);//unlink('../html/message/'.$value);
echo "<BR>You deleted file ".$PA . $value , "\n";
}
<end node> 5P9i0s8y19Z
dt=
<node>process file
3
foreach($_POST['delfile'] as $value) {
unlink($PA.$value);//unlink('../html/message/'.$value);
echo "<BR>You deleted file ".$PA . $value , "\n";
}
——
<end node> 5P9i0s8y19Z
dt=
<node>combo
2
<form name='searchcategory' method='post' action='bizdir.php?REPLY=1'>";
$query="SELECT * FROM category ORDER BY category";
$result=mysql_query($query);
if (!result){
echo "$query is deffective";
}
$dis.= "<select name='categoryid' size='1'><option value=0>All\n";
$num=mysql_num_rows($result);
For ($i=0; $i<$num; $i++){
$row=mysql_fetch_array($result);
$categoryid=$row['categoryid'];
$category=$row['category'];
if ($categoryid == $STID){
$dis.= "<option selected value=$categoryid>$category\n";
}
else{
$dis.= "<option value=$categoryid>$category\n";
}
}
$dis.= "</select>";
<end node> 5P9i0s8y19Z
dt=
<node>For
2
<?php
$counter = -4;
for ( ; $counter <= 10; $counter++ ) {
if ( $counter == 0 )
continue;
$temp = 4000/$counter;
print "4000 divided by $counter is… $temp<br>";
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>Pass Code
2
<?php
$seed=strtotime(date('Y-m-d h:i:sa'));srand($seed);$imagevalue="";
for($i=1;$i<=5;$i++){
$imgvalue.=chr(rand(64,91));
}
$HTTP_SESSION_VARS['PASSCODE']=$imgvalue;
echo "(required) Enter the Displayed Security Code:<IMG SRC='button.php?s=16'>"; //<?php echo $imgvalue;
?>
==============================================
button.php
<?php
session_start();
Header("Content-type: image/gif");
$text=$HTTP_SESSION_VARS['PASSCODE'];
if(!isset($s)) $s=11;
$size = imagettfbbox($s,0,"font/calligra.ttf",$text);
$dx = abs($size[2]-$size[0]);
$dy = abs($size[5]-$size[3]);
$xpad=9;
$ypad=9;
$im = imagecreate($dx+$xpad,$dy+$ypad);
$blue = ImageColorAllocate($im, 0x2c,0x6D,0xAF);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
ImageRectangle($im,0,0,$dx+$xpad-1,$dy+$ypad-1,$black);
ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,$white);
ImageTTFText($im, $s, 0, (int)($xpad/2)+1, $dy+(int)($ypad/2), $black, "font/calligra.ttf", $text);
ImageTTFText($im, $s, 0, (int)($xpad/2), $dy+(int)($ypad/2)-1, $white, "font/calligra.ttf", $text);
ImageGif($im);
ImageDestroy($im);
?>
<end node> 5P9i0s8y19Z
dt=
<node>radio Buttons
2
Type:<Input type='radio' name='filetype' value='html' checked>HTML <Input type='radio' name='filetype' value='text'>TEXT<br>
===============
switch($_POST["radiobutton"]) //we set the switch on the type radio which we create in the html file
{
case "teacher":
$val="teacher"; // if we pick the 'teacher' then the value will be get this parameter
break;
case "doctor":
$val="doctor"; // if we pick the 'doctor' then the value will be get this parameter
break;
case "engineer":
$val="engineer";
// if we pick the 'engineer' then the value will be get this parameter
default:
$val="teacher";
}
echo "the option u have pick is ".$val;
?>
======= FORM ==========
$b='';if($sign==1)$b='checked';
$display.="<tr><td><td><Input type='radio' name='sign' value='1' $b> Window Sign<br>";
$b='';if($sign==2)$b='checked';
$display.="<Input type='radio' name='sign' value='2' $b>Lot Sign<br>
<end node> 5P9i0s8y19Z
dt=
<node>submit
2
Give Nmaes to buttons:
<input type="submit" name="del_ip" value="del" />
<input type="submit" name="get_host" value="host" />
Or you could do a switch
if($_POST){
switch($_POST['Submit']){
case "First Button":
Run Code;
break;
case "Second Button":
Run Code
break;
case "Third Button:
Run Code;
break;
default:
echo "ERROR form not posted properly"
break;
}
}
One method I tend to use when I have a form that has 3 buttons, like
update, insert or delete.
> if($firstoption) {
> //perform action for first form button
> } else if($secondoption) {
> //perform action for second form button
> } else {
> //error
> }
[IMAGE KIND]
<INPUT TYPE="image" SRC="images/submit.gif" HEIGHT="30" WIDTH="173" BORDER="0" ALT="Submit Form">
<end node> 5P9i0s8y19Z
dt=
<node>Text Area
2
<textarea name='history' rows=20, cols=75>blah blah</textarea>
<end node> 5P9i0s8y19Z
dt=
<node>graphics
1
<?php
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
============
Save the above file as SimpleImage.php and take a look at the following examples of how to use the script.
The first example below will load a file named picture.jpg resize it to 250 pixels wide and 400 pixels high and resave it as picture2.jpg
<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resize(250,400);
$image->save('picture2.jpg');
?>
If you want to resize to a specifed width but keep the dimensions ratio the same then the script can work out the required height for you, just use the resizeToWidth function.
<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(250);
$image->save('picture2.jpg');
?>
You may wish to scale an image to a specified percentage like the following which will resize the image to 50% of its original width and height
<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->scale(50);
$image->save('picture2.jpg');
?>
You can of course do more than one thing at once. The following example will create two new images with heights of 200 pixels and 500 pixels
<?php
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToHeight(500);
$image->save('picture2.jpg');
$image->resizeToHeight(200);
$image->save('picture3.jpg');
?>
The output function lets you output the image straight to the browser without having to save the file. Its useful for on the fly thumbnail generation
<?php
header('Content-Type: image/jpeg');
include('SimpleImage.php');
$image = new SimpleImage();
$image->load('picture.jpg');
$image->resizeToWidth(150);
$image->output();
?>
The following example will resize and save an image which has been uploaded via a form
<?php
if( isset($_POST['submit']) ) {
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($_FILES['uploaded_image']['tmp_name']);
$image->resizeToWidth(150);
$image->output();
} else {
?> <form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_image" />
<input type="submit" name="submit" value="Upload" />
</form><?php
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>Create Button
2
<?php
session_start();
session_register('sessioncode');
//Header("Content-type: image/jpeg");
//echo "beg test";
$filename = "images/image1.gif";
$im = imagecreate(55, 15);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 100, 100, 100);
imagecolortransparent($im, $bg);
//imagestring($im, 5, 0, 0, substr(strtoupper(md5("Myshit".$sessioncode)), 0,6), $textcolor);
imagestring($im, 5, 0, 0, substr(strtoupper("Myshit"), 0,6), $textcolor);
imageGif($im,$filename);
ImageDestroy($im);
//***************************************************************
$filename = "images/image.gif";
$img = ImageCreate(200,20);
$red = ImageColorAllocate($img, 255, 0, 0); $white = ImageColorAllocate($img, 255, 255, 255);
ImageString($img, 3, 3, 3, "Uh, this is an image!", $white); ImageGif($img, $filename);
ImageDestroy($img);
echo "<img src='images/image1.gif'><img src='images/image.gif'>";
echo "Finished";
exit();
?>
<end node> 5P9i0s8y19Z
dt=
<node>font
3
$im = imagecreate(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
// The text to draw
$text = 'Testing…';
// Replace path by your own font path
$font = 'arial.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
*************************************
The below script would be called with a tag like this from a page: <IMG SRC="button.php3?s=36&text=PHP+is+Cool">
<?php
Header("Content-type: image/gif");
if(!isset($s)) $s=11;
$size = imagettfbbox($s,0,"/fonts/TIMES.TTF",$text);
$dx = abs($size[2]-$size[0]);
$dy = abs($size[5]-$size[3]);
$xpad=9;
$ypad=9;
$im = imagecreate($dx+$xpad,$dy+$ypad);
$blue = ImageColorAllocate($im, 0x2c,0x6D,0xAF);
$black = ImageColorAllocate($im, 0,0,0);
$white = ImageColorAllocate($im, 255,255,255);
ImageRectangle($im,0,0,$dx+$xpad-1,$dy+$ypad-1,$black);
ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,$white);
ImageTTFText($im, $s, 0, (int)($xpad/2)+1, $dy+(int)($ypad/2), $black, "/fonts/TIMES.TTF", $text);
ImageTTFText($im, $s, 0, (int)($xpad/2), $dy+(int)($ypad/2)-1, $white, "/fonts/TIMES.TTF", $text);
ImageGif($im);
ImageDestroy($im);
?>
It is very important to realize that you cannot put any HTML tags in this file. There should also not be any spaces or blank lines before or after the <? and ?> tags. If you are getting a broken image using this script, chances are you have a stray carriage return somewhere outside the PHP tags
<end node> 5P9i0s8y19Z
dt=
<node>header
1
header("target: _self");
header("Location: http://www.citywidecourier.com");
/*
if($_GET['action'] == "save") // This uses a variable value to write to file.
{
ob_clean();
ob_start();
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=$backupFile");
echo $result;
ob_end_flush();
exit;
}
else
{
echo "<textarea readonly rows=40 cols=100>$result</textarea><br>";
echo "<a href=\"db_backup.php?action=save\">save</a>";
}
*/
<end node> 5P9i0s8y19Z
dt=
<node>download
2
<?php
$filename = "theDownloadedFileIsCalledThis.mp3";
$myFile = "/absolute/path/to/my/file.mp3";
$mm_type="application/octet-stream";
header("Cache-Control: public, must-revalidate");
header("Pragma: hack"); // WTF? oh well, it works…
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($myFile)) );
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary\n");
readfile($myFile);
?>
<end node> 5P9i0s8y19Z
dt=
<node>redirect
2
$host = $_SERVER["HTTP_HOST"];
switch ($host) {
case "www.wolterfamily.org":
header("Location:http://build-a-site.com/wolter/index.php"); exit();
case "wolterfamily.org":
header("Location:http://build-a-site.com/wolter/index.php"); exit();
case "sellhay.com":
header("Location:build-a-site/sellhay/index.php"); exit();
case "www.sellhay.com":
header("Location:build-a-site/sellhay/index.php"); exit();
}
=========================================
header("Location: shop_checkout.php");
<end node> 5P9i0s8y19Z
dt=
<node>LANGUAGE
1
<end node> 5P9i0s8y19Z
dt=
<node>case – switch
2
<?php
$mood = "sad";
switch ( $mood ) {
case "happy":
print "Hooray, I'm in a good mood";
break;
case "sad":
print "Awww. Don't be down!";
break;
default:
print "Neither happy nor sad but $mood";
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>DATE
2
<?php
date_default_timezone_set('America/Denver');
$script_tz = date_default_timezone_get();
if (strcmp($script_tz, ini_get('date.timezone'))){
echo 'Script timezone differs from ini-set timezone.';
} else {
echo 'Script timezone and ini-set timezone match.';
}
?>
Really should be set in the php.ini file in this section of code:
Code:
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = "America/Los_Angeles"
; http://php.net/date.default-latitude
date.default_latitude = 34.3981
; http://php.net/date.default-longitude
date.default_longitude = 118.1358
; http://php.net/date.sunrise-zenith
;date.sunrise_zenith = 90.583333
; http://php.net/date.sunset-zenith
;date.sunset_zenith = 90.583333
Turning display errors off would also eliminate the problem. They aren't errors, simply warnings. They are due to how PHP has changed over the years. Previous to vBulletin 4.2.2, they were suppressed because vBulletin didn't know how to deal with them.
<end node> 5P9i0s8y19Z
dt=
<node>explode/implode
2
$w=explode('|',$mon);
<end node> 5P9i0s8y19Z
dt=
<node>for
2
for ($i=1; $i<=strlen($str); $i++)
{
echo substr($str, -$i, 1);
}
<end node> 5P9i0s8y19Z
dt=
<node>foreach
2
if($_POST['updatecart']==" UPDATE ORDER "){
$total=$_POST['PRI']; $pronum=$_POST['PRO'];$delivery=$_POST['DEL'];$ur=$_POST['UR'];$shipping=$_POST['SHI'];
foreach($_POST['QUA'] as $k=>$value) {
//if($pronum[$k]!="")$lastvalue=$pronum[$k];
//if($shipping[$k]=="")$shipping[$k]==""
$sql="UPDATE orderquantity SET prodquantity=".stripcomma($value).",unitprice=".stripcomma($total[$k]).",shipping='".$shipping[$k]."',pronumber='".
$pronum[$k]."',deliverydate='".convertdate($delivery[$k])."',urlid=".$ur[$k]." WHERE quantityid=$k";
dbq($sql,$tmp=0,1);
}
if(count($_POST['List'])==0) echo "<h4>Nothing has been Deleted. </h4>";
<end node> 5P9i0s8y19Z
dt=
<node>function
2
Passing arguments by reference ¶
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition:
Example #2 Passing function parameters by reference
<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
function reverse_i($str)
global $a, $b, $c;
{
for ($i=1; $i<=strlen($str); $i++)
{
echo substr($str, -$i, 1);
}
return;
}
<end node> 5P9i0s8y19Z
dt=
<node>headers sent
2
if (!headers_sent()) {
header('Location: http://www.example.com/');
exit;
}
// An example using the optional file and line parameters, as of PHP 4.3.0
// Note that $filename and $linenum are passed in for later use.
// Do not assign them values beforehand.
if (!headers_sent($filename, $linenum)) {
header('Location: http://www.example.com/');
exit;
// You would most likely trigger an error here.
} else {
echo "Headers already sent in $filename on line $linenum\n" .
"Cannot redirect, for now please click this <a " .
"href=\"http://www.example.com\">link</a> instead\n";
exit;
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>htmlspecial
2
[htmlspecialchars]
<input type="text" name="idtest" value="<?php echo htmlspecialchars($name); ?>" />
<end node> 5P9i0s8y19Z
dt=
<node>json_encode
2
[ENCODE]
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
[DECODE]
Example #1 json_decode() examples
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
USING COOKIES USE STRIPSLASHES
$array=json_decode(stripslashes($_COOKIE["MYORDER"]), true);
<end node> 5P9i0s8y19Z
dt=
<node>number
2
[exponent]
pow(5, 3)
[integer]
(int)
<end node> 5P9i0s8y19Z
dt=
<node>parse_url
2
parse_url
(PHP 4, PHP 5)
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
parse_url – Parse a URL and return its components
Specify one of PHP_URL_SCHEME, PHP_URL_HOST, PHP_URL_PORT, PHP_URL_USER, PHP_URL_PASS, PHP_URL_PATH, PHP_URL_QUERY or PHP_URL_FRAGMENT to retrieve just a specific URL component as a string (except when PHP_URL_PORT is given, in which case the return value will be an integer).
Return Values ¶
$url = 'http://google.com/dhasjkdas/sadsdds/sdda/sdads.html';
$parse = parse_url($url);
print $parse['host']; // prints 'google.com'
<end node> 5P9i0s8y19Z
dt=
<node>pregi
2
$priceid=preg_replace('/[^0-9.\-]/','',$priceid);
$pattern="(.jpg|.gif|.png)";
if (eregi($pattern,strtolower($val2))==true){
$dimen=sizepicture($PA."/".$val2);
echo $val2."<img src='".$PA."/".$val2."' height=".$dimen[1]." width=".$dimen[0]." align='right'><td valign='top'>".$val1;
}else echo $val2."<td valign='top'>".$val1;
<end node> 5P9i0s8y19Z
dt=
<node>random number
2
srand
int rand ([ int $min ], int $max )
If called without the optional min , max arguments rand() returns a pseudo-random integer between 0 and RAND_MAX. If you want a random number between 5 and 15 (inclusive), for example, use rand (5, 15).
Note: On some platforms (such as Windows) RAND_MAX is only 32768. If you require a range larger than 32768, specifying min and max will allow you to create a range larger than RAND_MAX, or consider using mt_rand() instead.
Note: As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is now done automatically.
Parameters
min
The lowest value to return (default: 0)
max
The highest value to return (default: RAND_MAX)
<end node> 5P9i0s8y19Z
dt=
<node>rtrim
2
You need to add the end of line anchor:
$string = preg_replace('/\n$/','',$string);
Its better to avoid regex for such a simple substitution. This can easily be done using rtrim as:
$string = rtrim($string);
rtrim without 2nd argument will remove the trailing whitespace char which include:
•newline
•space
•vertical tab
•horizontal tab
•carriage return
shareimprove this answer
<end node> 5P9i0s8y19Z
dt=
<node>while
2
<?php
$counter = 1;
while ( $counter <= 12 ) {
print "$counter times 2 is ".($counter*2)."<br>";
$counter++;
}
?>
<end node> 5P9i0s8y19Z
dt=
<node>php.ini
1
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
upload_max_filesize = 20M
[PHP]
;;;;;;;;;;;
; WARNING ;
;;;;;;;;;;;
; This is the default settings file for new PHP installations.
; By default, PHP installs itself with a configuration suitable for
; development purposes, and *NOT* for production purposes.
; For several security-oriented considerations that should be taken
; before going online with your site, please consult php.ini-recommended
; and http://php.net/manual/en/security.php.
;;;;;;;;;;;;;;;;;;;
; About this file ;
;;;;;;;;;;;;;;;;;;;
; This file controls many aspects of PHP's behavior. In order for PHP to
; read it, it must be named 'php.ini'. PHP looks for it in the current
; working directory, in the path designated by the environment variable
; PHPRC, and in the path that was defined in compile time (in that order).
; Under Windows, the compile-time path is the Windows directory. The
; path in which the php.ini file is looked for can be overridden using
; the -c argument in command line mode.
;
; The syntax of the file is extremely simple. Whitespace and Lines
; beginning with a semicolon are silently ignored (as you probably guessed).
; Section headers (e.g. [Foo]) are also silently ignored, even though
; they might mean something in the future.
;
; Directives are specified using the following syntax:
; directive = value
; Directive names are *case sensitive* – foo=bar is different from FOO=bar.
;
; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one
; of the INI constants (On, Off, True, False, Yes, No and None) or an expression
; (e.g. E_ALL & ~E_NOTICE), or a quoted string ("foo").
;
; Expressions in the INI file are limited to bitwise operators and parentheses:
; | bitwise OR
; & bitwise AND
; ~ bitwise NOT
; ! boolean NOT
;
; Boolean flags can be turned on using the values 1, On, True or Yes.
; They can be turned off using the values 0, Off, False or No.
;
; An empty string can be denoted by simply not writing anything after the equal
; sign, or by using the None keyword:
;
; foo = ; sets foo to an empty string
; foo = none ; sets foo to an empty string
; foo = "none" ; sets foo to the string 'none'
;
; If you use constants in your value, and these constants belong to a
; dynamically loaded extension (either a PHP extension or a Zend extension),
; you may only use these constants *after* the line that loads the extension.
;
; All the values in the php.ini-dist file correspond to the builtin
; defaults (that is, if no php.ini is used, or if you delete these lines,
; the builtin defaults will be identical).
;;;;;;;;;;;;;;;;;;;;
; Language Options ;
;;;;;;;;;;;;;;;;;;;;
; Enable the PHP scripting language engine under Apache.
engine = On
; Allow the <? tag. Otherwise, only <?php and <script> tags are recognized.
; NOTE: Using short tags should be avoided when developing applications or
; libraries that are meant for redistribution, or deployment on PHP
; servers which are not under your control, because short tags may not
; be supported on the target server. For portable, redistributable code,
; be sure not to use short tags.
short_open_tag = On
; Allow ASP-style <% %> tags.
asp_tags = Off
; The number of significant digits displayed in floating point numbers.
precision = 12
; Enforce year 2000 compliance (will cause problems with non-compliant browsers)
y2k_compliance = On
; Output buffering allows you to send header lines (including cookies) even
; after you send body content, at the price of slowing PHP's output layer a
; bit. You can enable output buffering during runtime by calling the output
; buffering functions. You can also enable output buffering for all files by
; setting this directive to On. If you wish to limit the size of the buffer
; to a certain size – you can use a maximum number of bytes instead of 'On', as
; a value for this directive (e.g., output_buffering=4096).
output_buffering = Off
; You can redirect all of the output of your scripts to a function. For
; example, if you set output_handler to "mb_output_handler", character
; encoding will be transparently converted to the specified encoding.
; Setting any output handler automatically turns on output buffering.
; Note: People who wrote portable scripts should not depend on this ini
; directive. Instead, explicitly set the output handler using ob_start().
; Using this ini directive may cause problems unless you know what script
; is doing.
; Note: You cannot use both "mb_output_handler" with "ob_iconv_handler"
; and you cannot use both "ob_gzhandler" and "zlib.output_compression".
;output_handler =
; Transparent output compression using the zlib library
; Valid values for this option are 'off', 'on', or a specific buffer size
; to be used for compression (default is 4KB)
; Note: Resulting chunk size may vary due to nature of compression. PHP
; outputs chunks that are few hundreds bytes each as a result of
; compression. If you prefer a larger chunk size for better
; performance, enable output_buffering in addition.
; Note: You need to use zlib.output_handler instead of the standard
; output_handler, or otherwise the output will be corrupted.
zlib.output_compression = Off
; You cannot specify additional output handlers if zlib.output_compression
; is activated here. This setting does the same as output_handler but in
; a different order.
;zlib.output_handler =
; Implicit flush tells PHP to tell the output layer to flush itself
; automatically after every output block. This is equivalent to calling the
; PHP function flush() after each and every call to print() or echo() and each
; and every HTML block. Turning this option on has serious performance
; implications and is generally recommended for debugging purposes only.
implicit_flush = Off
; The unserialize callback function will be called (with the undefined class'
; name as parameter), if the unserializer finds an undefined class
; which should be instanciated.
; A warning appears if the specified function is not defined, or if the
; function doesn't include/implement the missing class.
; So only set this entry, if you really want to implement such a
; callback-function.
unserialize_callback_func=
; When floats & doubles are serialized store serialize_precision significant
; digits after the floating point. The default value ensures that when floats
; are decoded with unserialize, the data will remain the same.
serialize_precision = 100
; Whether to enable the ability to force arguments to be passed by reference
; at function call time. This method is deprecated and is likely to be
; unsupported in future versions of PHP/Zend. The encouraged method of
; specifying which arguments should be passed by reference is in the function
; declaration. You're encouraged to try and turn this option Off and make
; sure your scripts work properly with it in order to ensure they will work
; with future versions of the language (you will receive a warning each time
; you use this feature, and the argument will be passed by value instead of by
; reference).
allow_call_time_pass_reference = On
; Safe Mode
;
safe_mode = Off
; By default, Safe Mode does a UID compare check when
; opening files. If you want to relax this to a GID compare,
; then turn on safe_mode_gid.
safe_mode_gid = Off
; When safe_mode is on, UID/GID checks are bypassed when
; including files from this directory and its subdirectories.
; (directory must also be in include_path or full path must
; be used when including)
safe_mode_include_dir =
; When safe_mode is on, only executables located in the safe_mode_exec_dir
; will be allowed to be executed via the exec family of functions.
safe_mode_exec_dir =
; Setting certain environment variables may be a potential security breach.
; This directive contains a comma-delimited list of prefixes. In Safe Mode,
; the user may only alter environment variables whose names begin with the
; prefixes supplied here. By default, users will only be able to set
; environment variables that begin with PHP_ (e.g. PHP_FOO=BAR).
;
; Note: If this directive is empty, PHP will let the user modify ANY
; environment variable!
safe_mode_allowed_env_vars = PHP_
; This directive contains a comma-delimited list of environment variables that
; the end user won't be able to change using putenv(). These variables will be
; protected even if safe_mode_allowed_env_vars is set to allow to change them.
safe_mode_protected_env_vars = LD_LIBRARY_PATH
; open_basedir, if set, limits all file operations to the defined directory
; and below. This directive makes most sense if used in a per-directory
; or per-virtualhost web server configuration file. This directive is
; *NOT* affected by whether Safe Mode is turned On or Off.
;open_basedir =
; This directive allows you to disable certain functions for security reasons.
; It receives a comma-delimited list of function names. This directive is
; *NOT* affected by whether Safe Mode is turned On or Off.
disable_functions =
; This directive allows you to disable certain classes for security reasons.
; It receives a comma-delimited list of class names. This directive is
; *NOT* affected by whether Safe Mode is turned On or Off.
disable_classes =
; Colors for Syntax Highlighting mode. Anything that's acceptable in
; <font color="??????"> would work.
;highlight.string = #DD0000
;highlight.comment = #FF9900
;highlight.keyword = #007700
;highlight.bg = #FFFFFF
;highlight.default = #0000BB
;highlight.html = #000000
;
; Misc
;
; Decides whether PHP may expose the fact that it is installed on the server
; (e.g. by adding its signature to the Web server header). It is no security
; threat in any way, but it makes it possible to determine whether you use PHP
; on your server or not.
expose_php = On
;;;;;;;;;;;;;;;;;;;
; Resource Limits ;
;;;;;;;;;;;;;;;;;;;
max_execution_time = 30 ; Maximum execution time of each script, in seconds
max_input_time = 60 ; Maximum amount of time each script may spend parsing request data
memory_limit = 32M ; Maximum amount of memory a script may consume (32MB)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; error_reporting is a bit-field. Or each number up to get desired error
; reporting level
; E_ALL – All errors and warnings
; E_ERROR – fatal run-time errors
; E_WARNING – run-time warnings (non-fatal errors)
; E_PARSE – compile-time parse errors
; E_NOTICE – run-time notices (these are warnings which often result
; from a bug in your code, but it's possible that it was
; intentional (e.g., using an uninitialized variable and
; relying on the fact it's automatically initialized to an
; empty string)
; E_CORE_ERROR – fatal errors that occur during PHP's initial startup
; E_CORE_WARNING – warnings (non-fatal errors) that occur during PHP's
; initial startup
; E_COMPILE_ERROR – fatal compile-time errors
; E_COMPILE_WARNING – compile-time warnings (non-fatal errors)
; E_USER_ERROR – user-generated error message
; E_USER_WARNING – user-generated warning message
; E_USER_NOTICE – user-generated notice message
;
; 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
; Print out errors (as a part of the output). For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below). Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On
; Even when display_errors is on, errors that occur during PHP's startup
; sequence are not displayed. It's strongly recommended to keep
; display_startup_errors off, except for when debugging.
display_startup_errors = Off
; Log errors into a log file (server-specific log, stderr, or error_log (below))
; As stated above, you're strongly advised to use error logging in place of
; error displaying on production web sites.
log_errors = On
; Set maximum length of log_errors. In error_log information about the source is
; added. The default is 1024 and 0 allows to not apply any maximum length at all.
;log_errors = On;
; Do not log repeated messages. Repeated errors must occur in same file on same
; line until ignore_repeated_source is set true.
ignore_repeated_errors = Off
; Ignore source of message when ignoring repeated messages. When this setting
; is On you will not log errors with repeated messages from different files or
; sourcelines.
ignore_repeated_source = Off
; If this parameter is set to Off, then memory leaks will not be shown (on
; stdout or in the log). This has only effect in a debug compile, and if
; error reporting includes E_WARNING in the allowed list
report_memleaks = On
; Store the last error/warning message in $php_errormsg (boolean).
track_errors = Off
; Disable the inclusion of HTML tags in error messages.
;html_errors = Off
; If html_errors is set On PHP produces clickable error messages that direct
; to a page describing the error or function causing the error in detail.
; You can download a copy of the PHP manual from http://www.php.net/docs.php
; and change docref_root to the base URL of your local copy including the
; leading '/'. You must also specify the file extension being used including
; the dot.
;docref_root = "/phpmanual/"
;docref_ext = .html
; String to output before an error message.
;error_prepend_string = "<font color=ff0000>"
; String to output after an error message.
;error_append_string = "</font>"
; Log errors to specified file.
error_log = error_log
; Log errors to syslog (Event Log on NT, not valid in Windows 95).
;error_log = error_log;
;;;;;;;;;;;;;;;;;
; Data Handling ;
;;;;;;;;;;;;;;;;;
;
; Note – track_vars is ALWAYS enabled as of PHP 4.0.3
; The separator used in PHP generated URLs to separate arguments.
; Default is "&".
;arg_separator.output = "&"
; List of separator(s) used by PHP to parse input URLs into variables.
; Default is "&".
; NOTE: Every character in this directive is considered as separator!
;arg_separator.input = ";&"
; This directive describes the order in which PHP registers GET, POST, Cookie,
; Environment and Built-in variables (G, P, C, E & S respectively, often
; referred to as EGPCS or GPC). Registration is done from left to right, newer
; values override older values.
variables_order = "EGPCS"
; Whether or not to register the EGPCS variables as global variables. You may
; want to turn this off if you don't want to clutter your scripts' global scope
; with user data. This makes most sense when coupled with track_vars – in which
; case you can access all of the GPC variables through the $HTTP_*_VARS[],
; variables.
;
; You should do your best to write your scripts so that they do not require
; register_globals to be on; Using form variables as globals can easily lead
; to possible security problems, if the code is not very well thought of.
register_globals = Off
; This directive tells PHP whether to declare the argv&argc variables (that
; would contain the GET information). If you don't use these variables, you
; should turn it off for increased performance.
register_argc_argv = On
; Maximum size of POST data that PHP will accept.
post_max_size = 8M
; This directive is deprecated. Use variables_order instead.
gpc_order = "GPC"
; Magic quotes
;
; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = On
; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off
; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off
; Automatically add files before or after any PHP document.
auto_prepend_file =
auto_append_file =
; As of 4.0b4, PHP always outputs a character encoding by default in
; the Content-type: header. To disable sending of the charset, simply
; set it to be empty.
;
; PHP's built-in default is text/html
default_mimetype = "text/html"
;default_charset = "iso-8859-1"
; Always populate the $HTTP_RAW_POST_DATA variable.
;always_populate_raw_post_data = On
;;;;;;;;;;;;;;;;;;;;;;;;;
; Paths and Directories ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; UNIX: "/path1:/path2"
include_path = ".:/usr/lib/php:/usr/local/lib/php"
;
; Windows: "\path1;\path2"
;;include_path = ".;c:\php\includes"
; The root of the PHP pages, used only if nonempty.
; if PHP was not compiled with FORCE_REDIRECT, you SHOULD set doc_root
; if you are running php as a CGI under any web server (other than IIS)
; see documentation for security issues. The alternate is to use the
; cgi.force_redirect configuration below
doc_root =
; The directory under which PHP opens the script using /~username used only
; if nonempty.
user_dir =
; Directory in which the loadable extensions (modules) reside.
extension_dir = "/usr/local/lib/php/extensions/no-debug-zts-20060613"
; Whether or not to enable the dl() function. The dl() function does NOT work
; properly in multithreaded servers, such as IIS or Zeus, and is automatically
; disabled on them.
enable_dl = On
; cgi.force_redirect is necessary to provide security running PHP as a CGI under
; most web servers. Left undefined, PHP turns this on by default. You can
; turn it off here AT YOUR OWN RISK
; **You CAN safely turn this off for IIS, in fact, you MUST.**
; cgi.force_redirect = 1
; if cgi.nph is enabled it will force cgi to always sent Status: 200 with
; every request.
; cgi.nph = 1
; if cgi.force_redirect is turned on, and you are not running under Apache or Netscape
; (iPlanet) web servers, you MAY need to set an environment variable name that PHP
; will look for to know it is OK to continue execution. Setting this variable MAY
; cause security issues, KNOW WHAT YOU ARE DOING FIRST.
; cgi.redirect_status_env = ;
; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting
; this to 1 will cause PHP CGI to fix it's paths to conform to the spec. A setting
; of zero causes PHP to behave as before. Default is zero. You should fix your scripts
; to use SCRIPT_FILENAME rather than PATH_TRANSLATED.
; cgi.fix_pathinfo=0
; FastCGI under IIS (on WINNT based OS) supports the ability to impersonate
; security tokens of the calling client. This allows IIS to define the
; security context that the request runs under. mod_fastcgi under Apache
; does not currently support this feature (03/17/2002)
; Set to 1 if running under IIS. Default is zero.
; fastcgi.impersonate = 1;
; cgi.rfc2616_headers configuration option tells PHP what type of headers to
; use when sending HTTP response code. If it's set 0 PHP sends Status: header that
; is supported by Apache. When this option is set to 1 PHP will send
; RFC2616 compliant header.
; Default is zero.
;cgi.rfc2616_headers = 0
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
; Whether to allow HTTP file uploads.
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
;upload_tmp_dir =
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
;;;;;;;;;;;;;;;;;;
; Fopen wrappers ;
;;;;;;;;;;;;;;;;;;
; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
allow_url_fopen = On
allow_url_include = On
; Define the anonymous ftp password (your email address)
;from="john@doe.com"
; Define the User-Agent string
; user_agent="PHP"
; Default timeout for socket based streams (seconds)
default_socket_timeout = 60
; If your scripts have to deal with files from Macintosh systems,
; or you are running on a Mac and need to deal with files from
; unix or win32 systems, setting this flag will cause PHP to
; automatically detect the EOL character in those files so that
; fgets() and file() will work regardless of the source of the file.
; auto_detect_line_endings = Off
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
;
; If you wish to have an extension loaded automatically, use the following
; syntax:
;
; extension=modulename.extension
;
; For example, on Windows:
;
; extension=msql.dll
;
; … or under UNIX:
;
; extension=msql.so
;
; Note that it should be the name of the module only; no directory information
; needs to go here. Specify the location of the extension with the
; extension_dir directive above.
;Windows Extensions
;Note that MySQL and ODBC support is now built in, so no dll is needed for it.
;
;extension=php_bz2.dll
;extension=php_cpdf.dll
;extension=php_crack.dll
;extension=php_curl.dll
;extension=php_db.dll
;extension=php_dba.dll
;extension=php_dbase.dll
;extension=php_dbx.dll
;extension=php_domxml.dll
;extension=php_exif.dll
;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_hyperwave.dll
;extension=php_iconv.dll
;extension=php_ifx.dll
;extension=php_iisfunc.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_java.dll
;extension=php_ldap.dll
;extension=php_mbstring.dll
;extension=php_mcrypt.dll
;extension=php_mhash.dll
;extension=php_mime_magic.dll
;extension=php_ming.dll
;extension=php_mssql.dll
;extension=php_msql.dll
;extension=php_oci8.dll
;extension=php_openssl.dll
;extension=php_oracle.dll
;extension=php_pdf.dll
;extension=php_pgsql.dll
;extension=php_printer.dll
;extension=php_shmop.dll
;extension=php_snmp.dll
;extension=php_sockets.dll
;extension=php_sybase_ct.dll
;extension=php_w32api.dll
;extension=php_xmlrpc.dll
;extension=php_xslt.dll
;extension=php_yaz.dll
;extension=php_zip.dll
;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;
[Syslog]
; Whether or not to define the various syslog variables (e.g. $LOG_PID,
; $LOG_CRON, etc.). Turning it off is a good idea performance-wise. In
; runtime, you can define these variables by calling define_syslog_variables().
define_syslog_variables = Off
[mail function]
; For Win32 only.
;SMTP = localhost
smtp_port = 25
; For Win32 only.
sendmail_from = steve@softwarewebdesign.com
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "/usr/sbin/sendmail -t -i"
[Java]
;java.class.path = .\php_java.jar
;java.home = c:\jdk
;java.library = c:\jdk\jre\bin\hotspot\jvm.dll
;java.library.path = .\
[SQL]
sql.safe_mode = Off
[ODBC]
;odbc.default_db = Not yet implemented
;odbc.default_user = Not yet implemented
;odbc.default_pw = Not yet implemented
; Allow or prevent persistent links.
odbc.allow_persistent = On
; Check that a connection is still valid before reuse.
odbc.check_persistent = On
; Maximum number of persistent links. -1 means no limit.
odbc.max_persistent = -1
; Maximum number of links (persistent + non-persistent). -1 means no limit.
odbc.max_links = -1
; Handling of LONG fields. Returns number of bytes to variables. 0 means
; passthru.
odbc.defaultlrl = 4096
; Handling of binary data. 0 means passthru, 1 return as is, 2 convert to char.
; See the documentation on odbc_binmode and odbc_longreadlen for an explanation
; of uodbc.defaultlrl and uodbc.defaultbinmode
odbc.defaultbinmode = 1
[MySQL]
; Allow or prevent persistent links.
mysql.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
mysql.max_persistent = -1
; Maximum number of links (persistent + non-persistent). -1 means no limit.
mysql.max_links = -1
; Default port number for mysql_connect(). If unset, mysql_connect() will use
; the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services or the
; compile-time value defined MYSQL_PORT (in that order). Win32 will only look
; at MYSQL_PORT.
mysql.default_port =
; Default socket name for local MySQL connects. If empty, uses the built-in
; MySQL defaults.
mysql.default_socket =
; Default host for mysql_connect() (doesn't apply in safe mode).
mysql.default_host =
; Default user for mysql_connect() (doesn't apply in safe mode).
mysql.default_user =
; Default password for mysql_connect() (doesn't apply in safe mode).
; Note that this is generally a *bad* idea to store passwords in this file.
; *Any* user with PHP access can run 'echo get_cfg_var("mysql.default_password")
; and reveal this password! And of course, any users with read access to this
; file will be able to reveal the password as well.
mysql.default_password =
; Maximum time (in seconds) for connect timeout. -1 means no limit
mysql.connect_timeout = 60
; Trace mode. When trace_mode is active (=On), warnings for table/index scans and
; SQL-Errors will be displayed.
mysql.trace_mode = Off
[mSQL]
; Allow or prevent persistent links.
msql.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
msql.max_persistent = -1
; Maximum number of links (persistent+non persistent). -1 means no limit.
msql.max_links = -1
[PostgresSQL]
; Allow or prevent persistent links.
pgsql.allow_persistent = On
; Detect broken persistent links always with pg_pconnect(). Need a little overhead.
pgsql.auto_reset_persistent = Off
; Maximum number of persistent links. -1 means no limit.
pgsql.max_persistent = -1
; Maximum number of links (persistent+non persistent). -1 means no limit.
pgsql.max_links = -1
; Ignore PostgreSQL backends Notice message or not.
pgsql.ignore_notice = 0
; Log PostgreSQL backends Noitce message or not.
; Unless pgsql.ignore_notice=0, module cannot log notice message.
pgsql.log_notice = 0
[Sybase]
; Allow or prevent persistent links.
sybase.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
sybase.max_persistent = -1
; Maximum number of links (persistent + non-persistent). -1 means no limit.
sybase.max_links = -1
;sybase.interface_file = "/usr/sybase/interfaces"
; Minimum error severity to display.
sybase.min_error_severity = 10
; Minimum message severity to display.
sybase.min_message_severity = 10
; Compatability mode with old versions of PHP 3.0.
; If on, this will cause PHP to automatically assign types to results according
; to their Sybase type, instead of treating them all as strings. This
; compatibility mode will probably not stay around forever, so try applying
; whatever necessary changes to your code, and turn it off.
sybase.compatability_mode = Off
[Sybase-CT]
; Allow or prevent persistent links.
sybct.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
sybct.max_persistent = -1
; Maximum number of links (persistent + non-persistent). -1 means no limit.
sybct.max_links = -1
; Minimum server message severity to display.
sybct.min_server_severity = 10
; Minimum client message severity to display.
sybct.min_client_severity = 10
[dbx]
; returned column names can be converted for compatibility reasons
; possible values for dbx.colnames_case are
; "unchanged" (default, if not set)
; "lowercase"
; "uppercase"
; the recommended default is either upper- or lowercase, but
; unchanged is currently set for backwards compatibility
dbx.colnames_case = "unchanged"
[bcmath]
; Number of decimal digits for all bcmath functions.
bcmath.scale = 0
[browscap]
;browscap = extra/browscap.ini
[Informix]
; Default host for ifx_connect() (doesn't apply in safe mode).
ifx.default_host =
; Default user for ifx_connect() (doesn't apply in safe mode).
ifx.default_user =
; Default password for ifx_connect() (doesn't apply in safe mode).
ifx.default_password =
; Allow or prevent persistent links.
ifx.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
ifx.max_persistent = -1
; Maximum number of links (persistent + non-persistent). -1 means no limit.
ifx.max_links = -1
; If on, select statements return the contents of a text blob instead of its id.
ifx.textasvarchar = 0
; If on, select statements return the contents of a byte blob instead of its id.
ifx.byteasvarchar = 0
; Trailing blanks are stripped from fixed-length char columns. May help the
; life of Informix SE users.
ifx.charasvarchar = 0
; If on, the contents of text and byte blobs are dumped to a file instead of
; keeping them in memory.
ifx.blobinfile = 0
; NULL's are returned as empty strings, unless this is set to 1. In that case,
; NULL's are returned as string 'NULL'.
ifx.nullformat = 0
[Session]
; Handler used to store/retrieve data.
session.save_handler = files
; Argument passed to save_handler. In the case of files, this is the path
; where data files are stored. Note: Windows users have to change this
; variable in order to use PHP's session functions.
; As of PHP 4.0.1, you can define the path as:
; session.save_path = "N;/path"
; where N is an integer. Instead of storing all the session files in
; /path, what this will do is use subdirectories N-levels deep, and
; store the session data in those directories. This is useful if you
; or your OS have problems with lots of files in one directory, and is
; a more efficient layout for servers that handle lots of sessions.
; NOTE 1: PHP will not create this directory structure automatically.
; You can use the script in the ext/session dir for that purpose.
; NOTE 2: See the section on garbage collection below if you choose to
; use subdirectories for session storage
;session.save_path = /tmp
; Whether to use cookies.
session.use_cookies = 1
; This option enables administrators to make their users invulnerable to
; attacks which involve passing session ids in URLs; defaults to 0.
; session.use_only_cookies = 1
; Name of the session (used as cookie name).
session.name = PHPSESSID
; Initialize session on request startup.
session.auto_start = 0
; Lifetime in seconds of cookie or, if 0, until browser is restarted.
session.cookie_lifetime = 0
; The path for which the cookie is valid.
session.cookie_path = /
; The domain for which the cookie is valid.
session.cookie_domain =
; Handler used to serialize data. php is the standard serializer of PHP.
session.serialize_handler = php
; Define the probability that the 'garbage collection' process is started
; on every session initialization.
; The probability is calculated by using gc_probability/gc_divisor,
; e.g. 1/100 means there is a 1% chance that the GC process starts
; on each request.
session.gc_probability = 1
session.gc_divisor = 100
; After this number of seconds, stored data will be seen as 'garbage' and
; cleaned up by the garbage collection process.
session.gc_maxlifetime = 1440
; NOTE: If you are using the subdirectory option for storing session files
; (see session.save_path above), then garbage collection does *not*
; happen automatically. You will need to do your own garbage
; collection through a shell script, cron entry, or some other method.
; For example, the following script would is the equivalent of
; setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
; cd /path/to/sessions; find -cmin +24 | xargs rm
; PHP 4.2 and less have an undocumented feature/bug that allows you to
; to initialize a session variable in the global scope, albeit register_globals
; is disabled. PHP 4.3 and later will warn you, if this feature is used.
; You can disable the feature and the warning separately. At this time,
; the warning is only displayed, if bug_compat_42 is enabled.
session.bug_compat_42 = 1
session.bug_compat_warn = 1
; Check HTTP Referer to invalidate externally stored URLs containing ids.
; HTTP_REFERER has to contain this substring for the session to be
; considered as valid.
session.referer_check =
; How many bytes to read from the file.
session.entropy_length = 0
; Specified here to create the session id.
session.entropy_file =
;session.entropy_length = 16
;session.entropy_file = /dev/urandom
; Set to {nocache,private,public,} to determine HTTP caching aspects
; or leave this empty to avoid sending anti-caching headers.
session.cache_limiter = nocache
; Document expires after n minutes.
session.cache_expire = 180
; trans sid support is disabled by default.
; Use of trans sid may risk your users security.
; Use this option with caution.
; – User may send URL contains active session ID
; to other person via. email/irc/etc.
; – URL that contains active session ID may be stored
; in publically accessible computer.
; – User may access your site with the same session ID
; always using URL stored in browser's history or bookmarks.
session.use_trans_sid = 0
; The URL rewriter will look for URLs in a defined set of HTML tags.
; form/fieldset are special; if you include them here, the rewriter will
; add a hidden <input> field with the info which is otherwise appended
; to URLs. If you want XHTML conformity, remove the form entry.
; Note that all valid entries require a "=", even if no value follows.
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=,fieldset="
[MSSQL]
; Allow or prevent persistent links.
mssql.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
mssql.max_persistent = -1
; Maximum number of links (persistent+non persistent). -1 means no limit.
mssql.max_links = -1
; Minimum error severity to display.
mssql.min_error_severity = 10
; Minimum message severity to display.
mssql.min_message_severity = 10
; Compatability mode with old versions of PHP 3.0.
mssql.compatability_mode = Off
; Connect timeout
;mssql.connect_timeout = 5
; Query timeout
;mssql.timeout = 60
; Valid range 0 – 2147483647. Default = 4096.
;mssql.textlimit = 4096
; Valid range 0 – 2147483647. Default = 4096.
;mssql.textsize = 4096
; Limits the number of records in each batch. 0 = all records in one batch.
;mssql.batchsize = 0
; Specify how datetime and datetim4 columns are returned
; On => Returns data converted to SQL server settings
; Off => Returns values as YYYY-MM-DD hh:mm:ss
;mssql.datetimeconvert = On
; Use NT authentication when connecting to the server
mssql.secure_connection = Off
; Specify max number of processes. Default = 25
;mssql.max_procs = 25
[Assertion]
; Assert(expr); active by default.
;assert.active = On
; Issue a PHP warning for each failed assertion.
;assert.warning = On
; Don't bail out by default.
;assert.bail = Off
; User-function to be called if an assertion fails.
;assert.callback = 0
; Eval the expression with current error_reporting(). Set to true if you want
; error_reporting(0) around the eval().
;assert.quiet_eval = 0
[Ingres II]
; Allow or prevent persistent links.
ingres.allow_persistent = On
; Maximum number of persistent links. -1 means no limit.
ingres.max_persistent = -1
; Maximum number of links, including persistents. -1 means no limit.
ingres.max_links = -1
; Default database (format: [node_id::]dbname[/srv_class]).
ingres.default_database =
; Default user.
ingres.default_user =
; Default password.
ingres.default_password =
[Verisign Payflow Pro]
; Default Payflow Pro server.
pfpro.defaulthost = "test-payflow.verisign.com"
; Default port to connect to.
pfpro.defaultport = 443
; Default timeout in seconds.
pfpro.defaulttimeout = 30
; Default proxy IP address (if required).
;pfpro.proxyaddress =
; Default proxy port.
;pfpro.proxyport =
; Default proxy logon.
;pfpro.proxylogon =
; Default proxy password.
;pfpro.proxypassword =
[com]
; path to a file containing GUIDs, IIDs or filenames of files with TypeLibs
;com.typelib_file =
; allow Distributed-COM calls
;com.allow_dcom = true
; autoregister constants of a components typlib on com_load()
;com.autoregister_typelib = true
; register constants casesensitive
;com.autoregister_casesensitive = false
; show warnings on duplicate constat registrations
;com.autoregister_verbose = true
[Printer]
;printer.default_printer = ""
[mbstring]
; language for internal character representation.
;mbstring.language = Japanese
; internal/script encoding.
; Some encoding cannot work as internal encoding.
; (e.g. SJIS, BIG5, ISO-2022-*)
;mbstring.internal_encoding = EUC-JP
; http input encoding.
;mbstring.http_input = auto
; http output encoding. mb_output_handler must be
; registered as output buffer to function
;mbstring.http_output = SJIS
; enable automatic encoding translation accoding to
; mbstring.internal_encoding setting. Input chars are
; converted to internal encoding by setting this to On.
; Note: Do _not_ use automatic encoding translation for
; portable libs/applications.
;mbstring.encoding_translation = Off
; automatic encoding detection order.
; auto means
;mbstring.detect_order = auto
; substitute_character used when character cannot be converted
; one from another
;mbstring.substitute_character = none;
; overload(replace) single byte functions by mbstring functions.
; mail(), ereg(), etc are overloaded by mb_send_mail(), mb_ereg(),
; etc. Possible values are 0,1,2,4 or combination of them.
; For example, 7 for overload everything.
; 0: No overload
; 1: Overload mail() function
; 2: Overload str*() functions
; 4: Overload ereg*() functions
;mbstring.func_overload = 0
[FrontBase]
;fbsql.allow_persistent = On
;fbsql.autocommit = On
;fbsql.default_database =
;fbsql.default_database_password =
;fbsql.default_host =
;fbsql.default_password =
;fbsql.default_user = "_SYSTEM"
;fbsql.generate_warnings = Off
;fbsql.max_connections = 128
;fbsql.max_links = 128
;fbsql.max_persistent = -1
;fbsql.max_results = 128
;fbsql.batchSize = 1000
[Crack]
; Modify the setting below to match the directory location of the cracklib
; dictionary files. Include the base filename, but not the file extension.
; crack.default_dictionary = "c:\php\lib\cracklib_dict"
[exif]
; Exif UNICODE user comments are handled as UCS-2BE/UCS-2LE and JIS as JIS.
; With mbstring support this will automatically be converted into the encoding
; given by corresponding encode setting. When empty mbstring.internal_encoding
; is used. For the decode settings you can distinguish between motorola and
; intel byte order. A decode setting cannot be empty.
;exif.encode_unicode = ISO-8859-15
;exif.decode_unicode_motorola = UCS-2BE
;exif.decode_unicode_intel = UCS-2LE
;exif.encode_jis =
;exif.decode_jis_motorola = JIS
;exif.decode_jis_intel = JIS
; Local Variables:
; tab-width: 4
; End:
extension=pdo.so
extension=pdo_sqlite.so
extension=sqlite.so
extension=pdo_mysql.so
zend_extension=/home1/softwax3/ioncube/ioncube_loader_lin.so
zend_extension_ts=/home1/softwax3/ioncube/ioncube_loader_lin_ts.so
[Zend]
zend_extension_manager.optimizer=/usr/local/Zend/lib/Optimizer-3.3.3
zend_extension_manager.optimizer_ts=/usr/local/Zend/lib/Optimizer_TS-3.3.3
zend_optimizer.version=3.3.3
zend_extension=/usr/local/Zend/lib/ZendExtensionManager.so
zend_extension_ts=/usr/local/Zend/lib/ZendExtensionManager_TS.so
<end node> 5P9i0s8y19Z
dt=
<node>setings
2
max_input_time=600
Current setting:
max_execution_time = 400 ; Maximum execution time of each script, in
seconds
max_input_time = 400 ; Maximum amount of time each script may spend parsing
request data
memory_limit = 30M ; Maximum amount of memory a script may consume
post_max_size = 30M ; Maximum size of POST data that PHP will accept.
upload_tmp_dir = /tmp/ ; Temporary directory for HTTP uploaded files.
<end node> 5P9i0s8y19Z
dt=
<node>phpAdmin
1
xxx.config.php
I had to add the url of the place I put the admin files which was do-wah-diddie.com/admin.
The language said 'en' is should be english.
Everything ran after these corrections
<end node> 5P9i0s8y19Z
dt=
<node>strings
1
rawurlencode
urlencode for passing gets
urldecode()
[lurl | urldecode for passing gets]
urldecode($var1);
<end node> 5P9i0s8y19Z
dt=
<node>ereg replacement
2
Posted 02 October 2010 – 02:34 PM
preg_match() Would be the pcre equivalent. The patterns will pretty much be the same, only real difference is that the preg_xxx functions require an opening/closing delimiter in the pattern and modifiers (if needed) are specified after the closing delimiter.
So for instance:
ereg(".",$var1)
would be
preg_match("~.~",$var1) // ~ is used as the pattern delimiter.
or for instance,
eregi(".",$var1) // case in-sensitive
would be
preg_match("~.~i",$var1) // i modifier added to make it case in-sensitive
if(eregi("color",$fieldName))
preg_match("~color~i",$fieldName))
<end node> 5P9i0s8y19Z
dt=
<node>eregi
2
http://docstore.mik.ua/orelly/webprog/pcook/ch13_02.htm
13.2. Switching From ereg to preg
13.2.1. Problem
You want to convert from using ereg functions to preg functions.
13.2.2. Solution
First, you have to add delimiters to your patterns:
preg_match('/pattern/', 'string')
For eregi( ) case-insensitive matching, use the /i modifier instead:
preg_match('/pattern/i', 'string');
When using integers instead of strings as patterns or replacement values, convert the number to hexadecimal and specify it using an escape sequence:
$hex = dechex($number);
preg_match("/\x$hex/", 'string');
13.2.3. Discussion
There are a few major differences between ereg and preg. First, when you use preg functions, the pattern isn't just the string pattern; it also needs delimiters, as in Perl, so it's /pattern/ instead.[11] So:
[11]Or {}, <>, ||, ##, or whatever your favorite delimiters are. PHP supports them all.
ereg('pattern', 'string');
becomes:
preg_match('/pattern/', 'string');
When choosing your pattern delimiters, don't put your delimiter character inside the regular-expression pattern, or you'll close the pattern early. If you can't find a way to avoid this problem, you need to escape any instances of your delimiters using the backslash. Instead of doing this by hand, call addcslashes( ).
For example, if you use / as your delimiter:
$ereg_pattern = '<b>.+</b>';
$preg_pattern = addcslashes($ereg_pattern, '/');
The value of $preg_pattern is now <b>.+<\/b>.
The preg functions don't have a parallel series of case-insensitive functions. They have a case-insensitive modifier instead. To convert, change:
eregi('pattern', 'string');
to:
preg_match('/pattern/i', 'string');
Adding the i after the closing delimiter makes the change.
Finally, there is one last obscure difference. If you use a number (not a string) as a pattern or replacement value in ereg_replace( ) , it's assumed you are referring to the ASCII value of a character. Therefore, since 9 is the ASCII representation of tab (i.e., \t), this code inserts tabs at the beginning of each line:
$tab = 9;
$replaced = ereg_replace('^', $tab, $string);
Here's how to convert linefeed endings:
$converted = ereg_replace(10, 12, $text);
To avoid this feature in ereg functions, use this instead:
$tab = '9';
On the other hand, preg_replace( ) treats the number 9 as the number 9, not as a tab substitute. To convert these character codes for use in preg_replace( ), convert them to hexadecimal and prefix them with \x. For example, 9 becomes \x9 or \x09, and 12 becomes \x0c. Alternatively, you can use \t , \r, and \n for tabs, carriage returns, and linefeeds, respectively.
This is line 466:
if(ereg('^([^=]*)=["\']?([^"\']*)["\']?$',$v,$a3))
I tried simply replacing with preg_match, but it couldn't recognize the = modifier in the regular expression.. I'm not too good with regular expression yet and solving this requires that I learn the regexp ereg needs AND the regexp preg_match needs (which, if I am not mistaken, is different)… Could you guys help me out with this one?
Thanks
php regex pcre posix-ere
share|improve this question
edited Aug 5 '10 at 10:26
Gumbo
292k42412549
asked Feb 7 '10 at 18:51
Shawn
1,60852455
add a comment
3 Answers
activeoldestvotes
up vote6down voteaccepted
POSIX extended regular expressions (POSIX ERE, used by ereg) and Perl-combatible regular expressions (PCRE, used by preg_match) are very similar. Except from some special POSIX expressions, PCRE is a superset of POSIX ERE.
That means you just need to put your POSIX ERE regular expressions into delimiters (here /) and escape any occurrence of that character inside the regular expression and you have a valid PCRE regular expression:
/^([^=]*)=["']?([^"']*)["']?$/
So:
preg_match('/^([^=]*)=["\']?([^"\']*)["\']?$/', $v, $a3)
share|improve this answer
=================================
if (eregi("[<>]",$reply))$found=true;
$text = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<A HREF='#' onclick=\"LoadPopup('\\0',800,800);\">\\0</a>", $c);
$text = ereg_replace("[[:alpha:]]+@[^<>[:space:]]+[[:alnum:]/]","<A HREF='mailto:\\0'>\\0</a>", $text);
<end node> 5P9i0s8y19Z
dt=
<node>find string
2
strpos($string,$character,$offset);
InStr($offset, $string,$charcter) compare vb.net
<end node> 5P9i0s8y19Z
dt=
<node>html tags
2
<?php
$text = '<p>Test paragraph.</p><!– Comment –> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
<end node> 5P9i0s8y19Z
dt=
<node>length
2
strlen($string)
<end node> 5P9i0s8y19Z
dt=
<node>lower case
2
$stringnew=strtolower($string);
[First Caps]
$string = strtolower($string);
$string = substr_replace($string, strtoupper(substr($string, 0, 1)), 0, 1);
<end node> 5P9i0s8y19Z
dt=
<node>pad
2
Run example »
——————————————————————————–
Definition and Usage
The str_pad() function pads a string to a new length.
——————————————————————————–
Syntax
str_pad(string,length,pad_string,pad_type)
Parameter
Description
string Required. Specifies the string to pad
length Required. Specifies the new string length. If this value is less than the original length of the string, nothing will be done
pad_string Optional. Specifies the string to use for padding. Default is whitespace
pad_type Optional. Specifies what side to pad the string.
Possible values:
•STR_PAD_BOTH – Pad to both sides of the string. If not an even number, the right side gets the extra padding
•STR_PAD_LEFT – Pad to the left side of the string
•STR_PAD_RIGHT – Pad to the right side of the string. This is default
Technical Details
<end node> 5P9i0s8y19Z
dt=
<node>section of string
2
$newstring=substr($string,int start, int length);
$url=$row['url'];
if($url!=""){
if(substr($url,0,4)=="www.")$url="http://".$url;
if(substr($url,0,7)!="http://")$url="http://".$url;
}
<end node> 5P9i0s8y19Z
dt=
<node>string replace
2
$longadd=str_replace(chr(13),'<BR>',$longadd);
<end node> 5P9i0s8y19Z
dt=
<node>System stuff
1
<end node> 5P9i0s8y19Z
dt=
<node>browser
2
<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
?>
The above example will output something similar to:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[css] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[vbscript] =>
[javascript] => 1
[javaapplets] => 1
[activexcontrols] =>
[cdf] =>
[aol] =>
[beta] => 1
[win16] =>
[crawler] =>
[stripper] =>
[wap] =>
[netclr] =>
)
<end node> 5P9i0s8y19Z
dt=
<node>URL
1
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER[REQUEST_URI];//$_SERVER['PHP_SELF'];
echo parse_url(get_site_url(),PHP_URL_PATH)."<br>$actual_link<br>";
//var_dump(parse_url($actual_link));
$part=parse_url($actual_link); echo $part["query"];
On seriously malformed URLs, parse_url() may return FALSE.
If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:
scheme – e.g. http
host
port
user
pass
path
query – after the question mark ?
fragment – after the hashmark #
If the component parameter is specified, parse_url() returns a string (or an integer, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, NULL will be returned.
Changelog ¶
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
<end node> 5P9i0s8y19Z
