Started learning php this week and had many doubts, but this is one of them which i couldn't find solution(Maybe i didn't know the right keyword to search for).
Is it possible to read variables in URL as a function inside a php file,
for example :
http://mywebsite.com/demo_app/phone_api/login/harsha/harshapass
Here demo_app is the folder, phone_api is the php file, and i want to invoke the function login, where harsha and harshapass is the paramaters to that function.
You'll need 2 things for this.
The first is mod_rewrite, this is an apache module. With this module you can rewrite the URL like you want, so that /demo_app/phone_api/ will redirect to your php file.
I advice that you read a tutorial somewhere about this, for example here.
Second thing is that you need to parse the URL.
With $_SERVER['REQUEST_URI'] you get the URL. With explode and/or preg_match you can parse this string into the parts you want (function, parameters, whatever).
If you have a more specific question about this, you can ask this here (in a new topic).
Good luck!
Did you consider sending the values as $_GET variables and retrieving them in the page like so:
http://mywebsite.com/demo_app/phone_api?login=login&harsha=harsha&harshapass=harshapass
so you can get the values in the phone_api.php page like:
$login = $_GET['login'];
$harsha = $_GET['harsha'];
$harshapass = $_GET['harshapass'];
$login($harsha, $harshapass){
//your function code.
}
Maybe it'll be easier this way.
Related
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.
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>
Setup:
Script that generates word images from multiple letter images
(autotext.php)
URL is formatted:
www.whatever.com/autotext.php?text=hello%20world
Script that alters images server-side to run filters or generate
smaller sizes (thumbnail.php)
URL is formatted:
www.whatever.com/thumbnail.php?src=whatever.png&h=XXX&w=XXX
Use-case:
I want to generate a smaller version of the autotext server-side. So my call would look something like:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
As you can see, I would like to treat a URL with _GET variables as a variable itself. No amount of playing with URI encoding has helped make this work.
I have access to the PHP for both scripts, and can make some simple alterations if that's the only solution. Any help or advice would be appreciated. I would not even rule out a Javascript frontend solution, though my preference is to utilize the two scripts I already have implemented.
You should be able to do this by urlencoding all the $_GET params into a variable then assigning that variable to another, like this (untested):
// Url generation
$url = www.whatever.com/thumbnail.php?src=(urlencode(http_build_query($_GET)));
Then you should be able to retrieve on other side:
$src = urldecode(explode('&', $_GET['src']));
I've seen this exact behavior when trapping where to redirect a user, after an action occurs.
---- Update ----
Your "use case" url was correct:
www.whatever.com/thumbnail.php?src=autotext.php?text=hello%20world&h=XXX&w=XXX
.... except that you CANNOT have more than one ? within a "valid" url. So if you convert the 2nd ? to a &, you should then be able to access $_GET['text'] from the autotext.php script, then you can urldecode it to get the contents.
I have read many about REST api in php articles. but I still get quite confusing.
they basically rewrite the url to a index.php, which process the url and depends on the method, then send response
but which is the properly way to process the url? this looks doen't look correct...
get the uri and split it
I should know what to do with each portion, eg. for GET /usr/1 I should do something like:
if($myUri[0]=="usr")
getUser($myUri[1]);
if the request url is like GET www.domain.com/user/1
it would call getUser($id);
but what happen if you can also retrieve the user by name, or maybe e-mail? so the url can also be www.domain.com/user/john or www.domain.com/user/john#gmail.com
and each url should call different methods like getUsrByName($name) or getUsrByEmail($mail)
The proper way of handling this would be to have URLs like this:
domain.com/user/id/1 -> user::getById
domain.com/user/email/foo#bar.com -> user::getByEmail
domain.com/user/username/foo -> user::getByUsername
However, specifying multiple "parameters" is more like a search, I'd go against using resources for that, because a path should be absolute. Which means:
domain.com/user/name/Kossel/likes/StackOverflow
And:
domain.com/user/likes/StackOverflow/name/Kossel
Are not the same resource. Instead I'd do:
domain.com/user/?name=Kossel&likes=StackOverflow
This is what Stack Overflow uses:
stackoverflow.com/questions/tagged/php
stackoverflow.com/tags/php/new
stackoverflow.com/questions/tagged/mysql?sort=featured
To avoid long if/else statement, use variable function names. this allows you to use the url string to call the correct function.
http://php.net/manual/en/functions.variable-functions.php
Also, you may want to use classes/class methods instead of functions. this way you can set up an __autoload function, which will allow you to only load code that you are going to use each time the index.php is called.
MVC architecture usually breaks their urls into /class_name/class_method_name/arguments...
I am using Jumi to include a number of PHP scripts on Joomla! articles and it works great. The problem I am having is with passing variables (in the form of $_GET parameters) to a PHP script.
Lets say I have a script "index.php" and I wish to pass the $_GET[] parameter "var" with the value of "10". This would normally be accomplished by pointing to: index.php?var=10. How do "emulate" this functionality with Jumi? I was hoping it would be as simple as:
{jumi [directory/index.php] [var=10]}
The above syntax however is not correct.
Any input would be appreciated.
-- Nicholas
After some trial and error and guidance from the official Joomla! forums I did solve my problem. Rather than passing a true $_GET[] parameter you can pass a $jumi array and reference that.
I wanted to avoid having to rewrite much of my script so what I did was the following.
1) Make the Jumi call like this:
{jumi [directory/index.php] [value]}
2) In index.php:
if(isset($jumi[0]))
{
$_GET['PARAM_YOU_WANT_SET'] = $jumi[0];
}
This is a very simple example of a quick and easy way to emulate passing a $_GET[] parameter to a script using Jumi. This approach saved me a great deal of time because I didn't have to rewrite my controller.
-- Nicholas
This is an old thread I know but there is something that some people might want to know.
If you are wanting to use Jumi with extra parameters in a Module then Nicholas' tip won't work but there is a way to do it.
There is a "Code written" section of the module and a "Source of code" section.
Put the url/path to the file in the "Source of code" section and then define your variables in the "Code written" section...it will pass the variable to the source file before executing so it will do what is desired.