Facebook Like Custom Profile URL PHP - php

Making a website and I want to put in a custom profile URL for all the users on my site (like facebook).
On my website already, people have a page like http://sitename.com/profile.php?id=100224232
However, I want to make a mirror for those pages that relates to their username. For example, if you go to http://sitename.com/profile.php?id=100224232 it redirects to you http://sitename.com/myprofile
How would I go about doing this with PHP and Apache?

No folders, no index.php
Just take a look at this tutorial.
Edit :
This is just a summary.
0) Context
I'll assume that we want the following URLs :
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);
}
To conclude
I wish I was clear enough. I know this code is not pretty, and not in an OOP style, but it could give some ideas...

Related

pretty url static files not loading

I'm building a social network and my htaccess pretty url isn't loading the css/js/img/php files. The following rules work
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^login$ index.php?act=login [NC]
RewriteRule ^register$ index.php?act=register [NC]
RewriteRule ^forgot$ index.php?act=forgot [NC]
But the following rule works but doesn't load the css/js/img
RewriteRule ^user/(\w+)/?$ index.php?act=profile&user=$1 [NC]
What I'm I doing wrong? I don't have a base url set. The home page url is
http://localhost/myWebsite/source/
I also have the following logic in my controller which is included at the top of the index page
if ($isLogged == true) {
// check if page request set
if (isset($_GET['act'])) {
// valid pages
$pgeArray = array("stories", "hashtags", "media", "user", "search");
// check if page is valid
if (in_array($_GET['act'], $pgeArray)) {
// get page name request
$pgeReq = $_GET['act'];
}else {
// show registration page
$pgeReq = "home";
}
}else {
// show registration page
$pgeReq = "home";
}
}
else {
// check if page request set
if (isset($_GET['act'])) {
// valid pages
$pgeArray = array("register", "login", "forgot");
// check if page is valid
if (in_array($_GET['act'], $pgeArray)) {
// get page name request
$pgeReq = $_GET['act'];
}else {
// show registration page
$pgeReq = "login";
}
}else {
// show registration page
$pgeReq = "login";
}
}
All I had to do is specify a base url <base href="http://localhost/myWebsite/source/" />
`

Error 404 when routing

I'm trying to do my site like this tutorial http://www.codeigniter.com/user_guide/tutorial/static_pages.html
but have some problem with routing. I have page "createBook" for default and when I call localhost it's work! But when I do like localhost/createBook I have Error 404. What I'm doing wrong?
In my controller:
public function view($page = 'createBook')
{
if ( ! file_exists(APPPATH.'views/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$this->load->view($page);
}
routes.php file
$route['default_controller'] = 'Books/view';
$route['(:any)'] = 'Books/view/$1';
And I have view files in my views folder named Success and createBook
I don't really get your question but it seems to me that you are trying to call a controller named createBook from the url, but in your function it shows that if there is no views/createBook.php than show 404, maybe its why you get a 404, because your calling a controller as a view, i think your function should be like this :
public function view($page = 'createBook')
{
if ( ! file_exists(APPPATH.'controllers/' . $page . '.php'))
{
// Whoops, we don't have a page for that!
$this->output->set_status_header('404');
show_404();
}
$this->load->view($page);
}
If you want your url to look something like this :
example.com/view/book/3
Your controller should look like this :
class View extends CI_Controller
{
public function book($book_id)
{
//Search the database for records about a book with its id, and return the data
//and assign it to a variable(in this case $data) ex : $data["book-name"] = ...
//And on your view you can call these values using ex : echo $book-name
$this->load->view('books_view', $data);
}
}
And make sure your .htaccess file next to the index.php looks like something like this :
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
Then go to your config, and change this line to :
$config['index_page'] = '';
Now you can access all of your controllers this way :
http://www.example.com/controller_name

trying to get url values of my index.php file

Im starting to devellop a pagination system, and so I´ll need to get some numbers in my URL, but Im having
one problem.
I have a project root folder "project", inside this folder I have:
1 .htaccess file
1 index.php file, that is where I call my getHome() function, to include the correct page and is where I import css, javascripts files, etc
1 folder with name "tpl", and inside it, I have my other index.php file that is my homepage and my other php files (categories.php, contacts.php,...)
To acess my homepage, Im using this url: localhost/project/
And now Im trying to get the numbers I pass in URL with this code:
$page = $url[1];
$page = ($page ? $page : 1);
echo '<h1>'.$page.'</h1>';
The problem is,
If I use this code to get number that I pass in URL in my "categories.php" file, like this: "htttp://localhost/projet/categories/2" -> it's working fine, I get echo of "2" and I have my categories.php file included, but wih one problem, I have some images im my categories.php file and if I use localhost/project/categories I have my images included correctly, but If I use localhost/project/categories/test-1 I can get value I pass in my url and my categories page is included but my images dont appear, images just appear in localhost/project/categories.
If I use this code to get number that I pass in URL in my "index.php" file, like this "htttp://localhost/project/2" Im getting my page 404 error "tpl/404.php", that I include in my getHome() function.
Do you see some way, using my function getHome(), how I can get the number I pass in url, using for example localhost/project/3, and have my index.php file included normally, and dont have my 404 page tpl/404.php' included?
And also how I can my solve my images problem with my categories page?
This is my function getHome()
function getHome(){
$url = $_GET['url'];
$url = explode('/', $url);
$url[0] = ($url[0] == NULL ? 'index' : $url[0]);
if(file_exists('tpl/'.$url[0].'.php'))
{
require_once('tpl/'.$url[0].'.php');
}
else
{
require_once('tpl/404.php');
}
}
This is my .htaccess file:
RewriteEngine OnRewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1
Also, If I use index in my URL, like this: htttp://localhost/projet/index/2, it works, I can get my url value of "2" and I have my home page included correctly. But I´m trying to have just my htttp://localhost/project/2 and get the value I pass, in this case "2" with my homepage and not my 404 error page.
Try using array_pop to get the last value of url then check is_numeric
function getHome(){
$url = (isset($_GET['url'])) ? $_GET['url'] : $_SERVER['REQUEST_URI'];
$url = explode('/', $url);
$template = $url[0] == NULL ? 'index' : $url[0];
$last = array_pop($url);
$page = (is_numerica($last)) ? $last : 1;
if ($template == 'index') {
return $page;
}
if(file_exists("tpl/$template.php")) {
require_once("tpl/$template.php");
} else {
require_once('tpl/404.php');
}
}
$page = getHome(); // $page is used in index.php

Codeigniter Rest server Digest or Basic auth cant login

I'm using Phil Sturgeon’s REST Server. I'm having trouble to set up the basic or digest authentication. When calling the method i get the dialog that prompts for username and password even if i write in the correct username and password it wont accept it. How do i troubleshoot this ? Is it my web host that doesnt allow it ?
This is how i set up the auth in rest.php:
The rest is default.
$config['rest_auth'] = 'Basic';
$config['auth_source'] = '';
$config['rest_valid_logins'] = array('admin' => 'password');
I found the solution myself. I had to add this on my .htaccess file.
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
Sorry for writing in such an old thread. Thought it may save somebody's time.
Please note that this solution is for basic auth only. I have not tested this with digest auth.
I required to tweak #Tan's answer a bit to get the .htaccess to work.
I removed the [L] from RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L] and placed the rewrite rule just after RewriteEngine on
The .htaccess file:
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#Other rules follow
Next, I required to change the rest.php config file inside application/config directory. The changes I made are as follows:
$config['auth_source'] = 'ldap' to $config['auth_source'] = 'library',
$config['auth_library_class'] = '' to $config['auth_library_class'] = 'api_auth'
$config['auth_library_function'] = '' to $config['auth_library_function'] = 'login'
Then, I created a new library file named Api_auth.php having the following code:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Api_auth
{
public function login($username, $password) {
if($username == 'admin' && $password == '1234')
{
return true;
}
else
{
return false;
}
}
}
Hope this helps someone someday.
this didnt work for me but this did
for me It related the the sever running php as a fastCGI, not a php5_module, like your localhost does. ( to find this out run phpinfo - Server API: CGI/FastCGI )
here was the solution
http://ellislab.com/forums/viewthread/173823/#825912
.htaccess
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
libraries/REST_Controller.php
BEFORE
// most other servers
elseif ($this->input->server('HTTP_AUTHENTICATION'))
{
if (strpos(strtolower($this->input->server('HTTP_AUTHENTICATION')),'basic') === 0)
{
list($username,$password) = explode(':',base64_decode(substr($this->input- >server('HTTP_AUTHORIZATION'), 6)));
}
}
AFTER
// most other servers
elseif ( $this->input->server('HTTP_AUTHENTICATION') || $this->input- >server('REDIRECT_REMOTE_USER') )
{
$HTTP_SERVER_AUTH = ($this->input->server('HTTP_AUTHENTICATION')) ? $this->input->server('HTTP_AUTHENTICATION') : $this->input->server('REDIRECT_REMOTE_USER');
if (strpos(strtolower($HTTP_SERVER_AUTH),'basic') === 0)
{
list($username,$password) = explode(':',base64_decode(substr($HTTP_SERVER_AUTH, 6)));
}
}

404 page not found

I'm trying to figure out why I'm getting a 404 page now found when I load a page. I thought it was because of the file structure but now i'm not sure why.
myurl.com/mycms/modules/bios/quotes
Here's the file structure
root
root/mycms
root/mycms/application
root/mycms/application/modules
root/mycms/application/modules/bios/
root/mycms/application/modules/bios/controllers/quotes
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Quotes extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
//Config Defaults Start
$msgBoxMsgs = array(); //msgType = dl, info, warn, note, msg
$cssPageAddons = ''; //If you have extra CSS for this view append it here
$jsPageAddons = ''; //If you have extra JS for this view append it here
$metaAddons = ''; //Sometimes there is a need for additional Meta Data such in the case of Facebook addon's
$siteTitle = ''; //alter only if you need something other than the default for this view.
//Config Defaults Start
//examples of how to use the message box system (css not included).
//$msgBoxMsgs[] = array('msgType' => 'dl', 'theMsg' => 'This is a Blank Message Box...');
/**********************************************************Your Coding Logic Here, Start*/
// Checks to see if a session is active for user and shows corresponding view page
if ($this->kowauth->isLoggedIn())
{
$bodyContent = "testing"; //which view file
}
else
{
redirect('login', 'refresh');
}
$bodyType = "full"; //type of template
/***********************************************************Your Coding Logic Here, End*/
//Double checks if any default variables have been changed, Start.
//If msgBoxMsgs array has anything in it, if so displays it in view, else does nothing.
if (count($msgBoxMsgs) !== 0)
{
$msgBoxes = $this->msgboxes->buildMsgBoxesOutput(array('display' => 'show',
'msgs' => $msgBoxMsgs));
}
else
{
$msgBoxes = array('display' => 'none');
}
if ($siteTitle == '')
{
$siteTitle = $this->metatags->SiteTitle(); //reads
}
//Double checks if any default variables have been changed, End.
$this->data['msgBoxes'] = $msgBoxes;
$this->data['cssPageAddons'] = $cssPageAddons; //if there is any additional CSS to add from above Variable this will send it to the view.
$this->data['jsPageAddons'] = $jsPageAddons; //if there is any addictional JS to add from the above variable this will send it to the view.
$this->data['metaAddons'] = $metaAddons; //if there is any addictional meta data to add from the above variable this will send it to the view.
$this->data['pageMetaTags'] = $this->metatags->MetaTags(); //defaults can be changed via models/metatags.php
$this->data['siteTitle'] = $siteTitle; //defaults can be changed via models/metatags.php
$this->data['bodyType'] = $bodyType;
$this->data['bodyContent'] = $bodyContent;
$this->data['userData'] = $this->users->getUserByUserID($this->session->userdata('userID'));
$roster = $this->kowauth->getRosterList($this->data['userData']->usersRolesID);
$userRoster = array();
foreach ($roster AS $member)
{
$userRoster[$member->id] = $member->rosterName;
}
$this->data['userRoster'] = $userRoster;
$this->data['personalMessages'] = array($this->pmmodel->
getInboxUnreadMessagesCount($this->session->userdata('userID')), $this->pmmodel->
getInboxMessagesCount($this->session->userdata('userID')), $this->pmmodel->
getLast5Messages($this->session->userdata('userID')));
$this->load->view('cpanel/index', $this->data);
}
}
/* End of file quotes.php */
/* Location: ./application/modules/bios/controllers/quotes.php */
htacess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
RewriteEngine On
RewriteBase /kowmanager
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
I don't have any custom routes.
Usually when using modules with CI you don't need to include the word "modules" in your URL. Try accessing myurl.com/mycms/bios/quotes
It might be that your cms works in a different way, but generally the theory is that any controllers in your modules are accessed simply by using the module name and then the controller name. If you think about using CI without modules you wouldn't use the word "controllers" in the URL.

Categories