Redirect user via 301 - too many loops?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

simonmlewis wrote:Bugger - I missed the fetch call as I always just use a While....
Yes I see it. bu tneed to gather the Subid and catid too.
They're part of the initial query. You already have them.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

So, keeping all the code in there, does this look about right?

Code: Select all

function slugify($string, $find = ' ', $replace = '-')
{
    return str_replace($find, $replace, $string);
}

if (!isset($_SESSION["loggedin"])) 
{
  if (isset($id))
  {
    $urlfind = $str[count($str)-2];
    $urlsubname = $str[count($str)-3];
    $urlsubid = $str[count($str)-4];
    $urlcatname = $str[count($str)-5];
    $urlcatid = $str[count($str)-6];
    
// Let's start by getting product information
        $query = "SELECT catid, subid, catname, subname, title FROM products WHERE id = :id";
        $stmt = $pdo->prepare($query);
        $stmt->execute(['id' => $id]);

        // If the product ID is not found, it will revert to the Sub or Cat
        if ($stmt->rowCount() == 0)
        {
          $queryredir = ("SELECT DISTINCT subid FROM products WHERE subid =:urlsubid");
          $resultredir = $pdo->prepare($queryredir);
          $resultredir->execute(array(':urlsubid' => $urlsubid));
          $num_rowssub = $resultredir->rowCount();
          if ($num_rowssub == "1")
            {
            header("Location: /subcateg/".urlencode($urlcatid)."/".urlencode($urlcatname)."/".urlencode($urlsubid)."/".   urlencode($urlsubname)."/",TRUE,301);
            }
          if ($num_rowssub == "0")
            {
            $queryredir = ("SELECT DISTINCT catid FROM products WHERE catid =:urlcatid");
            $resultredir = $pdo->prepare($queryredir);
            $resultredir->execute(array(':urlcatid' => $urlcatid));
            $num_rowscat = $resultredir->rowCount();
            if ($num_rowscat == "1")
              {
              header("Location: /categ/".urlencode($urlcatid)."/".urlencode($urlcatname)."/",TRUE,301);
              }
            if ($num_rowscat == 0)
              {
              header("HTTP/1.1 404 Not Found", true, 404);
              include ("custom_404.php");
              exit();
              }
            }
          }
          // If the product ID *IS* found... is the rest of the URL correct?
          // ID is unique. If rowCount isn't 0, then it's 1 and we've found the product
          else
          {
          // Just use the results of our first query
          $product    = $stmt->fetch(PDO::FETCH_OBJ);
          $subid = $product->subid;
          $catid = $product->catid;
          $title      = slugify($product->title);
          $catname    = slugify($product->catname);
          $subcatname = slugify($product->subname);
            
            if ($catname != $urlcatname || $subname != $urlsubname) {
            header("Location: /product/".urlencode($catid)."/".urlencode($catname)."/".urlencode($subid)."/".urlencode($subname)."/".urlencode($row->id)."/".urlencode($title)."/", TRUE, 301);
        }  
      }
      }
    }
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

Code: Select all

          $subid = $product->subid;
          $catid = $product->catid;
That bit isn't really necessary, as you could reference $product->catid directly below. You also don't need to urlencode integers (catid and subid). Finally, I'd recommend using a 302 until you've confirmed it's working properly. That aside, yes, it looks like it should work fine. What happens if the URL is already correct?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

You also appear to have removed your explode call. That's obviously going to need to be part of the final code. $str is undefined in your block above. I'm assuming you're already aware of that, but figured I'd mention it just in case.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

No that is causing an error.
It's looping again. I think it's finding it, then rewriting it, then finding it, then rewriting it and so on.

Here's everything.

Code: Select all

<?php
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
$id = isset($_GET['product']) ? $_GET['product'] : null;
$s = isset($_GET['s']) ? $_GET['s'] : null;
$c = isset($_GET['c']) ? $_GET['c'] : null;
$sname = isset($_GET['sname']) ? $_GET['sname'] : null;
$findsname ="/ /"; 
$replacesname ="-"; 
// rewriting subcategory name for use with hyphens in URL
$snamereplace = preg_replace ($findsname, $replacesname, $sname); 
$cname = isset($_GET['cname']) ? $_GET['cname'] : null;
$findcname ="/ /"; 
$replacecname ="-"; 
// rewriting category name for use with hyphens in URL
$cnamereplace = preg_replace ($findcname, $replacecname, $cname); 
$show = isset($_REQUEST['show']) ? $_REQUEST['show'] : null;
if (isset($show))
{
$rowsPerPage = $show;
}
else
{	  
if ( $detect->isMobile() && !$detect->isTablet() ) {
$rowsPerPage = 10;
}
else
{
$rowsPerPage = 44;
}
}
$pageNum = 1;
if(isset($_GET['pagenum']))
{
    $pageNum = $_GET['pagenum'];
}

if (isset($c) && !isset($id) && !isset($s))
{
$query   = "SELECT COUNT(id) AS numrows FROM products WHERE catid = :c AND pause = 'off'";
	$result  = $pdo->prepare($query);
  $result->execute(array(':c' => $_GET['c']));
  $numrows = $result->fetchColumn();
$maxPage = ceil($numrows/$rowsPerPage);
if ($pageNum > $maxPage)
{
// $c is the Category ID number in the URL
// $cnamereplace is from the variable at the top of this page - rewriting the category name from the database for the category
header("Location: /categ/".urlencode($c)."/".urlencode($cnamereplace)."/",TRUE,301);
}
}

if (isset($s) && !isset($id))
{
$query   = "SELECT COUNT(id) AS numrows FROM products WHERE subid = :s AND pause = 'off'";
	$result  = $pdo->prepare($query);
  $result->execute(array(':s' => $_GET['s']));
  $numrows = $result->fetchColumn();
$maxPage = ceil($numrows/$rowsPerPage);
if ($pageNum > $maxPage)
{
// $c is the Category ID number in the URL
// $cnamereplace is from the variable at the top of this page - rewriting the category name from the database for the category
// $s is the SubCategory ID number in the URL
// $snamereplace is from the variable at the top of this page - rewriting the subcategory name from the database for the category
header("Location: /subcateg/".urlencode($c)."/".urlencode($cnamereplace)."/".urlencode($s)."/".urlencode($snamereplace)."/",TRUE,301);
}
}
function checkURL()
{
 $pageURL = (isset($_SERVER['HTTPS']) && ($_SERVER["HTTPS"] == "on")) ? 'https://' : 'http://';
 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;
}
$url = checkURL();
$fullurl = "http://rs.site.co.uk"."$url";
$str = explode("/","$fullurl");
if (isset($c) && !isset($id) && !isset($s))
{
  $urlcatname = $str[count($str)-1];
  
$queryredir = ("SELECT DISTINCT catid FROM products WHERE catid =:c");
    $resultredir = $pdo->prepare($queryredir);
    $resultredir->execute(array(':c' => $c));
    $num_rows = $resultredir->rowCount();
    if ($num_rows == 0)
    {
    header("HTTP/1.1 404 Not Found", true, 404);
    include ("custom_404.php");
    exit();
    }
}



if (isset($s) && !isset($id))
{
  $urlsubname = $str[count($str)-2];
  $urlsubid = $str[count($str)-3];
  $urlcatname = $str[count($str)-4];
  $urlcatid = $str[count($str)-5];
 $queryredir = ("SELECT DISTINCT subid FROM products WHERE subid =:s");
  $resultredir = $pdo->prepare($queryredir);
  $resultredir->execute(array(':s' => $s));
  $num_rows = $resultredir->rowCount();
  if ($num_rows == "0")
  {
    $queryredir = ("SELECT DISTINCT catid FROM products WHERE catid =:c");
    $resultredir = $pdo->prepare($queryredir);
    $resultredir->execute(array(':c' => $c));
    $num_rows = $resultredir->rowCount();
    if ($num_rows == "1")
    {
    // $c is the Category ID number in the URL
// $urlcatname extracts the category name from the URL
    header("Location: /categ/".urlencode($c)."/".urlencode($urlcatname)."/",TRUE,301);
    }
    if ($num_rows == 0)
    {
    header("HTTP/1.1 404 Not Found", true, 404);
    include ("custom_404.php");
    exit();
    }
  }
}










function slugify($string, $find = ' ', $replace = '-')
{
    return str_replace($find, $replace, $string);
}

if (!isset($_SESSION["loggedin"])) 
{
  if (isset($id))
  {
    $urlfind = $str[count($str)-2];
    $urlsubname = $str[count($str)-3];
    $urlsubid = $str[count($str)-4];
    $urlcatname = $str[count($str)-5];
    $urlcatid = $str[count($str)-6];
    
// Let's start by getting product information
        $query = "SELECT id, catid, subid, catname, subname, title FROM products WHERE id = :id";
        $stmt = $pdo->prepare($query);
        $stmt->execute(['id' => $id]);

        // If the product ID is not found, it will revert to the Sub or Cat
        if ($stmt->rowCount() == 0)
        {
          $queryredir = ("SELECT DISTINCT subid FROM products WHERE subid =:urlsubid");
          $resultredir = $pdo->prepare($queryredir);
          $resultredir->execute(array(':urlsubid' => $urlsubid));
          $num_rowssub = $resultredir->rowCount();
          if ($num_rowssub == "1")
            {
            header("Location: /subcateg/".urlencode($urlcatid)."/".urlencode($urlcatname)."/".urlencode($urlsubid)."/".   urlencode($urlsubname)."/",TRUE,301);
            }
          if ($num_rowssub == "0")
            {
            $queryredir = ("SELECT DISTINCT catid FROM products WHERE catid =:urlcatid");
            $resultredir = $pdo->prepare($queryredir);
            $resultredir->execute(array(':urlcatid' => $urlcatid));
            $num_rowscat = $resultredir->rowCount();
            if ($num_rowscat == "1")
              {
              header("Location: /categ/".urlencode($urlcatid)."/".urlencode($urlcatname)."/",TRUE,301);
              }
            if ($num_rowscat == 0)
              {
              header("HTTP/1.1 404 Not Found", true, 404);
              include ("custom_404.php");
              exit();
              }
            }
          }
          // If the product ID *IS* found... is the rest of the URL correct?
          // ID is unique. If rowCount isn't 0, then it's 1 and we've found the product
          else
          {
          // Just use the results of our first query
          $product    = $stmt->fetch(PDO::FETCH_OBJ);
          $title      = slugify($product->title);
          $catname    = slugify($product->catname);
          $subcatname = slugify($product->subname);
            
            if ($catname != $urlcatname || $subname != $urlsubname) {
            header("Location: /product/$product->catid/".urlencode($catname)."/$product->subid/".urlencode($subcatname)."/".urlencode($product->id)."/".urlencode($title)."/", TRUE, 301);
        }  
      }
      }
    }

?>
Last edited by simonmlewis on Tue Oct 13, 2015 9:34 am, edited 1 time in total.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

Ok, I found the issue - it was in subcatname vs subname. My bad.
But it's not writing the URL. If I change the subid to something odd, then I was expecting it to reload the page with the correct one.

But it's not doing anything.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

Code: Select all

            if ($product->catid != $urlcatid || $product->subid != $urlsubid) {
            header("Location: /product/$product->catid/".urlencode($catname)."/$product->subid/".urlencode($subcatname)."/".urlencode($product->id)."/".urlencode($title)."/", TRUE, 301);
        }  
I thought this would do it.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

Looks like it should be working. Is it reaching that block? Is it performing any redirects? Where does it fail?
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

When I visit a full valid page, it's fine.
When I change the subid in the URL to say, 34999, the page still loads, but doesn't change the URL to what it SHOULD be.

No errors on screen.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

Have you confirmed it's hitting the script referenced above? Have you confirmed it's hitting the redirect block we're working on? Simple var_dump + exit will tell you both of those.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

What am I using var_dump for? To show exactly? The results of what variable?
I was hoping I'd see some error messages on my screen.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

Try

Code: Select all

var_dump($product); exit;
after fetching the product from the DB. That will at least confirm you're reaching that execution branch. We can progress from there.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

Ok when I add that, and change the URL with a dodgy number, it doesn't use that dodgy number in the var_dump. It shows the correct numbers that were there before. So it seems to be extracting the correct info from the database.
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Redirect user via 301 - too many loops?

Post by Celauran »

That's a good start. Next move on to the conditional. Remove the var_dump above and replace it with this right above your if statement.

Code: Select all

var_dump($product->catid != $urlcatid || $product->subid != $urlsubid); exit;
If that's true, then the problem is with your header() call. If it's false, then we need to examine why.
simonmlewis
DevNet Master
Posts: 4435
Joined: Wed Oct 08, 2008 3:39 pm
Location: United Kingdom
Contact:

Re: Redirect user via 301 - too many loops?

Post by simonmlewis »

Ok.
When I run that with the correct URL. I get:
[text]bool(false) [/text]

When I run it with the wrong URL (changing Subid to 349999), I get:
[text]bool(true)[/text]
Love PHP. Love CSS. Love learning new tricks too.
All the best from the United Kingdom.
Post Reply