How to display content based on the URL - php

I'm learning PHP and MySQL and I have a question. I've seen that a lot of sites use this, for example:
http://www.example.com/index.php?product_id=8
or
http://www.example.com/index.php?cattegory=headphones
If you change the values in the URL, the content the page displays changes, so I would like to know how to use that in my webpage, thanks!

You can check for the GET parameter included in the url...
if($_GET['product_id' == 8]) { ... }

Related

How to make dynamic links in php without eval()

I am using wordpress for a web site. I am using snippets (my own custom php code) to fetch data from a database and echo that data onto my web site.
if($_GET['commentID'] && is_numeric($_GET['commentID'])){
$comment_id=$_GET['commentID'];
$sql="SELECT comments FROM database WHERE commentID=$comment_id";
$result=$database->get_results($sql);
echo "<dl><dt>Comments:</dt>";
foreach($result as $item):
echo "<dd>".$item->comment."</dd>";
endforeach;
echo "</dl>";
}
This specific page reads an ID from the URL and shows all comments related to that ID. In most cases, these comments are texts. But some comments should be able to point to other pages on my web site.
For example, I would like to be able to input into the comment-field in the database:
This is a magnificent comment. You should also check out this other section for more information
where getURLtoSectionPage() is a function I have declared in my functions.php to provide the static URLs to each section of my home page in order to prevent broken links if I change my URL pattern in the future.
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Update:
Thanks for your replies. I have been thinking of this problem a lot, and spent the evening experimenting, and I have come up with the following solution.
My SQL "shortcode":
This is a magnificent comment. You should also check out this other section for more information
My php snippet in wordpress:
ob_start();
// All my code that echo content to my page comes here
// Retrieve ID from url
// Echo all page contents
// Finished generating page contents
$entire_page=ob_get_clean();
replaceInternalLinks($entire_page);
PHP function in my functions.php in wordpress
if(!function_exists("replaceInternalLinks")){
function replaceInternalLinks($reference){
mb_ereg_search_init($reference,"\[custom_func:([^\]]*):([^\]]*)\]");
if(mb_ereg_search()){
$matches = mb_ereg_search_getregs(); //get first result
do{
if($matches[1]=="getURLtoSectionPage" && is_numeric($matches[2])){
$reference=str_replace($matches[0],getURLtoSectionPage($matches[2]),$reference);
}else{
echo "Help! An unvalid function has been inserted into my tables. Have I been hacked?";
}
$matches = mb_ereg_search_regs();//get next result
}while($matches);
}
echo $reference;
}
}
This way I can decide which functions it is possible to call via the shortcode format and can validate that only integer references can be used.
I am safe now?
Don't store the code in the database, store the ID, then process it when you need to. BTW, I'm assuming you really need it to be dynamic, and you can't just store the final URL.
So, I'd change your example comment-field text to something like:
This is a magnificent comment. You should also check out this other section for more information
Then, when you need to display that text, do something like a regular expression search-replace on 'href="#comment-([0-9]+)"', calling your getURLtoSectionPage() function at that point.
Does that make sense?
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Eval is a terrible approach, as is allowing people to submit raw PHP at all. It's highly error-prone and the results of an error could be catastrophic (and that's without even considering the possibly that code designed by a malicious attacker gets submitted).
You need to use something custom. Possibly something inspired by BBCode.

How to remove any given $_GET variable from URL with PHP?

I'm puttings filters in links with GET variables like this: http://example.com/list?size=3&color=7 and I'd like to remove any given filter parameter from URL whenever a different value for that particular filter is selected so that it doesn't, for example, repeat the color filter like so:
http://example.com/list?size=3&color=7&color=1
How can I if(isset($_GET['color'])) { removeGet('color'); } ?
You can use parse_url and parse_str to extract parameters like in example below:
$href = 'http://example.com/list?size=3&color=7';
$query = parse_url( $href, PHP_URL_QUERY );
parse_str( $query, $params );
// set custom paramerets
$params['color'] = 1;
// build query string
$query = http_build_query( $params );
// build url
echo explode( '?', $href )[0] . '?' . $query;
In this example explode() is used to extract the part of the url before the query string, and http_build_query to generate query string, you can also use PECL http_build_url() function, if you cannot use PECL use alternative like in this question.
You can't remove variables from GET request, just redirect to address without this var.
if (isset($_GET['color'])) {
header ('Location: http://www.example.com/list?size=' . $_GET['size']);
exit;
}
Note: in URL http://example.com/list?size=3&color=7&color=1 is just one $_GET['color'], not two. Only one of them is taken. You can check, is $_GET['key'] exists, but you don't know how many of them you have in your URL
So, assuming I'm understanding your question correctly.
Your situation is as follows:
- You are building URLs which you put into a webpage as a link ( <a href= )
- You are using the GET syntax/markup (URL?key=value&anotherkey=anothervalue) as a way to assign filters of some sort which the user then receives when they click on a given link
What you want is to be able to modify one of the items in your GET parameter list (http://example.com/list?size=3&color=7&color=1) so you have only one filter key but you can modify the filter value. So instead of the above you would start with: (http://example.com/list?size=3&color=7) but after changing the color 'filter' you would instead have http://example.com/list?size=3&color=1).
Additionally you want to do the above in PHP, (as opposed to JavaScript etc...).
There are a lot of ways to implement the change and the most effective way to do it depends on what you are already doing, most likely.
First, if you are dynamically producing the HTML markup which includes the links with the filter text, (which is what it sounds like), then it makes the most sense to create a PHP array to hold your GET parameters, then write a function that would turn those parameters into the GET string.
New filters would appear when a user refreshed the page, (because, if you are dynamically producing the HTML then a server request is required to rebuild the page).
IF, however, you want to update the link URLs on a live page WITHOUT a reload look into doing it with JavaScript, it will make your life easier.
NOTE: It is likely possible to modify the page, assuming the links are hard coded, & the page is hard coded markup, by opening the page as a file in PHP & making the appropriate change. It's my opinion that this would be a headache and not worth the time & effort AND it would still require a page reload (which you could NOT trigger yourself).
Summary
If you are writing dynamic pages with PHP it shouldn't be a big deal, just create a structure (class or array) and a method/function to write that structure out as a GET string. The structure could then be modified according to your desire before generating the page.
If, however, you are dealing with a static page, I recommend JavaScript (either creating js structures to allow a user to dynamically select filters or utilizing AJAX to build new GET parameter lists with PHP and send that back to the javascript).
(NOTE: I am reminded that I have done something along the lines of modifying links on-the-fly for existing pages by intercepting them before they are displayed to the user [using PHP] but my hands were tied in other areas and I would not recommend it if you have a choice AND it should be noted that this still required a reload...)
Try doing something like this in your back-end script:
$originalValues=array();
foreach($_GET as $filter=>$value)
{
if(empty($originalValues[$filter]))
$originalValues[$filter] = $value;
}
This may do what you want, but it feels hackish. You may want to revise your logic.
Good luck!
just put a link/button send the user to index... like this.
<a class="btn btn-primary m-1" href="http:yoururl/index.php" role="button">Limpar</a>

How to change autolink

in my forum, I'm trying to stop links from converting into clickbale links and place a custom text language instead that says Links Not Allowed.
This seems to be the code that creates the clickable links. My question, is it possible to convert the urls to non-clickable text that says "Spam - Links Not Allowed"
public function parseUrl($params) {
$url = $params['url'];
$text = $params['text'];
If I remove this last line, it seems to make the links disappear, however I would like to display a custom message instead. Sorry if this is a basic question, my code knowledge is at a beginner level.
It's not just server side action, for this reason you should call JS function, so, at first change your php code to this :
$url = $params['javascript:myfunction();'];
and then in client side for javascript write this :
function myfunction(){
alert('not allowed!');
}
$text = $params['text'];
replace "text" with "spam - links not allowed."
In terms of how to make it not clickable, I need to see where the link is actually used.

jQuery/Drupal Append string to all HREF on site (Any page)

So I have a site with a dozen pages on it using Drupal as a CMS. Wanted to know how to set/append all href links on any page with a dynamic attribute?
so here is an example URL:
http://www.site.com/?q=node/4
and I wanted to append to the URL like so:
http://www.site.com/?q=node/4&attr=1234
Now I have a nav bar on the site and when I hover over the link I see the url but I need to append the &attr=1234 string to the end of it. The string is dynamic so it might change from time to time.
I was thinking jQuery would be a good choice to do this but does Drupal have any functionality as well?
Now I've seen a couple of posts on Stack:
Post 1
Post 2
Problem is I'm learning my way around Drupal and have minimal experience with jQuery but getting better with both. I see the jQuery can replace a HREF but looks like they hard coded the HREF, could jQuery find all HREF's on a page and append the string to it? Also does Drupal have this functionality and what would be the best approach?
Also need this to work for clean or standard URL format, so I think Apache would handle this I just wanted to make sure.
Thanks for any help
EDIT:
Looks like the general consensus is the Drupal should handle this type of request. Just looking for the best implementation. Simple function call would be best but I would like it to dynamically add it to all existing href's as I want this to be dynamic instead of hard coding any url/href calls. So I could add/remove pages on the fly without the need to reconfigure/recode anything.
Thanks for the great tips though
EDIT #2:
Okay maybe I'm asking the wring question. Here is what I need and why it's not working for me yet.
I need to pass a value in the url that changes some of the look and feel of the site. I need it to be passed on just about every href tag on the page but not on User logout or Admin pages.
I see in my template code where the nav links get generated, so I though I could pass my code in the attributes array as the second parm to the function, but that is setting the tag attributes and not the URL attributes.
Now I see the bottom nav links use this Drupal function: menu_navigation_links() in menu.inc but the top nav uses a custom function.
This function in the template.php script looks to be the one creating the links
function lplus($text, $path, $options = array()) {
global $language;
// Merge in defaults.
$options += array(
'attributes' => array(),
'html' => FALSE,
);
// Append active class.
if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
(empty($options['language']) || $options['language']->language == $language->language)) {
if (isset($options['attributes']['class'])) {
$options['attributes']['class'] .= ' active';
}
else {
$options['attributes']['class'] = 'active';
}
}
// Remove all HTML and PHP tags from a tooltip. For best performance, we act only
// if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
$options['attributes']['title'] = strip_tags($options['attributes']['title']);
}
return '<a href="'. check_url(url($path, $options)) .'"'. drupal_attributes($options['attributes']) .'><b>'. ($options['html'] ? $text : check_plain($text)) .'</b></a>';
}
not sure how to incorporate what I need into this function.
So on the home page the ?q=node/ is missing and if I append the ampersand it throws an error.
http://www.site.com/&attr=1234 // throws error
But if I mod it to the correct format it works fine
http://www.site.com/?attr=1234
Assuming that when you mean pages, you mean the content type of pages (will work for any other content type as long as it's really content and not something in a block or view).
You can easily replace the contents of any node that is about to be viewed by running a str_replace or with a regular expression. For instance, using str_replace:
function module_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
switch($op) {
case "view":
$node->body = str_replace($expected_link, $desired_link);
break;
}
}
where you define desired link somewhere else. Not an optimal solution, but non-Javascript browsers (yes, they still exist!) can't get around the forced, desired URLs if you try to change it with Javascript.
I think doing it in Drupal/PHP would be cleaner. Check out Pathauto module: http://drupal.org/node/17345
There is a good discussion on a related topic here:
http://drupal.org/node/249864
This wouldn't use jquery (instead you would overwrite a function using PHP) but you could get the same result. This assumes, however, that you are working with menu links.
I think you should consider exploring PURL ( http://drupal.org/project/purl ) and some of the modules it works with e.g. spaces and context.
I don't suggest you use jQuery to do this. It's a better practice to do this server side in PHP (Drupal).
You can overwrite the links dynamically into your preprocess page function.
On your template.php file:
function *yourtheme*_preprocess_page(&$vars, $hook){
//You can do it for the region that you need
$vars['content'] = preg_replace('/<a href="(.*?)"/i', '<a href="$1&attr=1234"', $vars['content']);
}
Note:
I did not try it, its only a hint.
It will add your parameters to the outside links too.

How to pass part of url in new link? Using only HTML & PHP

I have been trying to attempt to use the facebook share function in my website but i cant seems to have the right result.
Say:
i have a page called http://www.example.com/product.php?prod=lpd026n&cat=43
and i am using facebook's share function to have visitors to share the page in the FB wall.
i tried writing the link this way but i doesn't seems to be successful:
href="http://www.facebook.com/share.php?u=www.example.com/proddetail.php?<?php print urlencode(#$_SERVER['QUERY_STRING']!=''?'?'.$_SERVER['QUERY_STRING']:'')?>"
as the result the arguments in the URL came out to be in %26, %3D and etc..
Ie: example.com/proddetail.php?prod%3Dlpd026n%26cat%3D43
as some of you may know that the data after '?' is dynamic and i am planing to use the code above in the frame of the page, so it will have different query passed to the share link in every new item.
The end result that i want got to look like this:
http://www.facebook.com/sharer.php?u=http://www.example.com/proddetail.php?prod=lpd026n&cat=43
Not
http://www.facebook.com/share.php?u=http://www.example.com/proddetail.php?prod%3Dlpd026n%26cat%3D43
can anyone help me to solve this problem?
Thanks in advance!
Ps: if you are unclear, please ask me to further clarify.
This URL:
http://www.facebook.com/share.php?u=http://www.example.com/proddetail.php?prod%3Dlpd026n%26cat%3D43
is only partially-encoded. You actually need to fully URL-encode it before passing to FB, so that it won't interfere with FB's URL structure. I'm sure that their script will know how to parse it properly.
The correct method is:
$url = 'http://www.facebook.com/sharer.php?u='.urlencode('http://www.example.com/proddetail.php?prod=lpd026n&cat=43');
// evaluates to:
// http://www.facebook.com/sharer.php?u=http%3A%2F%2Fwww.example.com%2Fproddetail.php%3Fprod%3Dlpd026n%26cat%3D43
Update: build your dynamic query
// Original URL
$url = 'http://www.example.com/proddetail.php';
if ($_SERVER['QUERY_STRING'])
$url .= '?'.$_SERVER['QUERY_STRING'];
// Final URL for FB
$fb_url = 'http://www.facebook.com/share.php?u='.urlencode($url);
This is what urlencode does, what is the problem with the link this way?
Edit: I do not use PHP, but I think the following will do the trick (omitted the urlencode):
href="http://www.facebook.com/share.php?u=www.example.com/proddetail.php?<?php print $_SERVER['QUERY_STRING']?>"
I guess K Prime is right.
u need to encode the whole url because the slashes and ":" are still causing problems in this link ;)
$url = 'http://www.facebook.com/sharer.php?u='.urlencode('http://www.example.com/proddetail.php?prod=lpd026n&cat=43');
should be fine for your purposes.

Categories