I've got a page with the following url: website.com/foo/bar
Where foo is the page's php file and bar is the corresponding id to be used to pull in the data from the database.
I'm not using any sort of framework trickery. Just an htaccess to remove the .php and extensions and to process the page foo.php with the id as its not in a sub-folder.
Anyways, bar is just a number (like I said corresponds with database row id). For SEO and general readability in a users history I want to go to the more popular website.com/foo/this-is-the-name format (what is this format called??).
Currently my code is:
require('neou_cms/framework/framework.php');
$id = filter(basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
// no id
if (empty($id)) {
header('Location: ../portfolio');
}
$projects = Nemesis::select("*", "projects", "published = '1' AND id = {$id}");
$row_projects = $projects->fetch_assoc();
$totalRows_projects = $projects->num_rows;
// no results, bad id
if ($totalRows_projects <= 0) {
header('Location: ../portfolio');
}
If figure I would do the following (1) make it so that the pages linking to foo instead go to the page title e.g. /this-is-the-name (2) in foo i'd make it so that $id removes the dashes from the name and searches the database for the row using a select statement and the title.
However I feel like this is slow... Is there a better way to do it that wouldn't require me changing the current flow?
Your approach is fine. The this-is-the-name part of your url (website.com/foo/this-is-the-name) is commonly called a "slug". If you'll be querying a database table on the slug, just make sure the slug column has an index and the query should perform reasonably well.
I would also like to point out that you have a SQL injection vulnerability in the code you've posted. Consider binding $id as a parameter in a parameterized query instead of dynamically including it in a where clause.
Related
I'm trying to build a single pages.php file which I can pass slug information too and use mod-rewrite to make database output look like actual pages.
The problem is that the code works but only with integers being passed. If I pass the page_id it will make the call and work, if I pass page_slug it will fail.
Here is my rewrite rule
RewriteRule ^service/(.*)$ pages.php?pid=$1 [QSA,L]
And here is the select query in pages.php to which I'm using require_once("Database.php"); to call the database file.
$sql = "
SELECT
page_title,
page_html_title,
page_slug,
page_content
FROM pages
WHERE page_slug = $pid
";
$q = $db->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$r = $q->fetch();
The data is put into html in following matter {$r['page_title']}
Paste for pages.php http://pastebin.com/qA7zzvnY
Paste for Database.php http://pastebin.com/8pqXbzby
Here is database tables
Known problem.
SELECT page_slug
returns empty page, with no error or source code anywhere.
SELECT page_id
returns the page truth pages.php?pid=zzzzzz or rewrite service/zzzzz.html I'm not sure why I can't pull page slug from database when I have done it in past with usernames and other random data. But in the provided $sql code it does not want to work.
You need single quotes (or properly escaped double quotes) around $pid in the query. Also, as pointed out in the comments, you are wide open to SQL injection and need to address that immediately.
I have a database with just over 800 data.
product table
pid name p_page
1 money money.php
2 gold gold.php
3 .
. .
. .
800 .
I have 2 pages...
product_item.php
<div class="button">
View
</div>`
when you click view the product info is pass to product.php
in here i have
if (isset($_GET['pid'])) {
depending on what product the user clicked on the URL might look like something below but the 44 will change to whatever id
http://www.example.x10.mx/money.php?pid=44
the problem with this, is that money.php have a different layout to the other pages and if I change 44 to 68, the product info will show on the page but the layout will not look good.
My question
what is the best way for me to stop users from being able to change the url.
I want to encrypt all my pid in the url so it will look something like
http://www.example.x10.mx//money.php?sel=the product name here or 4 letters or anything
I just want to take away pid from the url.
Please help me. If you dont understand my question please ask in the comment and try and say what you think you understand.
Edited to show my fetch function
$php = "php/";
$apages = "account/";
$bpages = "booking/";
$gpages = "general/";
$ppages = "product/";
// Global functions
function fetchdir($dir)
{
$protocol = $GLOBALS['protocol'];
$host = $GLOBALS['host'];
($dir == $GLOBALS['apages'] || $dir == $GLOBALS['bpages'] || $dir == $GLOBALS['ppages'] || $dir == $GLOBALS['gpages'] ? $branch = $GLOBALS['pagebranch'] : $branch = $GLOBALS['branch']);
echo $protocol.$host.$branch.$dir;
}
Thanks
p.s. I dont know if this can be done in .htaccess but i think it can be done in php
Some clarification:
I have a url which looks like this
www.example.com/account/product.php?pid=1
the problem with this is that someone can change 1 or any number and if they is a pid in the database with that number it will get the items information and display on the page. Which I don't want to happen because not all product are meant to be display in some pages.
In the papge which i show all my available product. I simple uses a SELECT statement and then echo what I need in some div.
In that page I have a view button.
$stmt = $conn->prepare("SELECT * FROM Product WHERE Type = 'shoes'");
$stmt->execute();
$i = 0;
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = ($row['pid']);
$product_page ($row['dir_page']);
<div class="button" >
<a href = "<?php fetchdir($apages) ?><?echo $product_page?ProdID=<?php echo $id>" > View</a >
</div >
}
Depending on the page that information is getting sent to when you click on view I use Get method
<?php
if (isset($_GET['pid'])) {
// Connect to the MySQL database
dbconnect();
$id = preg_replace('#[^0-9]#i', '', $_GET['pid']);
}
If you notice in my select statement used type to show only the product which type is shoes. I have other types as well, which as their other pages. Now the problem is if i change the pid to any page that doesn't have a type of shoes or if an in the other pages and enter a pid which type is shoes or anything, the information from that page will still render. Which I don't want to happen.
My question
how can i stop users from changing that pid and even if they change it. they will still be on the same page?
The problem isn't having the PID in the URL, it is having the template name in the URL.
Store the template name in the database (you are doing this already), and use that to determine what HTML to wrap the data in instead of putting it (money.php) in the URL.
Move your templates out of the web root (they shouldn't be hit by users directly), have a single index.php and then include() the template based on the data in the database.
You cannot prevent someone from changing the URL or from requesting arbitrary URLs. Your server (i.e. your app) has to decide how to respond to an invalid request. If you don't want to display certain things publicly, flag them as such in your database, test for that flag and simply refuse to output anything if that flag is hit.
Make the server respond negatively if something doesn't fit your conditions; don't expect the user to behave correctly.
Assuming that PID is a autoincrement value, you can still obfuscate it. Add another column in the table that contains a randomly-generated key (using uniqid or some derivative). Then use that key in your URL. You'll get something like: www.example.com/account/product.php?pid=II8GypI6H93Ij. This doesn't guarantee that someone won't find it, but it's good enough in most instances.
Check for allowance in the Database
Depending on your level of programming skills, in the database you could add a field or a relational table that relates the ID of the pages to allowed page templates (I'm guessing you're talking about templates.)
Then in the code you can make it so the page checks this database to see if the page contents are allowed to show. Something like:
$query1 = "SELECT * FROM Product WHERE Type = 'shoes' and allowedTemplate='1'";
This way you won't have to hardcode everything into the code itself. On the backend (if there is a CMS) then you could have checkboxes indicating the relationships to the templates and prefill them by default.
You'll need to make the site so something with that stuff though.
Your other option
You could use clean urls (which used to be better for SEO) to show real words instead of the IDs. Then you can use .htaccess tricks to convert the URIs to their ID counterparts with a dynamic RewriteMap.
When i click on my table results from an individual sql query.
$zip = mysql_real_escape_string($_GET['zip1']);
$near = "select id, first, last, trainer_address1, CITY, STATE, trainer_zip "
"from event.ACS.trainer where trainer zip ='{$zip}'";
echo lookup_gen::query_results_table($near, matry::base_to('acs/trainer/edit&trainer_id'));
query_results_table just builds the table and rows and allows individual linking for whatever result/row is clicked on.
matry::base_to just Links from the base path.
return A link from the base path to the specified path.
the current page i'm on is:
index.php?q=event/form&id=19471
it has this id variable in the $_GET as shown above.
When i click through on my query_results_table i've set up matry::base_to to link me to
index.php?q=acs/trainer/edit&trainer_id&id=19471
How can i drop the &id=19471 in the end of that url.
Should i use unset or is there a more concise way of going about it, if any at all?
Additionally, if anyone would like me to post the query_results_table function or the matry::base_to function, i'd be more than happy too. Hope I can get this resolved. Thank you.
I have small problem.
I've coded a full website in php using CodeIgniter framework. One of my modules is search module, it contains text input with keyword and three select lists with filtering criterias.
That's ok, when I'm searching something - result's listing pagination is done via URL like that:
mysite.com/$keyword/$criteria1/$criteria2/$criteria3/$offset
works like a charm.
But when I'm entering into one of my images (it's image gallery) I want to have an option to go into NEXT and PREVIOUS image from my search results - the ones which I entered this image from.
I'm solving this case now in this way - I have session table called 'search_conditions' and I'm storing values of keyword and my three criterias there, but that's quite not comfortable, because why if someone opens second window and search something else there?
Then all of his searches in another windows or tabs are getting the same criteria - because with every new search, user overwrite the session value.
My next and previous functions:
public function next($count)
{
$search = $this->session->userdata('search_conditions'); //getting session table and overwriting it
$catid = isset($search['catid'])?$search['catid']:'0';
$brandid = isset($search['brandid'])?$search['brandid']:'0';
$prodid = isset($search['prodid'])?$search['prodid']:'0';
$keyword = isset($search['keyword'])?$search['keyword']:'';
$res = $this->search_model->main_search($keyword, $catid, $brandid, $prodid, $count, 1);
}
public function previous($count)
{
$search = $this->session->userdata('search_conditions');
$catid = isset($search['catid'])?$search['catid']:'0';
$brandid = isset($search['brandid'])?$search['brandid']:'0';
$prodid = isset($search['prodid'])?$search['prodid']:'0';
$keyword = isset($search['keyword'])?$search['keyword']:'';
$res = $this->search_model->main_search($keyword, $catid, $brandid, $prodid, $count-2, 1);
}
Can you recommend me some other, more comfortable solution, because this seems not to be good...
: )
Thank you!
Add an index to the $search_conditions variable:
$search_conditions[1]['catid']
$search_conditions[1]['brandid']
...
then refer to it with a controller's or config variable. This way you can allow one session to store multiple search conditions.
But I would recommend you drop storing the search condition in session. Instead, just pass it with the URI. Session data, in the case you describe, work as an intermediary; you don't need it. Use the Pagination Class and pass the search page number, not the direction (next or previous) to the URI.
Do not worry that the URI may look ugly - it only depends on what user searches for, and it's still friendly to share. Your only concern is if the GET string does not extend the limited length.
Pull the segments from the URI in your next() and previous() functions. Use the codeigniter URL helper. That should allow you to pass the different search criterion as variables to the next page, this would also remove your need to use the session.
I need something simple; I have page where a user clicks an author to see the books associated with that author. On my page displaying the list of books for the author, I want a simple HTML title saying: 'The books for: AUTHORNAME'
I can get the page to display author ID but not the name. When the user clicks the link in the previous page of the author, it looks likes this:
<?php echo $row['authorname']?>
And then on the 'viewauthorbooks.php?author_id=23' I have declared this at the start:
$author_id = $_GET['author_id'];
$authorname = $_GET['authorname'];
And finally, 'The books for: AUTHORNAME, where it says AUTHORNAME, I have this:
echo $authorname
(With PHP tags, buts its not letting me put them in!) And this doesnt show anything, however if I change it to author_id, it displays the correct author ID that has been clicked, but its not exactly user friendly!! Can anyone help me out!
You could pull the author_id from the query string as you did using $_GET but beware you will need to validate what is coming through by the query. I hope you can see that without validation how bad of a security hole this is.
I am at work at the moment, but this is a quick example that should give you what you need without sanitizing your query.
$id = intval($_GET['author_id']);
// of course, perform more validation checks
// just don't assume its safe.
$sql = "SELECT authorname FROM authors_tb WHERE author_id=" . $id;
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "The books for: " . $row['authorname'];
}
The reason why your approach wasn't working was because you utilize the $_GET URL parameter passing for author_name where you weren't supplying the parameters in the URL, just the author_id.
You don't send it in the query string, thus you can't get it from the $_GET array.
Just request it from the database using id.
An important note: Always use htmlspacialchars() when you display the data, coming from the client side.
This is because you do not define the author name in your get.
You should make the following your url:
<?php echo $row['authorname']?>
Or rather select the data from the database again, on the new page, using the ID you retrieved from the URI.
Author name won't be in $_GET. As your code stands, you only use it as the link title. It is no where in the address. Try this instead:
<?php echo $row['authorname']?>
It would be better to re-request it from the database using the author_id though.
EDIT:
To explain the problem in more detail. You have two pages, the new.php page and the viewauthorbooks.php page. You're sending users from the new page to the view page using the link you posted, right?
The problem with that is, your link assigns one variable in get. Here's the query string it would generate:
viewauthorbooks.php?author_id=13
What that will do is send the user to viewauthorbooks and place the value '13' in the $_GET variable: $_GET['author_id']. That is why the author_id is there and displays on viewauthorbooks. However, authorname is never passed to viewauthorbooks, it isn't in $_GET['authorname'] because you never set $_GET['authorname']. If you want it to be in $_GET, then you need your query string to look like this:
viewauthorbooks.php?author_id=13&authorname=bob
You can accomplish that using the new HTML code for the link I posted above. Look at it closely, there's a key difference from the one you have now.
However, it is generally discouraged to pass data through GET, because the query string is displayed to the user and it leaves you open to injection attacks. A better way to do this would be to use the author_id you are already passing to viewauthorbooks.php to retrieve the authorname from the database again. You can use the same code you used on the new.php page.