1

How can I redirect to a specific url in php, based on the first number input?

If the first number entered in the form is 1, then redirect to www.mysite.com/page1, If the first number entered in the same form is 2, then redirect to www.mysite.com/page2.

The input field can have more than one number, but I want to redirect based just on first number.

I've tried this and doesn't work:

if ($number != '2') {
    header("Location: http://example.com");
}
Will
  • 24,082
  • 14
  • 97
  • 108
Antonov A.
  • 11
  • 1
  • `header("Location: /page".$number);`, where `$number` is the one you get from the input. Note that headers must be sent before ANY kind of output to the browser, see [this post](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – Qirel Jan 24 '16 at 02:04
  • Better to show your form content. From where are you getting '$number' ? – zeflex Jan 24 '16 at 02:22
  • Are the URLs always identical except for the number at the end? Or could the URLs for each different number be completely different? – Will Jan 24 '16 at 03:02

2 Answers2

1

Try this:

<?php

$pages = [
    1 => 'http://example.com/some_page.html',
    2 => 'http://example.com/some_page_other.html',
    //...
    9 => 'http://example.com/differentpage.html',
];

if (!empty($_GET['number']))
{
    $firstNumber = (int) $_GET['number'][0]
}

if (isset($firstNumber, $pages[$number]))
{
    header('Location: ' . $pages[$number]);
}
else
{
    // We don't have a page for this number, or we don't have a number input.
}

This allows you to use a completely different URL for each number. If it's always the same URL, with a different number on the end, you could do this instead:

<?php

$baseUrl = 'www.example.com/page';

if (!empty($_GET['number']))
{
    $firstNumber = (int) $_GET['number'][0]
}

if (isset($firstNumber))
{
    header('Location: ' . $baseUrl . $number);
}
else
{
    // We don't have a number from the input.
}
Will
  • 24,082
  • 14
  • 97
  • 108
0

don't forget exit() or it will continue execute current script

if ($number != '2') {
    header("Location: http://example.com");
    exit();
}
uingtea
  • 6,002
  • 2
  • 26
  • 40