Get an id then put it into a href - php

I'm a bit new to this so sorry if this has been covered already but i'm going around in circles searching.
I've had a look around learn t how to edit htaccess and use the get function, I then even found a plugin called redirection that did similar.
What I would like to do is if I have a URL http://example.com/file.php?id=blue
is to grab the id which is "blue"
then in a href link dynamically add it to the end of another url
Link Example
If someone could help show me or point me in the right direction on how to get the id blue and add it into a href that would be great.
Many Thanks

You have to use $_GET. People might be dicks about it here - but I had a hard time when I was first learning to program too. You'll get it, don't worry.
This is how get works (at least, all you need to know about how it works):
if you have the file index.php
if you add a query string to the end of it like index.php?id=1
You can access id=1 by doing the following in your code:
$id = $_GET['id'];
Similarly if the query string contains the following index.php?id=1&page=5&par=3&club=putter&upnext=tigerwoods
On the left hand of the equal sign is the Key(id, page, par, club, upnext) and on the right side their value(1,5,3,putter,tigerwoods)
One thing to remember is that when retrieving numbers from the query string they will always be of the string type, so you cant do something like
if ( $_GET['page'] === 5 )
you'll have to do
if ( $_GET['page'] == 5 )
and to echo it into a link:
$club = $_GET['club'];
if ( $club == 'NRA' ) {
echo "Gun Show";
echo 'Buy tickets to my gunshow ^^';
}
Hope this helps!
You can also do things like set your website up so that it has one template and use the $_GET parameter to determine which files to include into the content sections of the site via a switch command. I do this, but not across my whole site. For my user control panel, I do this to simply include only the file necessary (change email, update password, delete account, update profile, etc)
Cah'piche?

Use the $_GET parameter.
YAY!!

Related

Prevent end user manipulating URL to change content on website, method GET PHP

I have a personal search site project I'm building, at the moment the only data that is being displayed on the website is data that is retrieved using SELECT queries and the GET method using the super global $_GET['example']. Now I don't know if I'm doing this wrong but some parts of my page are only displayed if certain GET variables in the URL are set or not empty. Below shows how my URL looks
EXAMPLE: index.php?search_category=guitar&main_category=9&postcode_val1=NP22&distance_default=100&submit=search
I have a lot of these if(isset($_GET['search_category']) type conditions in my website which are replied upon and show particular parts of content depending whether or not these are either true or false.
I have been on a lot of other websites that have similar URL's, I have tried to alter and manipulate these and the content does not break, alter or change in any way yet when i try this with my url it breaks my page and only certain parts of content gets displayed by being based on what is set. Is there some other layer of protection I should add, would using something like a rewrite rule help? The code below shows how I have wrote a drop down box based on what has been set In the URL but if a user edits the URL this is easily broken.
if(isset($_GET['search_category']) && isset($_GET['main_category']) &&
isset($_GET['postcode_val1']) && isset($_GET['distance_default']))
{
$stmt = $getFromUi->dispCategories();
echo "<option value='0'>All</option>";
echo "<option value='#'>-------------</option>";
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$selected = '';
if(!empty($_GET['main_category']) && $_GET['main_category'] == $row->cat_id)
{
$selected = ' selected="selected"';
}
echo '<option value="'.htmlentities($row->cat_id).'"'.$selected.'>'.htmlentities($row->cat_title).'</option>';
}
}
It will break because the strict nature of logic you use on your code. The && mark with isset mean any parameter you define not set will not evaluate to true. If the parameter is quite flexible why not ||.
If you need it to still evaluate all parameter try to do limit first if condition to main determiner. like $_GET['search_category'] and use the remaining $_GET['other_parameter'] as needed inside the block code of main if.
You would need to use a post method, so that this goes through as a request instead. In my experiance, get will only fetch the url you open - not actually pass anything through unless its in the URL.
Not sure if that made any sense, but check post out.
https://www.w3schools.com/tags/ref_httpmethods.asp is a good place to start to see the difference of get vs post.

how to check if bookmarks exist in html document

I've just designed my first form in HTML and a PHP page to display the results. In the form the user inputs some codes in response to some questions, a bit like a multiple choice, so for example, these are "ABC". The PHP page displays the code to the user as a link, which when clicked will go to a bookmark (a link within the same page) with the ID #ABC. This was achieved with simple manipulation of the PHP variable as follows:
<?php
$code = "ABC"
$part1 = '<a href="mywebpage.php#';
$part2 = '">Go to this code</a>';
$string = $part1.$code.$part2;
echo $string;
?>
(i.e. Link in the page says "go to this code" and when clicked will go to section with bookmark ABC)
This all works fine, but I simply need to know if there is a way of error trapping so that if a bookmark does not exist for the code entered, a message can be displayed to the user instead? Can this be done using the PHP variable, or do I need to use JavaScript? One work around may be to search the web page for the ID "#ABC'. Is it possible to do this? Another option would be to store an array of valid codes on the server then query this before setting the bookmark, but I want to keep it as simple as possible. Any help appreciated, thanks.
What you call a "bookmark" we call a hash. And when you say "go to a bookmark" you mean a hash change. Hash changes do not make an additional request to the server, it is all handled on the client-side, therefore this must be done with JavaScript and not PHP.
So let's just do some simple JavaScript on hash change window.onhashchange that will search for an element with that ID and if it's not found alert something.
window.onhashchange = function(){
if(!document.getElementById(location.hash){
alert("not found");
}
}

How to encrypt product ID in URL

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.

pass a value from one page to another outside querystring and without javascript?

One solution to automatically building navigation for a site is by scanning a folder for documents like this:
foreach(glob('pages/*.pg.php') as $_SITE_NAV_filePath):
$_SITE_NAV_filePath = explode('.pg',pathinfo($_SITE_NAV_filePath,PATHINFO_FILENAME));
$_SITE_NAV_fileName = $_SITE_NAV_filePath[0];
$_SITE_NAV_qv = preg_replace('/([A-Z])/','-$1',$_SITE_NAV_fileName); $_SITE_NAV_qv = trim($_SITE_NAV_qv,'-');
$_SITE_NAV_name = preg_replace('/([A-Z])/',' $1',$_SITE_NAV_fileName);
?>
<li><?=$_SITE_NAV_name?></li>
<?php
endforeach;
This code will turn "AnAwesomePage.pg.php" into a menu item like this :
<li>An Awesome Page</li>
This might be bad practice (?).
Anyway; I don't use this method very often since most of the time the sites have a database, and with that comes better solutions...
But my question is this:
Is there a way to prefix the filename with a integer followed by and underscore (3_AnAwesomePage.pg.php), for sorting order purposes, and pass it somehow to the destination page outside of the querystring and without any async javascript?
I could just explode the filename once again on "_" to get the sort order and store it somewhere, somehow?
This is the code for handeling the page query request:
$_SITE_PAGE['qv'] = $_GET['page'];
if (empty($_SITE_PAGE['qv'])){ $_SITE_PAGE['qv'] = explode('-','Home'); }
else { $_SITE_PAGE['qv'] = explode('-',$_GET['page']); }
$_SITE_PAGE['file'] = 'pages/'.implode($_SITE_PAGE['qv']).'.pg.php';
This code turns "An-Awesome-Page" back into "AnAwesomePage.pg.php" so it's possible to include it with php.
But with a prefix, it's not so easy.
The probliem is; Now there's no way to know what prefix number there was before since it has been stripped away from the query string. So I need to send it somehow along in the "background".
One very bad solution I came up with was to transform the navigation link into a form button and just _POST the prefix interger along with the form. At fist it sounded like a nice solution, but then I realized that once a user refreshes their page, it didn't look very good. And after all, that's not what forms are for either...
Any good solutions out there?
Or some other and better way for dealing with this?
There are two ways to keep that number saved, you can use cookies or php session variables.
But in this case, if user first enter the url in the browser or in a new browser, then he should be taken to default number.
Like you have:
1_first-page.php
2_first-page.php
3_first-page.php
If user enter the url like: domain.com/?page=first-page, you have to take him to 1_first-page.php to any number which you want to be default.

Multiple $_GET through links

I'm doing a website. There's a pagination, you click on links and they take you to the page you need, the links pass $_GET variable ( a href="?pn=2" ) and that works fine.
However when i add the category links (also contain $_GET variable
(a href="?sort=english") on the same page, which kind of sort the content on the page, and click it, the system simply overrides the url and deletes all the previous $_GET's.
For example, I'm on page 2 (http://website.com/index.php?pn=2)
and then I click this sorting link and what I'm expecting to get is this (http://website.com/index.php?pn=2&sort=english), but what I get is this:
(http://website.com/index.php?sort=english). It simply overrides the previous $_GET, instead of adding to it!
A relative URI consisting of just a query string will replace the entire existing query string. There is no way to write a URL that will add to an existing query. You have to write the complete query string that you want.
You can maintain the existing string by adding it explicitly:
href="?foo=<?php echo htmlspecialchars($_GET['foo']); ?>&bar=123"
Try using this:
$_SERVER['REQUEST_URI'];
On this link you can see examples. And on this link I have uploaded test document where you can try it yourself, it just prints out this line from above.
EDIT: Although this can help you get the current parameters in URL, I think it's not solution for you. Like Quentin said, you will have to write full link manually and maintain each parameter.
You could create a function that will iterate through your $_GET array and create a query string. Then all you would have to do is change your $_GET array and generate this query string.
Pseudocode (slash I don't really know PHP but here's a good example you should be able to follow):
function create_query_string($array) {
$kvps = array();
for ($key in $array) {
array_push($kvps, "$key=$array[$key]");
}
return "?" . implode("&", $kvps);
}
Usage:
$_GET["sort"] = "english";
$query_string = create_query_string($_GET);
You need to maintain the query parameters when you create the new links. The links on the page should be something like this:
Sort by English
The HTTP protocol is stateless -- it doesn't remember the past. You have to remind it of what the previous HTTP parameters were via PHP or other methods (cookies, etc). In your case, you need to remind it what the current page number is, as in the example above.

Categories