redirect with header function not working - php

I have this htaccess filecontent:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^admin/([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ public/admin/index.php?page=$1&query=$2 [L]
RewriteRule ^([a-zA-Z]+)/?([a-zA-Z0-9/]*)$ public/index.php?page=$1&query=$2 [L]
And now im trying to make a redirection depending on a session, very simple stuff. I have a Controller with this function:
protected function redirect($url) {
header("Location: http://localhost:8888/myproject/" . $url, true);
exit();
}
The ClientController that extends Controller has the page function
private function user_page() {
$this->redirect("homepage"); //Not working...
}
I have tried different ways of writing the location path like
Location: localhost:8888/myproject/" . $url,
Location: /myproject/" . $url,
Now after reading all posts on stackoverflow, I see none of these solutions have worked for me..
Edit: the solution to this can be seen on header redirect to Location does not work

After getting an answer from header redirect to Location does not work I found that the problem was some row of spaces that had been inputted after ?> in the Controller, so it took a while to notice it.
Clarification:
If you have the same problem make sure you have line numbers set and see if you can see any line numbers after the file content. If there is you may have blank lines after aswell. Just delete these. Needless to say, the same goes for linenumbers before filecontent

Related

Is there a function or way to do in PHP similar how this works in Node JS?

In Node we can get an url address with a structure like this /example/:page/:id and we can take the page and id params. Is there a possibility to do something similar using PHP? Or is it only possible using the "?" with all the wanted params after the interrogation point?
I searched for a while and I tried some configurations in the htaccess file. All of them gave some kind of error like 403, 404 or in one of the configurations the intentioned page was loaded but it didn't find the css, js and images files.
Thanks
Edit:
I will put the solution I found here because maybe it can be useful for someone someday. After looking for some routers packages, I saw them instructing to put these lines in the htaccess file:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
I've tried something like this before and it was the one that I mentioned in the question that loaded the page but it didn't find the files like css, js, etc.
So I've decide to check the base url and I saw this was the point where the error was coming. After I changed it, the page loaded as the expected and now it's possible to get the value where the users can put a number and redirect to the page that they want (it's something like a magazine).
You can achieve it many ways.
In Laravel (see Documentation). I think every framework now has routing implemented.
Route::get('example/{page}/{id}', function ($page, $id) {
//
})->where(['page' => '[0-9]+', 'id' => '[a-z]+']);
With Mod-rewrite and then with access through $_GET parameters.
RewriteEngine on
RewriteRule ^example/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$ index.php?page=$1&id=$2 [NC]
You can also redirect everything to index.php and there implement your own router. See: Redirect all to index.php using htaccess
RewriteEngine on
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
Something like this could work
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode( '/', $uri );
// all of our endpoints start with /person
// everything else results in a 404 Not Found
if ($uri[1] !== 'page') {
header("HTTP/1.1 404 Not Found");
exit();
}
For more reference visit this url
https://developer.okta.com/blog/2019/03/08/simple-rest-api-php
have you tried parse_url()?
it will return and associative array which has all the components in your URL

HTTP status code 404 but contents are loading perfectly fine

I am running a site, where I am trying my own slug mechanism.
here are my .htaccess file contents
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L,QSA]
</IfModule>
and in my index.php I have following code
$_REQUEST['action'] = trim($_SERVER['REQUEST_URI'],"/");
...
if (!empty( $_REQUEST['action'] )) {
$action = explode("/", $_REQUEST['action']);
$slug = $action[0];
$pageName = $slug.".php";
if (file_exists($pageName)) {
require_once $pageName; // 404 status code
}
else {
echo 'Your page is not found'; // 200 status code
}
} else {
require_once 'welcome.php';
}
now how it will work is
/school will be mapped on school.php
/mobile will be mapped on mobile.php
/about will be mapped on about.php
apparently this work perfectly fine, contents are loaded fine, but issue with HTTP status code which is 404
on the other hand if I type some thing random like
/some-thing-random it shows this line echo 'Your page is not found'; with 200 status code (please note some-thing-random.php does not exist)
What strangely worked for me is as follows, I just added following line in .htaccess file and its working fine now with 200 message
Options +FollowSymLinks -MultiViews
for all those concerned about manually setting header: I had not. and it should not, all sort of urls will be intercepted by index.php, at least this is what my understaing is about my .htaccess file
one more strange thing is that might help you to respond to my question is
let say
if url is as follows
www.mysite.com/about and if rename file about.php as xabout.php and then just perform following
$fileName = 'x'.$slug.'.php';
require_once($fileName);
it works fine
Now my question is what on earth is happning? can any one please explain this to me (also note that I am using GoDaddy hosting)
To send a 404 code, it must be indicated in the header.
header("HTTP/1.0 404 Not Found");
More infos on http://php.net/manual/fr/function.header.php

htaccess call php script then continue processing

I have this specific problem where I have to check URL if its part is 8 chars long hash code that is saved in my database or its just normal URL where you want to navigate.
For example if i write url :
- www.example.com/A4s8Gga3
i want to process it with my script in php file
And if i write url :
-www.example.com/my-books
-www.example.com/about
i want to navigate on those pages.
I know i have to use htaccess (so much I managed myself) and so far it looks like this :
#part1
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} (\/\w+)$ [NC]
RewriteRule ^(.*)$ mobile_redirect.php [L]
#part2
RewriteCond %{REQUEST_URI} (/|\.htm|\.php|\.html|/[^.]*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php
My mobile_redirect.php looks like this:
ob_start();
require_once('connect.php');
$request = $_SERVER['REQUEST_URI'];
$request_hotovy = str_replace('/', '', $request);
$request_hotovy = mysql_real_escape_string($request_hotovy);
$select = "SELECT HASH_ID,OFFER FROM kasko_send_form WHERE MOBILE_HASH_ID = '".$request_hotovy."'";
$query = mysql_query($select);
if(mysql_num_rows($query) > 0){
// request is mobile hash id
$result = mysql_fetch_array($query);
$hash_id = $result['HASH_ID'];
header("Location: some_link?def=".$hash_id);
} else {
// request is normal url
header("Location: ".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
I know that it will end up redirecting in loop. I tried to put part1 after part2 and still have the same problem. I am using joomla and it have many urls (which im not able to write down) that are not real directories or files that is why i cant just use in my php file this solution :
ob_start();
require_once('connect.php');
$request = $_SERVER['REQUEST_URI'];
$request_hotovy = str_replace('/', '', $request);
$request_hotovy = mysql_real_escape_string($request_hotovy);
$select = "SELECT HASH_ID,OFFER FROM kasko_send_form WHERE MOBILE_HASH_ID = '".$request_hotovy."'";
$query = mysql_query($select);
if(mysql_num_rows($query) > 0){
// request is mobile hash id
$result = mysql_fetch_array($query);
$hash_id = $result['HASH_ID'];
header("Location: some_link?def=".$hash_id);
} else {
// request is normal url
header("Location: page_not_found.php");
}
Because there is clearly more url processing done in joomla after it ends reading my htaccess (i dont know much about joomla either).
Can you guys give me a hint how to process the url (then maybe alter it so it wont end up in loop and then alter it again after the part1 back to normal so it can continue processing as it would normally)?
Also if you guys have any good tutorials where I could learn such things it would be really helpfull, because i understand only basics of regex and how htaccess works ...
If you use Joomla for most of your URLs exact the one that should have this eight character string there is a simple solution for this.
Just use the regular Joomla .htaccess file and add two lines before RewriteBase /
RewriteCond %{REQUEST_URI} ^/[A-Za-z0-9]{8}$
RewriteRule .* mobile_redirect.php [L]
But the Problem here is that if you have regular URLs in Joomla with 8 character than they would be redirected es well e.g. http://example.com/lastnews
So for this URL's you have to add a exception, and the hole thing would lock like this:
RewriteCond %{REQUEST_URI} !^/latesnews$ [NC]
RewriteCond %{REQUEST_URI} !^/youandme$ [NC]
RewriteCond %{REQUEST_URI} ^/[A-Za-z0-9]{8}$
RewriteRule .* mobile_redirectt.php [L]
There is no way to redirect back to Joomla with the same URL if your script do not find a record in your DB. Either your script is handling the URL or Joomla dose it. So you have to provide a 404, or find a way to include the index.php file from Joomla in your script.

Codeigniter: The requested URL was not found in the server

I am not good in English so consider my grammatical mistake.
I am from Bangladesh so my client wants Bangla URL for SEO friendly. I tried to passing some particulars Unicode word in URL.
Normally everything is ok but when I pass this 'অর্থনীতি' types of word browser show object not found. I used url_encode/url_decode, permitted_uri_chars, and more other suggestion too but this browser message is same. can I pass this types of word in the URL?
I attached two picture. one is URL working fine and another is not working well.
**** Solution ****
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /example3/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /example3/index.php [L]
</IfModule>
first of all make sure you enable query string in config.php file
$config['enable_query_strings'] = TRUE;
Here you have to change your controller function.
public function news_details($news_id, $news_slug)
{
$data = array();
$data['news'] = $this->WelcomeModel->full_news($news_id);
$this->load->view('full-news', $data);
}
You just need to add this parameter $news_slug in your controller function
Edit 1 :
This is my function I tried :
function news_details($id, $slug){
print_r("News Id : ". $id);
print_r("<br>");
print_r("News Slug : ".$slug);
}
And this is what my output is :
Edit 2 :
Second screenshot as per your provided string

PHP / htaccess redirect via GET

I want:
sub.domain.com to load index.php
sub.domain.com?s=custom to load /custom/index.php
I'm doing this right now:
In .htaccess:
RewriteRule ^(custom)/?$ index.php?subject=$1
and in index.php I have this:
if($_GET['s'] == 'custom') {
header( 'Location: http://sub.domain.com/custom/index.php' ) ;
}
... but is it possible to do the redirect via htaccess itself depending on the GET variable?
Thanks!
Yes, you could check query string with RewriteCond
RewriteCond %{QUERY_STRING} s=custom
RewriteRule ^(.*?)$ custom/index.php [L]
With this, it redirects all requests with existing "custom" get parameter to index.php, and this can be extended :)
Idea: http://statichtml.com/2010/mod-rewrite-baseon-on-query-string.html
You probably want to use "RedirectMatch"
RedirectMatch ^sub.domain.com?s=custom$ /custom/index.php
Maybe youll need to play with the regex abit

Categories