PHP Paging with variables ugly URLS - php

OK I have a large database I an querying LIKE SO
SELECT * FROM PricePaid WHERE PostCode LIKE '$loc%'
ORDER BY Price DESC
LIMIT $start,$perPage
I know how to do the paging links to work out the total records found and page through them. I am using the following code on my NEXT link :
<a href='http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&start=$next'>NEXT</a>
Which works OK as it keeps my ?loc variable but the start variable duplicates.
This is how my url looks on the first page
mysite/uk-property-prices.php?loc=l24
Then when I click my next page link the first time my url passes the start variable and the query displays page two
mysite/uk-property-prices.php?loc=l24&start=1
But when I click next again I get this
mysite/uk-property-prices.php?loc=l24&start=1&start=2
Now I know this works but after a while my URL gets stupidly long LIKE so
mysite/uk-property-prices.php?loc=l24&start=1&start=2&start=3&start=4
What AM I doing wrong

$_SERVER['REQUEST_URI'] contains the query string as well. All you're doing is appending more and more variables each time.
You will need to parse the query string, replace the value that you want to replace, and re-build the URL. PHP has already parsed it for you in $_GET (assuming you don't need duplicate values). Untested, but try this:
$newQueryParts = $_GET;
$newQueryParts['loc'] = 3;
$urlParts = parse_url($_SERVER['REQUEST_URI']);
echo 'http://', $_SERVER['HTTP_HOST'], $urlParts['path'], '?', http_build_query($newQueryParts);
Don't forget to consider the protocol as well. Your site might use HTTPS in the future. Also, they way you are interpolating variables directly in your query implies that you might be open to SQL injection attacks. Always use prepared/parameterized queries to avoid this problem.

You're using 'REQUEST_URI', which will naturally contain the address of the page you're on, so if your visiting http://example.com/somescript.php?foo=bar in your browser, REQUEST_URI will be /somescript.php?foo=bar.
Since you spit out that into your html's href parameters, then slap on MORE parameters, you naturally start building up longer and longer urls:
1st request /somescript.php?foo=bar&start=1
^^^^^^^^^^^^^^^^^^^^^^^---request uri for #2
2nd request /somescript.php?foo=bar&start=1&start=2
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---request uri for #2
3rd request /somescript.php?foo=bar&start=1&start=2&start=3
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^request_uri for #3

Related

How do I find the second, or third instance of a character in a string in PHP

I am trying to parse out the middle of the referrer information just to check from where the form submission is coming from.
Consider that the referrer is "https://www.somewebsite.com/someform.php
And what I want to extract is the part between those first two "//" and the next one "/".
I can get the string position, but how can I do a quick piece of code that will just parse out the part I need without several steps?
$ref=strpos($_SERVER['HTTP_REFERER'],'://');
gives me 5 (as the position where the "://" is found.
I want to use something like substr(string,start,length) the part out that is needed to get the pure referrer
the part that says "www.somewebsite.com"
without all the extra lines of code
used it
echo $_SERVER['HTTP_HOST'];

Redirecting to a url by appending query strings to it

I have to capture a query string at the starting of my survey, which i was able to do using php syntax. I now have the query string sitting in php.
My next task is to redirect to another URL at the end of my survey, BUT by appending the same query string I captured before.
For example,
If I have a php field $user='abcdefgh';
And
I need to redirect to another link at the end, say https://en.wikipedia.org/wiki/Stack_Overflow
By adding the query string $user. So the URL now becomes
https://en.wikipedia.org/wiki/Stack_Overflow?id=abcdefgh
Can someone guide me how to accomplish this.
I tried to do it using header in php, but it doesn't seem to work.
Any assistance will be greatly appreciated.
Neeraj
You can try something like this:
$url = https://en.wikipedia.org/wiki/Stack_Overflow;
$user='abcdefgh';
header("location:".$url."?id=".$user);

PHP (Change the pageid to the page name.)

I am making the dynamic website in PHP. While code is running good using pageid.
The url is now like www.google.com/pageid=1
Now, i want to change the url for 1 level pages as www.google.com/page1
for level 2 as www.google.com/page1/page2
for level 3 as www.google.com/page1/page2/page3
While unique address is stored in the my table as page1,page2,page3.
How can it be possible to change url at run time. Please give the examples and comments. So that it may helpful to understand.
Also i want to know if it is possible using the .htaccess file. If possible How .htaccess %{REQUESTED_FILE}% will reach out for my unique url's that are stored in the database.
$URL= "www.google.com/page1"
1) split the string with '/'
$data = explode("/",$URL);
$data[1] will have page1 value
2) replace the string page with ""
$pageId = str_replace("page","", $data[1]);
3) whatever is left is the page id
pageId has the value now.
Use that to query the database.
Another way is to use regex to extract the number from page1 and use it where-ever you want to use it.

GET form in PHP. How to link to the 2nd+ page of results?

I have a POST form in PHP that I'm converting to GET.
The form works and gives me the first page of results without any problems.
But how do I link to the second page? I assume I have to replicate all the GET parameters into the "Next Page" link plus the page number (which the script already handles), but how would I do that?
CLARIFICATION: How do I get all the GET variables from a form onto a link in the page?
simpliest way is too to do something like:
$get = preg_replace("/page=\d+/i", "", $_SERVER['QUERY_STRING']);
$link = "somepage.php?".$get."&page=".($_GET['page']+1);
echo "<a href='".$link."'>Next Page</a>";
That will simply take the get string, remove the page then add the page back in as +1. Please note this would be insecure as people could pass anything in the query string. A better option would be to build the the URL explicitly by checking for each expected $_GET key=>value pair, validating it, then adding it to a link variable. That way any additional bits in the query string wont be echo'd to the page.
EDIT:
Ok so heres a very quick example.
$category = (int)$_GET['cat'];
$keyword = trim($_GET['keyword']);
$keyword = filter_var($keyword, FILTER_SANITIZE_STRING);
$nextlink = "somepage.php?";
$nextlink .= http_build_query(array(
"cat" => $category,
"keyword" => $keyword,
"page" => $page+1
));
So basically you get the GET var's you want, validate them, then just use http_build_query and an associative array to build your query string for the link. The security i put in their is very basic, but typecasting numbers and limiting the amount of crud you can stick into a string is a place to start
Simplistically speaking, you would read them out of the request like this:
$link = 'mypage/?someitem=' . $_GET['someitem'] . '&page=' . ($page + 1);
Although you may not wish to trust the parameters as they may contain an HTML injection or other nasty tricks designed to attack your website.
Isn't it just URL?param1=val1&param2=val2&...?

Jquery, ajax and the ampersand conundrum

I know that I should encodeURI any url passed to anything else, because I read this:
http://www.digitalbart.com/jquery-and-urlencode/
I want to share the current time of the current track I am listening to.
So I installed the excellent yoururls shortener.
And I have a bit of code that puts all the bits together, and makes the following:
track=2&time=967
As I don't want everyone seeing my private key, I have a little php file which takes the input, and appends the following, so it looks like this:
http://myshorten.example/yourls-api.php?signature=x&action=shorturl&format=simple&url=http://urltoshorten?track=2&time=967
So in the main page, I call the jquery of $("div.shorturl").load(loadall);
It then does a little bit of CURL and then shortener returns a nice short URL.
Like this:
$myurl='http://myshorten.example/yourls-api.php?signature=x&action=shorturl&format=simple&url=' . $theurl;
$ch = curl_init($myurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}
echo $data;
All perfect.
Except... the URL which is shortened is always in the form of http://urltoshorten?track=2 - anything after the ampersand is shortened.
I have tried wrapping the whole URL in php's URLencode, I've wrapped the track=2&time=967 in both encodeURI and encodeURIComponent, I've evem tried wrapping the whole thing in one or both.
And still, the & breaks it, even though I can see the submitted url looks like track=1%26time%3D5 at the end.
If I paste this or even the "plain" version with the unencoded url either into the yoururls interface, or submit it to the yoururls via the api as a normal URL pasted into the location bar of the browser, again it works perfectly.
So it's not yoururls at fault, it seems like the url is being encoded properly, the only thing I can think of is CURL possibly?
Now at this point you might be thinking "why not replace the & with a * and then convert it back again?".
OK, so when the url is expanded, I get the values from
var track = $.getUrlVar('track');
var time = $.getUrlVar('time');
so I COULD lose the time var, then do a bit of finding on where the * is in track and then assume the rest of anything after * is the time, but it's a bit ugly, and more to the point, it's not really the correct way to do things.
If anyone could help me, it would be appreciated.
I have tried wrapping the whole URL in php's URLencode
That is indeed what you have to do (assuming by ‘URL’ you mean inner URL being passed as a component of the outer URL). Any time you put a value in a URL component, you need to URL-encode, whether the value you're setting is a URL or not.
$myurl='http://...?...&url='.rawurlencode($theurl);
(urlencode() is OK for query parameters like this, but rawurlencode() is also OK for path parts, so unless you really need spaces to look slightly prettier [+ vs %20], I'd go for rawurlencode() by default.)
This will give you a final URL like:
http://myshorten.example/yourls-api.php?signature=x&action=shorturl&format=simple&url=http%3A%2F%2Furltoshorten%3Ftrack%3D2%26time%3D967
Which you should be able to verify works. If it doesn't, there is something wrong with yourls-api.php.
I have tried wrapping the whole URL in php's URLencode, I've wrapped the track=2&time=967 in both encodeURI and encodeURIComponent, I've evem tried wrapping the whole thing in one or both. And still, the & breaks it, even though I can see the submitted url looks like track=1%26time%3D5 at the end.
Maybe an explanation of how HTTP variables work will help you out.
If I'm getting a page with the following variables and values:
var1 = Bruce Oxford
var2 = Brandy&Wine
var3 = ➋➌➔ (unicode chars)
We uri-encode the var name and the value of the var, ie:
var1 = Bruce+Oxford
var2 = Brandy%26Wine
var3 = %E2%9E%8B%E2%9E%8C%E2%9E%94
What we are not doing is encoding the delimiting charecters, so what the request data will look like for the above is:
?var1=Bruce+Oxford&var2=Brandy%26Wine&var3=%E2%9E%8B%E2%9E%8C%E2%9E%94
Rather than:
%3Fvar1%3DBruce+Oxford%26var2%3DBrandy%26Wine%26var3%3D%E2%9E%8B%E2%9E%8C%E2%9E%94
Which is of course just gibberish.

Categories