php-general Digest 6 Jul 2006 04:53:36 -0000 Issue 4224
Topics (messages 239148 through 239157):
Re: Filter php page
239148 by: Dave Goodchild
Re: What's the regex for this...?
239149 by: Tom Chubb
Re: global class instance
239150 by: Eric Butera
239151 by: KermodeBear
Re: About GD Version 2 or above..
239152 by: BBC
239154 by: Chris
Re: Printing in php
239153 by: BBC
require_once and E_WARNING?
239155 by: php.kermodebear.org
239156 by: Chris
239157 by: php.kermodebear.org
Administrivia:
To subscribe to the digest, e-mail:
[EMAIL PROTECTED]
To unsubscribe from the digest, e-mail:
[EMAIL PROTECTED]
To post to the list, e-mail:
[email protected]
----------------------------------------------------------------------
--- Begin Message ---
On 05/07/06, Jay Blanchard <[EMAIL PROTECTED]> wrote:
[snip]
can I create a script that will search a php page for iframes. And
have it check the path of the iframe, If the iframe is listed as bad
don't show. (list I make)
Trying to do something with virus like through an iframe.
I don't really know where to start looking for help.
[/snip]
Best thing to do is open the file, use regular expressions to capture all
text that begins and ends with 'iframe', parse that for src=url, attempt to
get the url, if it fails it's bad and you can rewrite the string back into
the file, perhaps adding a css class such as 'class=bad' that has display
set to none.
So, have a look at files, regular expressions and css.
--
http://www.web-buddha.co.uk
http://www.projectkarma.co.uk
--- End Message ---
--- Begin Message ---
Brian,
I was trying to do this the other day using file_get_contents to load a page
into a variable, but never quite got round to finishing it off.
However, I recently received a very good Reg Exp tutorial which I hope is of
use to you...
*Basic Syntax of Regular Expressions (as from PHPBuilder.com)*
First of all, let's take a look at two special symbols: '^' and '$'. What
they do is indicate the
start and the end of a string, respectively, like this:
"^The": matches any string that starts with "The";
"of despair$": matches a string that ends in the substring "of despair";
"^abc$": a string that starts and ends with "abc" -- that could only be
"abc" itself!
"notice": a string that has the text "notice" in it.
You can see that if you don't use either of the two characters we mentioned,
as in the last example,
you're saying that the pattern may occur anywhere inside the string --
you're not "hooking" it to any of the edges.
There are also the symbols '*', '+', and '?', which denote the number of
times a character or a sequence of
characters may occur. What they mean is: "zero or more", "one or more", and
"zero or one." Here are some examples:
"ab*": matches a string that has an a followed by zero or more b's ("a",
"ab", "abbb", etc.);
"ab+": same, but there's at least one b ("ab", "abbb", etc.);
"ab?": there might be a b or not;
"a?b+$": a possible a followed by one or more b's ending a string.
You can also use bounds, which come inside braces and indicate ranges in the
number of occurences:
"ab{2}": matches a string that has an a followed by exactly two b's ("abb");
"ab{2,}": there are at least two b's ("abb", "abbbb", etc.);
"ab{3,5}": from three to five b's ("abbb", "abbbb", or "abbbbb").
Note that you must always specify the first number of a range (i.e, "{0,2}",
not "{,2}"). Also, as you might
have noticed, the symbols '*', '+', and '?' have the same effect as using
the bounds "{0,}", "{1,}", and "{0,1}",
respectively.
Now, to quantify a sequence of characters, put them inside parentheses:
"a(bc)*": matches a string that has an a followed by zero or more copies of
the sequence "bc";
"a(bc){1,5}": one through five copies of "bc."
There's also the '|' symbol, which works as an OR operator:
"hi|hello": matches a string that has either "hi" or "hello" in it;
"(b|cd)ef": a string that has either "bef" or "cdef";
"(a|b)*c": a string that has a sequence of alternating a's and b's ending in
a c;
A period ('.') stands for any single character:
"a.[0-9]": matches a string that has an a followed by one character and a
digit;
"^.{3}$": a string with exactly 3 characters.
Bracket expressions specify which characters are allowed in a single
position of a string:
"[ab]": matches a string that has either an a or a b (that's the same as
"a|b");
"[a-d]": a string that has lowercase letters 'a' through 'd' (that's equal
to "a|b|c|d" and even "[abcd]");
"^[a-zA-Z]": a string that starts with a letter;
"[0-9]%": a string that has a single digit before a percent sign;
",[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric
character.
You can also list which characters you DON'T want -- just use a '^' as the
first symbol in a bracket expression
(i.e., "%[^a-zA-Z]%" matches a string with a character that is not a letter
between two percent signs).
In order to be taken literally, you must escape the characters
"^.[$()|*+?{\" with a backslash ('\'), as
they have special meaning. On top of that, you must escape the backslash
character itself in PHP3 strings, so,
for instance, the regular expression "(\$|¥)[0-9]+" would have the function
call: ereg("(\\$|¥)[0-9]+", $str)
(what string does that validate?)
Example 1. Examples of valid patterns
* /<\/\w+>/
* |(\d{3})-\d+|Sm
* /^(?i)php[34]/
* {^\s+(\s+)?$}
Example 2. Examples of invalid patterns
* /href='(.*)' - missing ending delimiter
* /\w+\s*\w+/J - unknown modifier 'J'
* 1-\d3-\d3-\d4| - missing starting delimiter
Some useful PHP Keywords and their use (php.net man pages)
preg_split
(PHP 3>= 3.0.9, PHP 4 )
preg_split -- Split string by a regular expression
Description
array preg_split ( string pattern, string subject [, int limit [, int
flags]])
Returns an array containing substrings of subject split along boundaries
matched by pattern.
If limit is specified, then only substrings up to limit are returned, and if
limit is -1, it
actually means "no limit", which is useful for specifying the flags.
flags can be any combination of the following flags (combined with bitwise |
operator):
PREG_SPLIT_NO_EMPTY
If this flag is set, only non-empty pieces will be returned by preg_split().
PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will
be captured and
returned as well. This flag was added for 4.0.5.
PREG_SPLIT_OFFSET_CAPTURE
If this flag is set, for every occuring match the appendant string offset
will also be
returned. Note that this changes the return value in an array where every
element is an
array consisting of the matched string at offset 0 and it's string offset
into subject
at offset 1. This flag is available since PHP 4.3.0 .
Example 1. preg_split() example : Get the parts of a search string
// split the phrase by any number of commas or space characters,
// which include " ", \r, \t, \n and \f
$keywords = preg_split ("/[\s,]+/", "hypertext language, programming");
?>
Example 2. Splitting a string into component characters
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>
Example 3. Splitting a string into matches and their offsets
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>
will yield:
Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)
[1] => Array
(
[0] => language
[1] => 10
)
[2] => Array
(
[0] => programming
[1] => 19
)
)
Note: Parameter flags was added in PHP 4 Beta 3.
preg_match
(PHP 3>= 3.0.9, PHP 4 )
preg_match -- Perform a regular expression match
Description
int preg_match ( string pattern, string subject [, array matches [, int
flags]])
Searches subject for a match to the regular expression given in pattern.
If matches is provided, then it is filled with the results of search.
$matches[0] will
contain the text that matched the full pattern, $matches[1] will have the
text that matched
the first captured parenthesized subpattern, and so on.
flags can be the following flag:
PREG_OFFSET_CAPTURE
If this flag is set, for every occuring match the appendant string offset
will also
be returned. Note that this changes the return value in an array where every
element
is an array consisting of the matched string at offset 0 and it's string
offset into
subject at offset 1. This flag is available since PHP 4.3.0 .
The flags parameter is available since PHP 4.3.0 .
preg_match() returns the number of times pattern matches. That will be
either 0 times
(no match) or 1 time because preg_match() will stop searching after the
first match.
preg_match_all() on the contrary will continue until it reaches the end of
subject.
preg_match() returns FALSE if an error occured.
Tip: Do not use preg_match() if you only want to check if one string is
contained
in another string. Use strpos() or strstr() instead as they will be faster.
Example 1. Find the string of text "php"
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match ("/php/i", "PHP is the web scripting language of choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
?>
*Example 2.* Find the word "web"
/* The \b in the pattern indicates a word boundary, so only the distinct
* word "web" is matched, and not a word partial like "webbing" or "cobweb"
*/
if (preg_match ("/\bweb\b/i", "PHP is the web scripting language of
choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
if (preg_match ("/\bweb\b/i", "PHP is the website scripting language of
choice.")) {
print "A match was found.";
} else {
print "A match was not found.";
}
?>
*Example 3.* Getting the domain name out of a URL
// get host name from URL
preg_match("/^(http:\/\/)?([^\/]+)/i",
"http://www.php.net/index.html ", $matches);
$host = $matches[2];
// get last two segments of host name
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
This example will produce:
domain name is: php.net
Perl Style Delimiters (as from crazygrrl.com)
When using Perl-style matching, the pattern also has to be enclosed by
special delimiters.
The default is the forward slash, though you can use others. For example:
/colou?r/
Usually you'll want to stick with the default, but if you need to use the
forward slash a lot in the actual pattern (especially if you're dealing with
pathnames) you might want to use something else:
!/root/home/random!
To make a match case-insensitive, all you need to do is append the option
i to the pattern:
/colou?r/i
Perl-style functions support these extra metacharacters (this is not a full
list):
\b A word boundary, the spot between word (\w) and non-word (\W) characters.
\B A non-word boundary.
\d A single digit character.
\D A single non-digit character.
\n The newline character. (ASCII 10)
\r The carriage return character. (ASCII 13)
\s A single whitespace character.
\S A single non-whitespace character.
\t The tab character. (ASCII 9)
\w A single word character - alphanumeric and underscore.
\W A single non-word character.
Example:
/\bhomer\b/
Have a donut, Homer no match
A tale of homeric proportions! no match
Do you think he can hit a homer? match
Corresponding to ereg() is preg_match(). Syntax:
preg_match(pattern (string), target (string), optional_array);
Example:
$pattern = "/\b(do(ugh)?nut)\b.*\b(Homer|Fred)\b/i";
$target = "Have a donut, Homer.";
if (preg_match($pattern, $target, $matches)) {
print("
Match: $reg[0]
");
print("
Pastry: $reg[1]
");
print("
Variant: $reg[2]
");
print("
Name: $reg[3]
");
}
else {
print("No match.");
}
Results:
Match: donut, Homer
Pastry: donut
Variant: [blank because there was no "ugh"]
Name: Homer
If you use the $target "Doughnut, Frederick?" there will be no match,
since there has to be a word boundary after Fred.
but "Doughnut, fred?" will match since we've specified it to be
case-insensitive.
Contributed code which is applicable (and very useful!)
mkr at binarywerks dot dk
A (AFAIK) correct implementation of Ipv4 validation, this one supports
optional ranges
(CIDR notation) and it validates numbers from 0-255 only in the address
part, and 1-32
only after the /
function valid_ipv4($ip_addr)
{
$num="([0-9]|1?\d\d|2[0-4]\d|25[0-5])";
$range="([1-9]|1\d|2\d|3[0-2])";
if(preg_match("/^$num\.$num\.$num\.$num(\/$range)?$/",$ip_addr))
{
return 1;
}
return 0;
}
$ip_array[] = "127.0.0.1";
$ip_array[] = "127.0.0.256 ";
$ip_array[] = "127.0.0.1/36";
$ip_array[] = " 127.0.0.1/1";
foreach ($ip_array as $ip_addr)
{
if(valid_ipv4($ip_addr))
{
echo "$ip_addr is valid
\n";
}
else
{
echo "$ip_addr is NOT valid
\n";
}
}
?>
plenque at hotmail dot com
I wrote a function that checks if a given regular expression is valid. I
think some of
you might find it useful. It changes the error_handler and restores it, I
didn't find
any other way to do it.
Function IsRegExp ($sREGEXP)
{
$sPREVIOUSHANDLER = Set_Error_Handler ("TrapError");
Preg_Match ($sREGEXP, "");
Restore_Error_Handler ($sPREVIOUSHANDLER);
Return !TrapError ();
}
Function TrapError ()
{
Static $iERRORES;
If (!Func_Num_Args ())
{
$iRETORNO = $iERRORES;
$iERRORES = 0;
Return $iRETORNO;
}
Else
{
$iERRORES++;
}
}
PHP Get_title tag code which uses simple regex and nice php string functions
(As from Zend PHP)
function get_title_tag($chaine){
$fp = fopen ($chaine, 'r');
while (! feof ($fp)){
$contenu .= fgets ($fp, 1024);
if (stristr($contenu, '<\title>' )){
break;
}
}
if (eregi("", $contenu, $out)) {
return $out[1];
}
else{
return false;
}
}
?>
My Own 'Visitor Trac' code which uses regex XML parsing methods
$referer = $_SERVER['HTTP_REFERER'];
$filename = $_SERVER[REMOTE_ADDR] . '.txt';
//print_r($_SERVER);
if (file_exists($filename)){
$lastvisit = filectime($filename);
$currentdate = date('U');
$difference = round(($currentdate - $lastvisit)/84600);
if ($difference > 7) {
unlink($filename);
$fp = fopen($filename, "a");
}
else $fp = fopen($filename, "a");
}
else $fp = fopen($filename, "a");
if (!$_SERVER['HTTP_REFERER']) $url_test = ' http://dinki.mine.nu/weblog/';
else $url_test = $_SERVER['HTTP_REFERER'];
$new_title = return_title ($url_test);
//print $new_title;
$new_name = stripslashes("$new_title\n");
$new_URL = stripslashes("$referer\n");
fwrite($fp,$new_URL);
fwrite($fp,$new_name);
fclose($fp);
$fp = fopen($filename, "r");
$file = implode('', file ($filename));
$foo = preg_split("//",$file);
$number = count($foo);
//print $number;
if ($number > 11) {
fclose($fp);
$fp = fopen($filename, "w");
$count = $number - 10;
while ($count < $number) {
$print1 = $foo[$count];
$print2 = $foo[$count+1];
print " ";
print " $print2 <http://arif-blog.blogspot.com$print1/>"; //print $count;
$count += 2;
$new_name = stripslashes("$print2");
$new_URL = stripslashes("$print1");
fwrite($fp,$new_URL);
fwrite($fp,$new_name);
}
fclose($fp);
}
//print_r($foo);
else {
$count = 1;
while ($count <= $number) {
$print1 = $foo[$count];
$print2 = $foo[$count+1];
print " ";
print " $print2 <http://arif-blog.blogspot.com$print1/>"; //print $count;
$count += 2;
}
fclose($fp);
}
?>
On 05/07/06, Brian Dunning <[EMAIL PROTECTED]> wrote:
I have the source of a web page stored in $here and I want to set
$this to whatever appears between '<span class="myclass">' and '</
span>'. Example:
$here contains (amid tons of other stuff): <span
class="myclass">This is a statement.</span>
I want to set $this to "This is a statement." Seems simple but I'm
banging my head against a wall and can't figure out how to do it...
can anyone help out a dude on the 4th of July?? :) :)
- Brian
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
--
Tom Chubb
[EMAIL PROTECTED]
07915 053312
--- End Message ---
--- Begin Message ---
On 7/1/06, sempsteen <[EMAIL PROTECTED]> wrote:
hi all,
i wonder if there is a way of creating an instance of a class and
reach it direcly from any scope in PHP4. basically what i want is:
class a
{
function print()
{
echo 'sth';
}
}
$a = new a();
and use this "a" instance from anywhere ex, in a function that is a
method of another class.
class b
{
function print()
{
$a->print();
}
}
i don't want to:
- declare global $foo,
- use pre-defined $GLOBALS variable,
- or use a::print
thanks.
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
Static is your friend.
http://www.horde.org/papers/kongress2002-design_patterns/11_singleton_impl.xml.html
--- End Message ---
--- Begin Message ---
>> hi all,
>> i wonder if there is a way of creating an instance of a class and
>> reach it direcly from any scope in PHP4. basically what i want is:
>> i don't want to:
>> - declare global $foo,
>> - use pre-defined $GLOBALS variable,
>> - or use a::print
>>
>> thanks.
> Static is your friend.
>
http://www.horde.org/papers/kongress2002-design_patterns/11_singleton_impl.x
ml.html
Also, if using PHP 4, make sure to read the "References with global and
static variables" section. It doesn't work quite the way a lot of people
expect it to.
http://us2.php.net/static
The manual isn't all that clear, but the user comments help a lot (which, I
have found, is often the case, but that's a rant for another day... At least
we have a manual that accepts such comments!)
class Singleton {
function &getFoo() {
$object =& Singleton::getFooRef();
if (!is_a('Foo', $object)) {
$object =& new Foo();
}
return $object;
}
function &getFooRef() {
static $object = null;
return $object;
}
}
$myFoo =& Singleton::getFoo();
Hope that helps.
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php
--- End Message ---
--- Begin Message ---
> Take out the ; in that line and re-start your computer and you should
> have GD installed, with any luck...
Thank for your answer...
I tried your suggestion to take out the ';'. Somehow the error still there
but different out put.
"GD version 2 or above is needed" or something. So I got the conclusion that
I need to upgrade my GD version, I visited this page
http://www.php.net/manual/en/install.windows.extensions.php as Chris told
me. But I couldn't find the 'GD' version 2 or above. I got only explanation
about GD but not the GD it self. Huh.. someone please tell me where can I
get that GD or should I upgrade my PHP v4.1.1, so I can get that GD v2 or
above
> On Sun, July 2, 2006 12:42 pm, BBC wrote:
> >> Did you check if you had the required "gd" extension? I believe
> >> someone
> > already told you and how to check.
> >
> > Sorry I resent my question unintentionally
> > I believe no one did.
> > btw, what is GD extension, and how to install or load it?
> > I have read my 'php.ini', and then I found this:
> > ;extension=php_gd.dll
> > But I don't know what's that suppose to mean..
> > My system is winXP
> >
>
--- End Message ---
--- Begin Message ---
BBC wrote:
Take out the ; in that line and re-start your computer and you should
have GD installed, with any luck...
Thank for your answer...
I tried your suggestion to take out the ';'. Somehow the error still there
but different out put.
"GD version 2 or above is needed" or something. So I got the conclusion that
I need to upgrade my GD version, I visited this page
http://www.php.net/manual/en/install.windows.extensions.php as Chris told
me. But I couldn't find the 'GD' version 2 or above. I got only explanation
about GD but not the GD it self. Huh.. someone please tell me where can I
get that GD or should I upgrade my PHP v4.1.1, so I can get that GD v2 or
above
I doubt gd2 works with php4.1.1, I'd suggest an upgrade for many reasons
apart from this particular one (security fixes are very high on that list).
--
Postgresql & php tutorials
http://www.designmagick.com/
--- End Message ---
--- Begin Message ---
> weetat wrote:
> > Hi all ,
> >
> > I am using PHP 4.3.2 and MYSQL .
> >
> > I need to do printing function in php .
> > Basically , in my client web page , it will display the list of items
> > on the html page. And i have a print button , so that the user can print
> > the html page to their local printer.
> >
> > Any way how to do this in PHP ?
I believe someone already told you,
I guess we can't do it in PHP, so why not in JavaScript
Sorry I don't mean to take you belittle, but I write this completely for
easy to look for others:
<a href=”#” action="window.print();return false">Print this page</a>
Best Regards
============BBC============
**o<0>o**
--- End Message ---
--- Begin Message ---
Hello all,
According to the PHP Manual, when require or require_once failes, an
E_ERROR is triggered: "require() and include() are identical in every way
except how they handle failure. include() produces a Warning while
require() results in a Fatal Error." (With 'Fatal Error' being a link to
E_ERROR).
Thing is, when using a custom error handler via set_error_handler(), it
appears to be triggering an E_WARNING, not an E_ERROR. Using PHP 5.1.4
under Linux.
There are one of three possibilities: I am suffering from a lapse in
lucidity (common), the manual is wrong (possible), or PHP is broken
somehow (unlikely). I'm guessing it's the first, but what am I doing
wrong? I'd like to get a second opinion before submitting a bug. I
searched bugs.php.net but was unable to find anything relevant for 5.1.4.
Code:
function default_error_handler($code, $error, $file, $line) {
switch ($code) {
case E_ERROR:
die ("Error: $error");
case E_WARNING:
die("Warning: $error");
default:
die("Something else entirely: $error");
}
}
set_error_handler('default_error_handler');
require('This file does not exist. At least not here!');
Result:
Warning: require(This file does not exist. At least not here!)
[function.require]: failed to open stream: No such file or directory
Expected Result:
Error: require(This file does not exist. At least not here!)
[function.require]: failed to open stream: No such file or directory
--- End Message ---
--- Begin Message ---
[EMAIL PROTECTED] wrote:
Hello all,
According to the PHP Manual, when require or require_once failes, an
E_ERROR is triggered: "require() and include() are identical in every way
except how they handle failure. include() produces a Warning while
require() results in a Fatal Error." (With 'Fatal Error' being a link to
E_ERROR).
Thing is, when using a custom error handler via set_error_handler(), it
appears to be triggering an E_WARNING, not an E_ERROR. Using PHP 5.1.4
under Linux.
There are one of three possibilities: I am suffering from a lapse in
lucidity (common), the manual is wrong (possible), or PHP is broken
somehow (unlikely). I'm guessing it's the first, but what am I doing
wrong? I'd like to get a second opinion before submitting a bug. I
searched bugs.php.net but was unable to find anything relevant for 5.1.4.
Code:
function default_error_handler($code, $error, $file, $line) {
switch ($code) {
case E_ERROR:
die ("Error: $error");
case E_WARNING:
die("Warning: $error");
default:
die("Something else entirely: $error");
}
}
set_error_handler('default_error_handler');
require('This file does not exist. At least not here!');
Result:
Warning: require(This file does not exist. At least not here!)
[function.require]: failed to open stream: No such file or directory
Expected Result:
Error: require(This file does not exist. At least not here!)
[function.require]: failed to open stream: No such file or directory
If you comment out the 'set_error_handler' line what happens? Do you get
what you expect (and what should happen) ?
It looks like a pretty simple bug report to me but others may have
reasons why it's not working.
--
Postgresql & php tutorials
http://www.designmagick.com/
--- End Message ---
--- Begin Message ---
>> Code:
>> function default_error_handler($code, $error, $file, $line) {
>> switch ($code) {
>> case E_ERROR:
>> die ("Error: $error");
>> case E_WARNING:
>> die("Warning: $error");
>> default:
>> die("Something else entirely: $error");
>> }
>> }
>> set_error_handler('default_error_handler');
>> require('This file does not exist. At least not here!');
>>
>> Result:
>> Warning: require(This file does not exist. At least not here!)
>> [function.require]: failed to open stream: No such file or directory
>>
>> Expected Result:
>> Error: require(This file does not exist. At least not here!)
>> [function.require]: failed to open stream: No such file or directory
>>
>
> If you comment out the 'set_error_handler' line what happens? Do you get
> what you expect (and what should happen) ?
>
> It looks like a pretty simple bug report to me but others may have
> reasons why it's not working.
Without the error handler, I get the expected result: A fatal error with
the script dying. That is what makes this so mysterious. Doesn't make
sense that it would raise a different kind of error under different
circumstances. It should have the same value every time.
I'm going to sit on this for a day or so and see what people say before I
toss it over to the bug folks. No sense in bothering them if I'm being a
bonehead. (o;
--- End Message ---