I'm using cpanel and php to create my website.
how i can get id from url http://example.com/id
problem is that when i'm trying to get url , im redirecting to file with id name 404 error !
and i can't get path in index.php page ?
for example when i try to get this url
http://example.com/01OWUY
i want to get 01OWUY with
$link .= $_SERVER['REQUEST_URI'];
code but i'm going to a 404 error
update :
every user have a id
with this id he can see her info
for example user with id 01OWUY can see her info from database
like this ->
<?php
require 'config.php';
//Database connection
$conn = mysqli_connect(SERVERNAME, USERNAME, PASSWORD, DBNAME);
$user = handle_user($conn, $_SERVER['REQUEST_URI'])
?>
and the function is this ->
// Return true if link is active
function handle_user($conn, $linkId)
{
$sql = "SELECT *FROM users WHERE link_id = '" . $linkId . "'";
$result = $conn->query($sql);
// get user data from db
if ($result->num_rows > 0) {
return $result;
}
return false;
}
but i get a 404 error !!!
You will need to load index.php if the file does not exist.
this is a very common practice in php frameworks like Laravel.
.htaccess file
# Not for real file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
for this to work you must have mod_rewrite enabled
Then you will have the data available in your index.php file.
you will still need to sanitize the input $_SERVER["REQUEST_URI"]
Recommendation for lightweight framework includes routing features:
Lumen
https://lumen.laravel.com/
Related
I know that similar questions were already asked, but i could not find any information for my specific "problem".
What i want to do is the following in a very dynamic way, which means that a "SuperUser" should be able to define new routes in a admin interface:
If a user enters http://www.example.com/nice-url/
he should get redirected to http://www.example.com/category.php?id=123 without changing the url.
Now there are a few ways i can achieve this. Either i use .htaccess like this:
RewriteEngine on
RewriteRule ^nice-url category.php?id=123 [L]
This works, but is not very dynamic. I would need to let a php script append new rules at the bottom which is not something i would like to do.
Or this:
.htaccess
FallbackResource /process.php
process.php
$path = ltrim($_SERVER['REQUEST_URI'], '/');
$elements = explode('/', $path);
if(count($elements) == 0) {
header("Location: http://www.example.com");
exit;
}
$sql = sprintf("SELECT Target FROM urlrewrites WHERE Source = '%s' LIMIT 1", array_shift($elements));
$result = execQuery($sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$target = $row['Target'];
header("Location: ".$target);
exit;
This also works, but sadly the url in the address bar gets changed. Is there a way in the middle of both? Having the flexibilty of PHP and the "silentness" of RewriteEngine? How do great CMS like joomla do it? Do they generate a htaccess file for each new page you create?
Thanks!
You can have this code in root .htaccess:
RewriteEngine on
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ category.php?uri=$1 [L,QSA]
PS: Note this will route /nice-url to /category.php?uri=nice-url. Then inside category.php you can dip into your database and translate $_GET['uri'] to id.
It would be more dynamic if you use regular expressions. That's how it works in CMS systems like Joomla. Good idea is to install Joomla with 'nice' URLs on and look over .htacces file to get to know how does it work.
You can start here:
http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/
I have a domain www.domain.com and I have users who create profiles on it with a username. I have created a mechanism for them to access their public profile as www.domain.com/username using htaccess and some code in index.php file.
My .htaccess file looks like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L,QSA]
An additional feature is that users can select a design (1st or 2nd design) for their profile. So I store the chosen design in database and redirect www.domain.com/username to www.domain.com/1/ or www.domain.com/2/ and load the users profile on that URL. The logic for that in PHP is
//Load profile of user
$requestURI = $_SERVER['REQUEST_URI'];
$parameterArray = explode('/', $requestURI);
$username = $parameterArray[1];
if($username != "")
{
//Get chosen design from database and store it in a variable
$chosenDesign = *Selected design value*;
header("Location: $chosenDesign/");
}
else
{
//Username not found, hence redirect to error page
header("Location: 404.html");
}
My problem is, how can I redirect in such a way that the URL is always www.domain.com/username and it loads the design in the background (logically) and displays it.
It is not possible to hide information in a visible link.
You can use a link like that:
www.domain.com/username-1 redirect to -> www.domain.com/page.php?user=username&design=1
For that kind of stuff, I use cookies...
Actually my question can not understand directly but i think you can understand from following example
http://www.timestips.com/gadgets/samsung-galaxy-s4-specifications-and-features/
mashable.com/2012/12/11/responsive-web-design/
https://www.facebook.com/timestips
here in wordpress not any html or php page page or folder name gadgets is not available in server but when user visit this link open as html
i create my own website where uer login they visit there profile from
www.website.com/profile.php but i want to give every user to link like
www.website.com/userid like facebook
so i want to know only how to these url are open i develop whole website but i want update only /profile.php to /username
thanks for read it and answer it
Enable mod_rewrite, apache => htaccess
on this link i write after googling about this problem and i found solution
Click here for see this tutorial then read following steps
0) Question
I try to ask you like this :
i want to open page like facebook profile www.facebook.com/kaila.piyush
it get id from url and parse it to profile.php file and return featch data from database and show user to his profile
normally when we develope any website its link look like
www.website.com/profile.php?id=username
example.com/weblog/index.php?y=2000&m=11&d=23&id=5678
now we update with new style not rewrite we use www.website.com/username or example.com/weblog/2000/11/23/5678 as permalink
http://example.com/profile/userid (get a profile by the ID)
http://example.com/profile/username (get a profile by the username)
http://example.com/myprofile (get the profile of the currently logged-in user)
1) .htaccess
Create a .htaccess file in the root folder or update the existing one :
Options +FollowSymLinks
# Turn on the RewriteEngine
RewriteEngine On
# Rules
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
What does that do ?
If the request is for a real directory or file (one that exists on the server), index.php isn't served, else every url is redirected to index.php.
2) index.php
Now, we want to know what action to trigger, so we need to read the URL :
In index.php :
// index.php
// This is necessary when index.php is not in the root folder, but in some subfolder...
// We compare $requestURL and $scriptName to remove the inappropriate values
$requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
$scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
for ($i= 0; $i < sizeof($scriptName); $i++)
{
if ($requestURI[$i] == $scriptName[$i])
{
unset($requestURI[$i]);
}
}
$command = array_values($requestURI);
With the url http://example.com/profile/19837, $command would contain :
$command = array(
[0] => 'profile',
[1] => 19837,
[2] => ,
)
Now, we have to dispatch the URLs. We add this in the index.php :
// index.php
require_once("profile.php"); // We need this file
switch($command[0])
{
case ‘profile’ :
// We run the profile function from the profile.php file.
profile($command([1]);
break;
case ‘myprofile’ :
// We run the myProfile function from the profile.php file.
myProfile();
break;
default:
// Wrong page ! You could also redirect to your custom 404 page.
echo "404 Error : wrong page.";
break;
}
2) profile.php
Now in the profile.php file, we should have something like this :
// profile.php
function profile($chars)
{
// We check if $chars is an Integer (ie. an ID) or a String (ie. a potential username)
if (is_int($chars)) {
$id = $chars;
// Do the SQL to get the $user from his ID
// ........
} else {
$username = mysqli_real_escape_string($char);
// Do the SQL to get the $user from his username
// ...........
}
// Render your view with the $user variable
// .........
}
function myProfile()
{
// Get the currently logged-in user ID from the session :
$id = ....
// Run the above function :
profile($id);
}
If you want a WordPress site where each user has their own subsite you should look at BuddyPress. It's a WordPress social network plugin.
I think you are asking about clean urls?
You don't want to do this http://mysite.com/profile.php?id=foo
But you would like this http://mysite.com/foo
Where you pass the username, in this case 'foo' to some script so you can do something with it.
#godesign got it right by telling you that you need to enable mod_rewrite in your .htaccess file. There are a lot of interesting things you can do with it, and you should read up on it and regular expressions too.
This is what my .htaccess file looks like (modified for the example):
RewriteEngine On
RewriteRule ^([a-z]+)$ profile.php?id=$1 [L]
This takes whatever matches the regular expression - the ^([a-z]+)$ bit - and puts it into the $1 variable.
Read more:
http://wettone.com/code/clean-urls
http://corz.org/serv/tricks/htaccess2.php
http://www.branded3.com/blogs/htaccess-mod_rewrite-ultimate-guide/
I am attempting to publish a question which I know has many answers floating around Stack Overflow. However I, for some reason, just cannot seem to get the information in them to click. I will post my sources at the end of the question.
The question being, how can I pull a user_id from a URL & mod_rewrite it show the username.
Instead of this:
domain/user/index.php?user_id=1
I get this:
domain/username
I had customized other SO answers to my needs on my .htaccess file to this:
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
RewriteOptions MaxRedirects=1
RewriteCond %{REQUEST_FILENAME} -f [NC,OR]
RewriteCond %{REQUEST_FILENAME} -d [NC]
RewriteRule .* - [L]
RewriteRule ^user/([^/]+)$ index.php?user_id=$1
</IfModule>
The if statement at the top of my user page looks like this:
if (isset($_GET['user_id']) || isset($_GET['username']) && queryUserId($user_id)) {
// Render Page Content
} else {
header('Location: sign_up.php');
}
And my queryUsername functions looks like this:
function queryUsername($username) {
$conn = dbConnect('read');
$sql = "SELECT * FROM users WHERE user_id = '".$username."'";
$result = $conn->query($sql) or die(mysqli_error($conn));
$row = $result->fetch_assoc();
return $row['username'];
$username = $row['username'];
}
I have successfully implemented unique URL's for users, and am accessing Account Profiles just fine when appending different user_id's to my URL, so what am I missing to get the username written to the URL instead of variable strings and folder structure?
Cheers!
Other SO Questions:
Directly adding username to URL PHP
Get username from URL in PHP
Using mod rewrite to change URL with username variable
AddedBytes Article
URL Rewriting for Beginners
This line is wrong according to your information:
RewriteRule ^user/([^/]+)$ index.php?user_id=$1
It should at least be:
RewriteRule ^user/([^/]+)$ /user/index.php?user_id=$1 // for a url like domain/user/username
or using your description:
RewriteRule ^([^/]+)$ /user/index.php?user_id=$1 // for a url like domain/username
Also, you are not setting any variable with the name of username in the code you have shown, so the check for $_GET['username'] is unnecessary.
Your check in php should look something like:
if ( isset($_GET['user_id']) && queryUserId($_GET['user_id']) ) {
Apart from that you should not use the deprecated mysql_* functions and use prepared statements as you have an sql injection problem now.
Also note that using two return statements after each other only returns the first value.
Edit: There seems to be some confusion between the user ID and the username. If the value in the url is a username, you'd better call it username in both the .htaccess file and php to avoid confusion with the user ID:
RewriteRule ^([^/]+)$ /user/index.php?username=$1 // for a url like domain/username}
and
if ( isset($_GET['username']) && queryUserName($_GET['username']) ) {
in the function (using the deprecated functions just to illustrate...):
function queryUserName($username) {
$conn = dbConnect('read');
$sql = "SELECT * FROM users WHERE username = '".$username."'";
...
}
I am running into the following issue:
Our members have a desire for personalized sites directly from our primary domain in the form of http://www.example.com/membername. I am looking at possibly solutions in two ways but neither are ideal (will be explained below).
Method 1 - ?Member=
In this method, I simply create a custom URL and store the information in the member's database profile. For example: if I want my "custom" URL to be jm4, for a consumer to visit my site, they must type in http://www.example.com?Member=jm4.
The site, of course, does a $_GET['Member'] to lookup the member information, stores the primary data in Session from the index page, then redirects to a homepage. The consumer no longer sees the membername in the URL but instead sees all the page names for www.example.com as if they simply visited the parent domain to start (each member's page has custom information however).
While this method works it presents the following problems:
The URL is not nearly as easy as /jm4
and any errors typing out the
wildcard ?Members= will result in
page error. Also, This method keeps
that particular member's information
in session (which is necessary
browing from page to page on that
particular member domain) and
prevents somebody from simply typing
http://www.example.com?Member=name2 to
visit another site without clearing
their session or closing the browser.
Method 2 - /membername
While the preferred method, currently the only way we know how to create is to manually generate an index file in a subfolder, redirect to the primary index then allow the consumer to view the member's personal site.
For example, if I visit www.example.com/jm4, I am hitting the /jm4 folder which contains index.php. Within this file simply contains:
<?php
session_start();
ob_start();
$_SESSION['AgentNumber'] = "779562";
header("Location: ../index.php");
exit;
?>
the primary index recognizes this with:
<?php
session_start();
ob_start();
if ($_SESSION['MemberNumber'] == NULL) {
header("Location:ac/");
exit;
}
$conn = mysql_connect("localhost", "USER", "PW");
mysql_select_db("DB",$conn);
$sql = "SELECT * FROM table WHERE MemberNumber = $_SESSION[MemberNumber]";
$result = mysql_query($sql, $conn) or die(mysql_error());
while ($newArray = mysql_fetch_array($result)) {
$_SESSION['MemberName'] = $newArray['MemberName'];
$_SESSION['MemberPhone'] = $newArray['MemberPhone'];
$_SESSION['MemberMobile'] = $newArray['MemberMobile'];
$_SESSION['MemberFax'] = $newArray['MemberFax'];
$_SESSION['MemberEmail'] = $newArray['MemberEmail'];
$_SESSION['MemberAddress'] = $newArray['MemberAddress'];
$_SESSION['MemberCity'] = $newArray['MemberCity'];
$_SESSION['MemberState'] = $newArray['MemberState'];
$_SESSION['MemberZip'] = $newArray['MemberZip'];
$_SESSION['MemberAltName'] = $newArray['MemberAltName'];
}
mysql_close($conn);
header("Location: home/");
exit;
?>
We would certainly prefer to use the second method in terms of 'ease' for the member but keep running into the following issues:
We are forced to manually create a
sub-folder and unique index.php file
for each new member we onboard
While the above probably could be
automated (when new member creates
profile, automatically generate php
file and folder) but this is more
complicated and we don't want to
have 3000 subfolders on the primary
domain.
Has anybody run into similar issues? If so, how did you go about solving it? What would you recommend based on my details above? Any advice is appreciated.
Also - using as subdomain (membername.example.com) is not preferred because our current SSL does not allow for wildcards.
EDIT 1 - EXISTING .HTACCESS FILE
My existing .htaccess file on the site looks like this for reference:
ErrorDocument 404 /404.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [L]
RewriteRule ^(.*)$ /?Member=$1 [L]
You can do your prefered method by just adding some lines to the .htaccess in your root directory:
This site should get you started
Or this one
If you are using apache, then you could use mod_rewrite to change urls like http://host/membername to http://host/memberpage.php?name=membername.
You could use this in a .htaccess file for your second method. It will rewrite http://yoursite.com/membername to http://yoursite.com/?Member=membername
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /?Member=$1 [L]
</IfModule>