0

having a problem with a delimiter. I'm a noob with PHP, so I'm sorry if this is a really simple fix. I was using eregi() before, but I checked on here for a "deprecated" error, and I found out that I had to use preg_match. Anyways, here's the error:

Warning: preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in /home/legitstr/public_html/members/includes/functions.php on line 4

And here's my code: (I've checked on other threads before, but no one seems to have similar code to mine)

$file = basename(__FILE__);
if(preg_match($file,$_SERVER['REQUEST_URI'])) {
die("Sorry but you cannot access this file directly for security reasons.");

Please help me out, and thank you!

Jonah Lee
  • 37
  • 7
  • You missed the part of code that's important here; the line. What that error means is that you need delimiters around your regex, so if it was `'regex'` now it has to be `'/regex/'`. PHP has some nice docs: http://www.php.net/manual/en/regexp.reference.delimiters.php – elclanrs Jan 26 '14 at 03:22
  • 2
    Why not a simple `strpos` or `stripos` instead of `preg_match`? – Gumbo Jan 26 '14 at 03:23
  • possible duplicate of [Delimiter must not be alphanumeric or backslash and preg\_match](http://stackoverflow.com/questions/7660545/delimiter-must-not-be-alphanumeric-or-backslash-and-preg-match) – Toto Jan 26 '14 at 10:40

2 Answers2

2

try:

$file = basename(__FILE__);
if(false !== strpos($_SERVER['REQUEST_URI'], $file)) {
die("Sorry but you cannot access this file directly for security reasons.");

strpos()

or

stripos()

for case insensitive match, should be a better match for what you seem to be doing

Bas Kuis
  • 748
  • 1
  • 7
  • 20
  • I agree this is a better approach than regex. My answer addresses "how to make the error go away", but your answer addresses "the right way to solve this problem". – Floris Jan 26 '14 at 03:29
0

You need to surround your regex with delimiters - usually something like /myregex/

If you leave off the delimiters you get this error. You could try

if(preg_match($file,"|".$_SERVER['REQUEST_URI']."|")) {

Since | is a legitimate delimiter, and may not be used in a legal URL

Having said that - regex is a powerful tool, and if you are looking for a verbatim match it may be overkill. Furthermore, a URL could have all kinds of characters in it that have special meaning in regex - which would actually cause a false match. For example, . in a regex means "any character", so apple.com will match applescom which is probably not what you want.

Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122