Display posts without using GET in PHP - php

How does one make a view contain without using the get variable in PHP
I am trying to display post/id like this
www.domain.com/view/1234
instead of
www.domain.com/view.php?id=1234

Assuming you have an Apache server with the mod_rewrite module enabled, you can create a new .htaccess file with the following content:
// First of all we want to set the FollowSymlinks option,
// and turn the RewriteEngine on
Options +FollowSymlinks
RewriteEngine on
// This is the rule that changes the URL
RewriteRule ^view/([^/.]+)/?$ view.php?id=$1 [L]
This would do exactly like you wanted and redirects any /view/123 to view.php?id=123.

This is done via webserver url rewriting.
Here's some references for Apache (using mod_rewrite):
Apache.Org
(http://coding.smashingmagazine.com/2011/11/02/introduction-to-url-rewriting/)

If what you're looking for is the ability to parse the uri, you can use this:
$uri = $_SERVER["REQUEST_URI"]
$parts = explode("/",$uri)
The last element in your $parts array should be your view id.
Drupal(1) contains the following function to do exactly this:
function arg($index) {
static $arguments, $q;
if (empty($arguments) || $q != $_GET['q']) {
$arguments = explode('/', $_GET['q']);
$q = $_GET['q'];
}
if (isset($arguments[$index])) {
return $arguments[$index];
}
}
(1) I do not advocate using Drupal, I merely use it as an example.

You need to rewrite the URL with htaccess and intercept it somehow using PHP and loading the file from somewhere.
Rewrite URL with mod_rewrite (i.e.: domain.com/23234234/0 to domain.com?id=23234234&nr=0)
Make a call to the database requesting the post with id 23234234
Show it to the user
Is it what are you looking for?
(based on a previous answer)

Related

How to check what is Written in the url bar and navigate to a certain page in php?

What i want to be able to do is if someone writes in the url bar
www.somesite.com/test
test is like the Username name so it will be www.somesite.com/Username
then page navigate to another and display data from the data where the username is the same
The page will navigate to another page and display data from he database
is this possible first of?
And this is what i have write now it not much, and i am also new to PHP
$url = 'http://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url2 = "http://www.somesite.com/"$databaseVar1=mysql_result($result,$i,"username");
if ($url) == ($url2)
{
header("location: http://somesite.com/viewcontent.php");
}
else
{
//not found
}
Am i Able to do something like this? Any help will be great-full thanks
In PHP this is not exactly possible, however, you can do the following:
www.somesite.com/index.php/test
Apache will open index.php and you can use something like $_SERVER['REQUEST_URI'] to navigate from there
You will either need to use a rewrite rule in .htaccess to redirect all requests to index.php. Index.php can then use
Or you can put a ? before the username. Then index.php will automatically get all requests. The $_SERVER['querystring'] will then receive the username.
Taken some assumptions (due to lack of complete source code in your question):
mysql connection is estabilished
proper query has been sent to mysql server
variable $i is set to meaningful value
www server is configured to rewrite requests to index.php
You only have to compare REQUEST_URI with "username" column value taken from database.
Header "Location: ..." must have capital letter "L".
And avoid usage of "==" operator when comparing strings in PHP, strcmp() function is more reliable - "==" operator tests identity not equality - it's useful to compare numeric values.
You can define the index.php as the application dispatcher and create an .htaccess file that will redirect the requests to it:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]
index.php:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
if ($page == '/some/page/') include('file_that_handles_this_request.php');
Or you could use this to create instances of classes and call methods:
$page = $_SERVER['REQUEST_URI']; //=> '/Users/show'
list($class, $method) = explode($page);
$object = new $class();
$object->{$method}();
you should use mvc architecture to get perfect as you want.
the url in mvc is like same as you want. You can call the method with the parameter from url directly. Here is a url pattern in mvc architecture -
www.yoursitename.com/controller/methodname/parameter

send each request to appropriate controller

I want to make a small web application, and I'm not sure how to go about this.
What I want to do is send every request to the right controller. Kind of how CodeIgniter does it.
So if user asks for domain.com/video/details
I want my bootstrap (index?) file to send him to the "Video" controller class and call the "details" method in that class.
If the user asks for domain.com/profile/edit I want to send him to the "Profile" controller class and call the "edit" method in that class.
Can someone explain how I should do this? I have some experience using MVC frameworks, but have never "written" something with MVC myself.
Thanks!
Edit: I understand now how the url points to the right Controller, but I don't see where the object instance of the Controller is made, to call the right method?
You need to re-route your requests. Using apache, this can be done using mod_rewrite.
For example, add a .htaccess file to your public base directory and add the following:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]
This will redirect users trying to access
/profile/edit
to
index.php?rt=profile/edit
In index.php, you can access the $_GET['rt'] to determine which controller and action has been requested.
Use mod-rewrite (.htaccess) to
rewrite the url from
www.example.com/taco to
www.example.com/index.php?taco/
in index.php, grab the first URL
parameter key, use that to route to
the correct url. As it will look
like "taco/"
You may want to add / to the front
and back if it doesn't exist. As
this will normalize the urls and
make life easier
If you want to preserve the ability
to have traditional query strings.
Inspect the URL directly and take
the query string portion. break that
on ?, which will leave you with the
routing info in key 0 and the rest
in key 1. split that on &, then
split each of those on = and set the
first to the key and the second to
the value of an array. Replace $_GET
with that array.
Example:
$path = explode("?", $_SERVER["QUERY_STRING"],2);
$url = $path[0];
if(substr($url,0,1) != "/")
{
$url = "/".$url;
}
if(substr($url,-1,1) != "/")
{
$url = $url."/";
}
unset($_GET);
foreach(explode("&", $path[1]) as $pair)
{
$get = explode("=", $pair, 2);
$_GET[$get[0]] = $get[1];
}
// Define the Query String Path
define("QS_PATH", $url);
Depending on what you want to do or how much work you want to do, another option versus writing your own MVC is to use Zend Framework. It does exactly what you're asking for and more. You still need to configure URL rewriting as mentioned in the other answers, but it quick and easy.
Even if you're not interested in Zend Framework, the following link can help you configure your rewrite rules: http://framework.zend.com/wiki/display/ZFDEV/Configuring%2BYour%2BURL%2BRewriter

SEO Url Redirect/Rewrite Using Database Managed Links

I have searched left and right.
And I am trying to find a script or a method on how I can store links in database and use them for redirection.
This is an E-commerce project and I am looking for something to manage product and system URL from database.
Something similar like magento does.
Basically anything after the domain say like domain.com/demo/12/my_iphone
so now demo/12/my_iphone will be sent to database for query and in databases there will be a destination URL which could be productlisting.php?searchstring=iphones
The user will see link domain.com/demo/12/my_iphone but actually he will be seing productlisting.php?searchstring=iphones
Basically demo/12/my_iphone = productlisting.php?searchstring=iphones
And tomorrow if the user wants to edit demo/12/my_iphone to demo/12/myiphone he can just do so using simple form which will update in the database.
How can I achieve this?
Use mod_rewrite in apache in combination with a PHP script.
1) Make a .htaccess file and put it in a folder, say www.yourdomain.com/a/.htaccess
Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteRule .* index.php?%{QUERY_STRING} [L]
2) Create an index.php that handles all requests
(psaudo-code)
<?php
/**
* This script is simply parsing the url used, /demo/12/my_iphone
*/
require_once('library.php');
$request_uri = $_SERVER['REQUEST_URI'];
// parse $request_uri by splitting on slashes /
$params = my_parse_function($request_uri); // <= parse_url() is helpful here!
$param1 = $params[0]; // "demo"
$param2 = $params[1]; // "12";
$param3 = $params[2]; // "my_iphone";
// db-lookup based on the request
$url = fetchUrlFromDB($param1, $param2, $param3);
if($url){
header('Location: '.$url); // $url = "productlisting.php?searchstring=iphones"
die();
}
else{
echo "invalid parameters";
}
?>
It wouldn't be difficult to program such a solution if it comes to that. You could grab the uri from $_SERVER['REQUEST_URI'] and pass it to parse_url to grab the path. Then use the path to query against the database.

Call PHP Function based on URI

I am looking to create a simple php script that based on the URI, it will call a certain function.
Instead of having a bunch of if statements, I would like to be able to visit:
/dev/view/posts/
and it would call a 'posts' function I have created in the PHP script.
Any help would be greatly appreciated.
Thanks!
Are you using a framework? they do this sort of thing for you.
you need to use mod_rewrite in apache to do this.
Basically you take /dev/view/posts
and rewrite it to
/dev/view.php?page=posts
RewriteEngine On
RewriteRule ^/dev/view/posts/(.*)$ /dev/view?page=$1
in view.php
switch($_REQUEST['page'])
{
case 'posts':
// call posts
echo posts();
break;
}
EDIT made this call whatever function is called "page"
You probably want to use a framework to do this because there are security implications. but very simply you can do this:
if (array_key_exists('page',$_REQUEST))
{
$f = $_REQUEST['page'];
if (is_callable($f))
{
call_user_func($f);
}
}
Note there are MUCH better ways of doing this! You should be using a framework!!!
Take a look at the call_user_func function documentation.
$functions['/dev/view/posts'] = 'function_a';
$functions['/dev/view/comments'] = 'function_b';
$functions['/dev/view/notes'] = 'function_c';
$uri = '/dev/view/comments';
call_user_func($functions[$uri]);
What you are looking for is a form of URL rewriting on your web server. For instance, if you are using Apache you should lookup mod_rewrite. An example of what your rule might look like:
RewriteEngine On
RewriteRule ^/dev/view/posts/(.*)$ /posts.php?id=$1
But I'm assuming that you are wanting to have a trailing post ID or similar so that you can use this for multiple posts URLs.

How To rewrite a url with PHP?

Let' say for example one of my members is to http://www.example.com/members/893674.php. How do I let them customize there url so it can be for example, http://www.example.com/myname
I guess what I want is for my members to have there own customized url. Is there a better way to do this by reorganizing my files.
You could use a Front Controller, it's a common solution for making custom URLs and is used in all languages, not just PHP. Here's a guide: http://www.oreillynet.com/pub/a/php/2004/07/08/front_controller.html
Essentially you would create an index.php file that is called for every URL, its job is to parse the URL and determine which code to run base on the URL's contents. So, on your site your URLs would be something like: http://www.example.com/index.php/myname or http://www.example.com/index.php/about-us or http://www.example.com/index.php/contact-us and so on. index.php is called for ALL URLs.
You can remove index.php from the URL using mod_rewrite, see here: http://www.wil-linssen.com/expressionengine-removing-indexphp/
Add a re-write rule to point everything to index.php. Then inside of your index.php, parse the url and grab myname. Lookup a path to myname in somekinda table and include that path
RewriteEngine on
RewriteRule ^.*$ index.php [L,QSA]
index.php:
$myname = $_SERVER['REQUEST_URI'];
$myname = ltrim($myname, '/'); //strip leading slash if need be.
$realpath = LookupNameToPath($myname);
include($realpath);
create a new file and change it name to (.htaccess) and put this apache commands (just for example) into it :
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^profile/([0-9]*)$ members.php?id=$1
You must create a rewrite rule that point from http://www.example.com/myname to something like http://www.example.com/user.php?uname=myname.
In '.htaccess':
RewriteEngine on
RewriteRule ^/(.*)$ /user.php?uname=$1
# SourceURL TargetURL
Then you create a 'user.php', that load user information from 'uname' GET variable.
See from your question, you may already have user page based on user id (i.e., '893674.php') so you make redirect it there.
But I do not suggest it as redirect will change the URL on the location bar.
Another way (if you already have '893674.php') is to include it.
The best way though, is to show the information of the user (or whatever you do with it) right in that page.
For example:
<?phg
vat $UName = $_GET['uname'];
var $User = new User($UName);
$User->showInfo();
?>
you need apache’s mod_rewrite for that. with php alone you won’t have any luck.
see: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

Categories