I'm working on a URL shortener script.
My script generates a link like http://127.0.0.1:1337/urlshortener/v5tjp.
v5tjp is a random value, generated by a script.
My script's logic is that I input an URL, then PHP takes it, generates a random value (with the length taken also from the SQL database), then inserts the long url and the short url in the database.
Where I'm stuck: I need to create a .htaccess file to redirect the visitor to redirect.php, where I have the redirect script.
This is the redirect.php file:
<?php
include ('connect.php');
$decode = mysql_real_escape_string($_GET['decode']);
$sql = 'SELECT * FROM urls WHERE short_code="$decode"';
$result = mysql_query($sql);
if (isset($_GET['url_token'])){
$urlId=$_GET['url_token'];
$query = "SELECT * FROM urls WHERE short_code=".$urlId." LIMIT 1";
$redirect = mysql_query($query);
if(mysql_num_rows($redirect)) {
$row = mysql_fetch_assoc($redirect);
$url = $row['long_url'];
header('Location: http://'.$url);
}
echo 'Bad URL!';
exit();
}
while($row = mysql_fetch_array($result))
{
$res=$row['long_url'];
header("location:".$res);
}
This is the .htaccess file I've made:
RewriteEngine On
RewriteRle ^$ index.php [L]
RewriteCond %(REQUEST_FILENAME) !-f
RewriteRule ^(.*)$ redirect.php?url_token=$1 [L]
But for some reason it's not working. I'm running my script with XAMPP.
RewriteRule ^$ index.php [L]
You missed a 'u'.
Try this code:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteRle ^$ /index.php [L]
RewriteCond %(REQUEST_FILENAME) !-f
RewriteRule ^urlshortener/(.*)$ /redirect.php?url_token=$1 [L,QSA,NC]
Related
I know there are many similar questions on this and I've read them and no they didn't work. I want to show 404 page when a non existing dynamic url is accessed on my website but without changing the url. For example:
https://www.trvme.com/destinations/corbett
is fine. But if I enter an invalid link like
https://www.trvme.com/destinations/corbetts
I get browser's 404 error but I don't see my 404 page.
Here's the code I have in PHP
if(isset($_GET['destId'])){
$link = mysqli_real_escape_string($connect, $_GET['destId']);
$thisPage = 'destinations/'.$link;
$query = "SELECT * FROM `destinations` WHERE `link` = '$link' AND `active` = 1 AND `delete` = 0";
$destinationsQuery = mysqli_query($connect, $query);
if(mysqli_num_rows($destinationsQuery)!=0){
// do stuff
} else {
http_response_code(404);
exit();
}
} else {
http_response_code(404);
exit();
}
And htaccess
RewriteEngine On
ErrorDocument 404 /message.php?id=2
RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]
I don't want to use header('location:message.php?id=2'); in php because that would change the URL. I'm getting 404 code from the URL but htaccess doesn't seem to be doing its job.
I also can't use
http_response_code(404);
include 'message.php';
because it throws all kinds of errors like session has started already and constants have been defined already. That doesn't seem like an elegant solution.
Edit:
The code in the linked question doesn't work for me. If I add the code above the destinations rule, the existing, legitimate pages also go to 404 because there's no actual file or directory, these are dynamic urls.
RewriteEngine On
ErrorDocument 404 /message.php?id=2
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /message.php?id=2 [L,NC]
RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]
If I put it afterwards, it just doesn't work because the destinations rule takes over
RewriteEngine On
ErrorDocument 404 /message.php?id=2
RewriteRule ^destinations/(.*)$ destinations.php?destId=$1 [NC,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /message.php?id=2 [L,NC]
if you want a specific 404 you need to catch it or create the 404 HTML that is loaded within apache.
look at: catching all invalid URLs
They've suggested using the ErrorDocument within the apache.
I have a website with the following folder structure:
website >> magazine >> news
Inside news my files include:
htaccess, updates.php, articles.php & article.php
So my htaccess looks like:
Options -MultiViews
DirectoryIndex updates.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^updates updates.php
RewriteRule ^articles articles.php
RewriteRule ^updates/([\w-]+)/?$ updates.php?id=$1 [NC,L,QSA]
RewriteRule ^articles/([0-9]+)/?$ articles.php?currentpage=$1 [NC,L,QSA]
RewriteRule ^article/([0-9]+)/([\w-]+)/?$ article.php?id=$1&title=$2 [NC,L,QSA]
The problem(s) that I have is that when I visit website.uk/magazine/news/updates/1459967836 it shows the result for my article with ID 1460544406.
The code in my updates page is:
...
if(isset($_GET["id"])){$id = $_GET["id"];}else{
$id = "latest";
}
?>
<?php
if ($id == "latest"){$var = "ORDER BY added DESC LIMIT 1";}else{$var = "WHERE id = '$id'";}
?>
<?php
$posts_sql = "SELECT * FROM magazine_news_updates $var";
...
Does anyone know why when I visit 1459967836 I gewt shown the result for 1460544406.
Also, when I visit website.uk/magazine/news/article-add-form.php I get shown website.uk/magazine/news/articles, even though the URL is displayed correctly. Any Ideas?
** SOLVED **
By removing (
RewriteRule ^updates updates.php
RewriteRule ^articles articles.php
) the pages now show everything correctly!
I just started to learn htaccess and i'd like to rewrite my current urls from this:
http://www.url.com/?location=script
To:
http://www.url.com/script
So far i've managed to do this but now i want to have a directory with more controllers so i can have something like this:
http://www.url.com/script/method
Structure: Script directory --> method.php
Currently my directory structure for includes its like this:
assets-->client(directory):
login.php
logout.php
register.php
something.php
And i'd like to access these using a url like:
url.com/client/login
url.com/client/logout
url.com/client/register
url.com/client/something
My .htaccess:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?location=$1 [L]
</ifModule>
PHP based inclusion code:
####################################################################
# PARSE THE CURRENT PAGE #
####################################################################
$includeDir =".".DIRECTORY_SEPARATOR."assets/controllers".DIRECTORY_SEPARATOR;
$includeDefault = $includeDir."home.php";
if(isset($_GET['ajaxpage']) && !empty($_GET['ajaxpage'])){
$_GET['ajaxpage'] = str_replace("\0", '', $_GET['ajaxpage']);
$includeFile = basename(realpath($includeDir.$_GET['ajaxpage'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath)) {
include($includePath);
}
else{
include($includeDefault);
}
exit();
}
if(isset($_GET['location']) && !empty($_GET['location']))
{
$_GET['location'] = str_replace("\0", '', $_GET['location']);
$includeFile = basename(realpath($includeDir.$_GET['location'].".php"));
$includePath = $includeDir.$includeFile;
if(!empty($includeFile) && file_exists($includePath))
{
include($includePath);
}
else
{
include($includeDefault);
}
}
else
{
include($includeDefault);
}
All my controllers are in assets/controllers/ucp/login.php for example.
How about:
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^(/client/[a-zA-Z0-9_\-]+)$
RewriteRule ^[a-z]+ index.php?location=$2 [L]
</ifModule>
It does include a leading slash and doesn't have the PHP extension. But this can be altered in PHP to suit your needs.
Be wary though, your code gives access to all your PHP files. You might want to check $_GET['location'] against an array of allowed locations. Consider the following URL as example of how this could go wrong
http://example.com/index.php?location=../drop_database.php
I'm trying to hide the php page name in url which redirects after login by header function. So far I can hide the index file but can't hide the file which redirects after login. Here are my codes,
PHP script for after login events
$sql_login = mysql_query("SELECT * FROM sms_people WHERE username='$username' AND password='$password'");
$row = mysql_fetch_array($sql_login);
if ($row > 0 && $row[5] == 1) {
header('Location: adminpanel.php');
}
.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
How can I hide the files which redirects from header function by using .htaccess file? Need this help badly. Tnx.
there is an alternative way to redirect php files and hide them
for example
http://yourwebsite.com/user/login/
user part main user.php or you can change the file name
firstl, in your htaccess redirect to index php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
############### SEO ##########################
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
in your index.php file
$rootfolder="parts"
if(isset($_GET["url"])){
$part= explode("/", $_GET["url"]);
if(isset($part[0]))
$controller = ''.strtolower($part[0]).'';
if(isset($parca[1]))
$method = ''.strtolower($part[1]).'';
if(isset($parca[2]))
$id = ''.$part[2].'';
if( file_exists($rootfolder."/".$controller.php))
{
//you can call the file if it is exits
requre_once $rootfolder."/".$controller.php;
}else{
die("404 not found !");
}
}
Ok got a solution. I changed the information in header function & placed the file corresponding to the given information in .htaccess file. Here are the codes,
PHP Script
if ($row > 0 && $row[5] == 1) {
header('Location: AdminPanel'); // Instead of adminpanel.php
}
.htaccess
RewriteRule ^AdminPanel/?$ adminpanel.php [R,NC,L] // Added this line.
Tnx for all your efforts btw.
I have a site in localhost that uses a shortened URL's from
http://localhost/Portal/mysite/profile.php?id=1
to
http://localhost/Portal/mysite/profile/1/this_is_id
Using the below .htaccess below
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteRule ^profile/([0-9]+)/.*$ /Portal/mysite/profile.php?id=$1 [QSA,L,NC]
But, I need the URL to be instead as http://localhost/Portal/mysite/this_is_id
This is all in localhost, that is why .com does not appear, but the site file is mysite
So, I tried sending a link that is in my mysite/index.php to mysite/profile.php with $id but it is not working. Anyway simple suggestion would be fine, thanks
UPDATE
Ok, I did as both you asked, but this is the function that is sending a user from index page to profile page, and I do not know how to modify it, even though I have done what both of you asked.
// sql query goes here.
foreach ($stmt as $row) {
$url = "/profile/$row[id]/".preg_replace('/[^a-zA-Z0-9-_]/', '-', $row['company']);
echo "<h4>". substr($row['company'], 0,26)."</h4>
";
}
the echo is the link, now when I press on that link, It takes me to page not found
UPDATE 2
this is the image of my directory, the link is in index.php and when clicked it sends me to profile.php all the above file is situated in WAMP/www/Portal/mysite
Try this:
#for subdirectory
RewriteBase /Portal/mysite/
#for localhost
#RewriteBase /
#RewriteRule ^profile/([0-9]+)$ profile.php?id=$1 [QSA,L,NC]
#RewriteRule ^profile/([0-9]+)/([a-zA-Z0-9\-]+)$ profile.php?id=$1 [QSA,L,NC]
RewriteRule ^profile/([a-zA-Z0-9\-]+)$ profile.php?id=$1 [QSA,L,NC]
.htaccess and profile.php in Portal/Site directory.
UPDATE:
foreach ($stmt as $row) {
$url = "/profile/".preg_replace('/[^a-zA-Z0-9-_]/', '-', $row['company']) . "-" . $row[id];
echo "<h4>". substr($row['company'], 0,26)."</h4>";
}
profile.php
var_dump($_GET);
if(isset($_GET['id'])) {
$params = explode('-', $_GET['id']);
$id = (int)array_pop($params);
var_dump($id);
}
.htaccess
RewriteEngine On
RewriteBase /Portal/mysite/
RewriteRule ^profile/([a-zA-Z0-9\-]+)$ profile.php?id=$1 [QSA,L,NC]
run your link ( f.e.: localhost/Portal/mysite/profile/This-is-name-12 ) and result:
array (size=1) 'id' => string 'This-is-name-12' (length=15)
int 12
12 is your profile id.
Try:
RewriteRule ^([0-9]+)$ profile.php?id=$1 [QSA,L,NC]
if the Rule (.htaccess) is in your /Portal/mysite/ directory, and profile.php is there as well.