Use URL segments as jQuery $.post variables - php

I would like to be able to use jQuery $.post with url segments as follows:
www.mysite.com/stats/user1
www.mysite.com/stats is the landing page, with this code on it:
var user = //get user1 from the url;
$.post('stats.php', {username : user}, function(results){...});
The username should be posted to a PHP backend which then does some database querying.
Is this possible? I might be able to use .htaccess to redirect users from stats/user1 to stats/, but I don't have much experience in this area.
Many thanks in advance for your help.
EDIT
In response to Loopo's answer:
I can use .htaccess to rewrite incoming URLs as follows:
RewriteRule ^/stats/(.*)$ stats.php?username=$1 [L].
This would allow me to enter a URL such as mysite.com/stats/user123, which the server would interpret as mysite.com/stats?username=user123
In stats.php can I then use $user = $_GET['username']?

It seems you are mixing some concepts up.
If you want to pass data to a webserver, you can do it in two ways; POST or GET. (There is also PUT and DELETE but we'll ignore that here.)
If you are using a GET request, the data is in the URL, normally in a format like
mysite.com/mypage.php?param1=value1&param2=value2....
the slashes normally act as a path separator to tell the webserver where to look for the resource that answers the request.
mysite.com/myapp/myfolder/resources/logo.png
would tell the server where to find and then send the file logo.png to the client.
If you want to have parameters in the path, you can also use redirection (.htaccess) to have virtual resources.
as in your example.
www.mysite.com/stats/user1
there is no stats folder with a script for every user.
You'll have to tell your webserver when someone asks for some path that looks like
/stats/<something>
the request should be served by some script (probably 'stats.php') and the parameters that are passed to the script will be <something>
in your .htaccess this might look like:
RewriteRule ^/stats/(.*)$ stats.php/$1 [L]
In a POST request the parameters are not visible in the url.
So your stats.php would have to be called without the username in the URL, but instead in the POST variables, i.e. in your case POSTing to stats.php/user1 and then including the username again in the POST variables is redundant.
So your stats.php could deal with a POST request by reading in the parameters and creating/updating a new user with the values provided in the POST parameters, while dealing with GET requests by returning the user's stats as they are now.
What I am describing is REST, see also

Related

Intercept Angular URL with PHP first before loading webpage

We currently have a full Angular project running in a sub-dir on our server and a physical "device" using a hardcoded URL to send a user to that page.
I'm looking for some kind of way to "intercept" the request via a PHP script first to (for example, not the real purpose) see if the requested "ID" param for that browser page has enabled the option to view the browser page or if it has been configured by the user to return a 406 HTTP response (for example).
Currently:
- ..com/app/routing-view?id=1234 => Angular view -> fetch info
Idea:
- ..com/app/routing-view?id=1234 => PHP-script -> isValid => forward to angular and do a normal 'webview' -> fetch info
- ..com/app/routing-view?id=2889 => PHP-script -> notValid => HTTP code
I thought about having a .htaccess "intercept" the url and forward it to a .php file. Do the magic and checks there, and then forward the browser to the original url, but to "bypass" the previous interceptor.
It's about that last part that I'm currently having issues. Because it's Angular and it is using paths, I can't just say "okay, redirect to index.html instead of index.php" because it would need to be something like ..com/app/routing-view?id=1234 (and the index.html is located in the /app directory.
I don't want to add PHP code to the original Angular-index file if that could be avoided.
Am I looking at this right or would there be a different, more efficient way to tackle this?
The reason for all this is that I want to (for example) return a different HTTP code or different headers to the device instead of a 200 html header response even if the ID turned out to be disabled or something like that.
Got it to work via a simple .htaccess, a parameter and an "interceptor" script. Quite simple and basic really, not sure why my brain didn't go this route before posting my question.
Added the .htaccess to the root of the Angular application with the following code.
RewriteEngine On
# Check if the request has been intercepted before (via URL parameter)
RewriteCond %{QUERY_STRING} !(^|&)intercepted=true
# .. If not, rewrite the page to use the interceptor script (only if it matches the route).
RewriteRule ^my-route dir-of-script/extra/interceptor.php?url=https://%{HTTP_HOST}%{REQUEST_URI}?%{QUERY_STRING} [L,QSA]
# Other stuff for rewriting the Angular routes etc
...
Added a /dir-of-script/extra/interceptor.php like-script that parses the URL from the GET parameter, fetches the info, does the checks and depending on the result, returns the output or redirects the page and let it through.
This adds a ..&intercepted=true parameter to the original URL so that the .htaccess doesn't intercept it again.
This seems to be working like a charm (for my situation). The only "downside" is that this counts as a redirect and not just a rewrite when it was allowed to go through. Will look further into it, to maybe let the PHP script "serve" the Angular content instead of redirecting to it.

How to take data from URL

I am developing API for my company. Normally, we use POST & GET method to send form data to other website or another page. But what I want, If we want to send data in URL like
http://www.example.com/data1/data2/data3
like that.
In that case, Data1, Data2, Data3 is our data and I want this data in PHP.
I am searching on that but I can't find what I want.
Look into Apache mod_rewrite (http://httpd.apache.org/docs/current/mod/mod_rewrite.html).
You can rewrite data1/data2/data3 into ?thing1=data1&thing2=data2&thing3=data3, then use $_GET like you usually would...
What you are looking for is called URL Rewriting which is supported by all major Web Servers like Apache and NGINX.
To read more about URL rewriting in apache go thorugh:
https://code.tutsplus.com/tutorials/using-htaccess-files-for-pretty-urls--net-6049
To read more about neat urls in NGINX go through https://serverfault.com/questions/653177/clean-url-with-several-params-in-nginx
In apache servers clean URLS can be achieved by enabling a module called mod_rewrite and a simple way to do it is using the .htaccess file.
In nginx you can use web.config file.
After having clean URL's you can use any method from GET,PUT, POST, PATCH, DELETE etc. but remember if the user enters your URL in your browser then it is always a GET request by default.
you can do it by simply fetching the entire URL and preg_split() the string as below code
$path = $_SERVER['REQUEST_URI']; // this gives you /folder1/folder2/THIS_ONE/file.php
$folders = preg_split('/', $path); // splits folders in array
$what_we_need = $folders[3];

PHP: How to get content of another URL (page) on my site without changing address in bar

I am using ModRewrite as below to convert urls on my site to be SEO friendly:
RewriteRule user/(.*)/$ seo-url-user-by-name.php?username=$1
Now I am writing code for seo-url-user-by-name.php and am looking for a way in PHP to redirect to:
user.php?uid=<uid>
so that seo-url-user-by-name.php will essentially return the contents of user.php?uid=<uid> BUT without changing the address in address bar to user.php?uid=<uid>
How do I do that?
Simply include user.php in seo-url-user-by-name.php. To get the querystring right you have to overwrite the value in $_GET.
$_GET['uid'] = 'whatever you want';
include 'user.php';
You're going about it backwards. The only URLs your code should be outputting are the 'friendly' ones. Those are the urls that will appear in the produced HTML and what will show up in the user's address bar.
e.g.
Bad URL (URL #1)
This URL is fine (URL #2)
You should never output anything but URL #2's. It'll be your server's responsibility to convert that clean (and in real terms, non-existent) URL to whatever really is on the server. PHP itself should never care nor see the /user/foo URL. PHP will be invoked as /user.php?id=foo as usual, and go about its business as usual.
The remote user would never see that rewriting occurring, they'll just see a request go out for /user/foo.

How to preserve POST data via ajax request after a .htaccess redirect?

.htacesss
RewriteCond %{REQUEST_URI} ^/api/(.+)$
RewriteRule ^api/(.+)$ /index.php?api=%1 [QSA,L]
example ajax url request:
'http://hostname.com/api/ext/list.php?query=de'
I want to be able to redirect urls in this format to the following
index.php?api={requested_filename}&param1=value1&param2=value2 ...
because the whole site is processed through a bootstrap process in index.php which has a routing part loading configs, templates etc...
When I try a jquery code for example, the POST data is lost after redirect.
$.ajax({
url: '/api/contact.php',
type: 'POST',
data: {
email: $("#contactEmail").val(),
name: $("#contactName").val(),
message: $("#contactMessage").val()
// etc ...
}
});
I've read that you cannot preserve data on a http redirect. But how do all the frameworks avoid that? I've coded in many, and every one is bootstraped through the index.php and there are rewrite rules in the .htaccess file for enabling pretty urls. So in Yii for example, I would call an url "api/uploads/latests.json" with some POST data and the controllers on the backend would receive that data. What am i missing here?
note: I've tested the [P] mod_rewrite parameter, and i think that this server doesn't have mod_proxy enabled.
There is a difference between a rewrite and a redirect.
Rewrite is an apache (and other servers) module that will follow a set of cond/rules to map a requested url to files on the server (ex: a bootstrap rewrites all urls to a single file, usually index.php. A mvc might map /model/controller/view uri to an index.php that calls the appropriate mvc files).
A redirect actually changes the page you are on. Someone requests page A.php and that page says "what you are looking for is on B.php" and so your browser goes to B.php.
A rewrite will preserve post parameters because the url doesn't change. A rewrite will just change the script being requested, but to the browser it looks like the page still exists at the requested url.
A redirect will not preserve post parameters because the server will redirect you to another page completely.
What it appears you are trying to do is a rewrite, not a redirect. You should have no problems getting the post parameters.
To fix this, how are you checking in index.php that there are no post parameters? Are you sure the controller you are expecting is getting called?
All POST data is lost on redirect. There is no way to preserve it via htaccess rewrite/redirect rules.
The redirect (all 301,302,303) received by the client (all major browsers I know) is treated as a new url to make a GET request to. Browsers won't automatically tack on old post parameters to this URL--even if the source of the redirect was a POST request.
The only way I've every found around this is to do the rewrite inside code and covert the POST parametes to GET parameters and stick them on the end of the new url. In php you then issue a header location change (or whatever redirect call your library of choice uses):
header("Location: http://www.example.com/?my_old_post_args=123");
exit;
for any one have this problem i have the sam problem and i use
some thing like this
RewriteRule ^services/MainService/(.*)$ http://193.9.162.91/mobile-feed/mobile.list.news.images.php?original_request=$1 [R=301,L]
this will not work with ajax post i have to chnage the RewriteRule to
RewriteRule ^services/MainService/(.*)$ http://193.9.162.91/mobile-feed/mobile.list.news.images.php?original_request=$1 [QSA,L]
this work
and in the php file i have
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
print_r($input);

PHP redirect to another website

I have a directory named "goto" and a file inside called index.php. Currently the following is inside the index.php file:
<?php
$url = $_GET['url'];
header("Location: $url");
?>
At the moment to redirect to another URL I have to type this into the address bar:
http://mysite.com/goto/?url=http://google.com
I would appreciate it if you could tell me how I could change that URL so that I could redirect the user to a website by typing this into the address bar:
http://mysite.com/goto/http://google.com
Use mod_rewrite and .htaccess to rewrite http://mysite.com/goto/http://google.com as http://mysite.com/goto/?url=http://google.com
RewriteEngine On
RewriteRule ^goto/(.+)$ /goto/?url=$1 [L]
Depending on your server configuration you may need to include a / in your rewrite path (i.e., ^/goto/(.+)$).
Unless you want to become a malware hub, I would wholeheartedly recommend you not doing this.
If you wish to allow redirect in such a manner, using http://mysite.com/goto/google and then work out the domain from a whitelist of available, allowed, destinations.
You will need to parse the data which could be a little tricky because you have to differentiate the difference between your URL and the other URL.
My suggestion is to not do so because the second that header is launched you will not see the url and it be better for you to just pass it as a get statement or a post.
EDIT
If you're determined then parse_url() is what you want. :)
#ide's method would work ... but you could also have the PHP script examine $_SERVER['PATH_INFO'], which is how that part of the URL would get passed to the CGI script.
(although, if there's a question mark in there, you'll also have to either make sure it's URI encoded, or also get the QUERY_STRING; you'll also lose any part after a hash, but you'd have the same problem with your current scheme)

Categories