Constructing a URL based on existing variables - php

I'm a bit of a PHP newbie, and I'm trying to do what I believe is quite a complicated operation on a website. So I need your help :)
What I want to do is request a specific page for each client, the only URL variables involved are at the end, as normal.
Basically my variables have been set previously in the script, what I want to say is;
The URL is http://site.com/index.php?image=$clientnumber Somehow.
if you guys could give me some insight on how to do this, that would be great!

You can use the sprintf function to do this:
$url = sprintf('http://site.com/index.php?image=%s', $clientnumber);

PHP String Operators
$new_url = "http://site.com/index.php?image=$clientnumber";
or
$new_url = 'http://site.com/index.php?image=' . $clientnumber;

$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data) . "\n";
Results in:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
For your needs:
$data = array('image'=> $clientnumber);
echo 'index.php?' . $data;
Will give you:
index.php?image=878787283

Related

PHP Parse URL From Current URL

I am trying to parse url and extract value from it .My url value is www.mysite.com/register/?referredby=admin. I want to get value admin from this url. For this, I have written following code. Its giving me value referredby=admin, but I want only admin as value. How Can I achieve this? Below is my code:
<?php
$url = $current_url="//".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
setcookie('ref_by', parse_url($url, PHP_URL_QUERY));
echo $_COOKIE['ref_by'];
?>
You can use parse_str() function.
$url = "www.mysite.com/register/?email=admin";
$parts = parse_url($url);
parse_str($parts['query'], $query);
echo $query['email'];
Try this code,
$url = "www.mysite.com/register/?referredby=admin";
$parse = parse_url($url, PHP_URL_QUERY);
parse_str($parse, $output);
echo $output['referredby'];
$referred = $_GET['referredby'];
$referred = "referredby=admin";
$pieces = explode("=", $referred);
echo $pieces[1]; // admin
I don't know if it's still relevant for you, but maybe it is for others: I've recently released a composer package for parsing urls (https://www.crwlr.software/packages/url). Using that library you can do it like this:
$url = 'https://www.example.com/register/?referredby=admin';
$query = Crwlr\Url\Url::parse($url)->queryArray();
echo $query['referredby'];
The parse method parses the url and returns an object, the queryArray method returns the url query as array.
Is not a really clean solution, but you can try something like:
$url = "MYURL";
$parse = parse_url($url);
parse_str($parse['query']);
echo $referredby; // same name of the get param (see parse_str doc)
PHP.net: Warning
Using this function without the result parameter is highly DISCOURAGED and DEPRECATED as of PHP 7.2.
Dynamically setting variables in function's scope suffers from exactly same problems as register_globals.
Read section on security of Using Register Globals explaining why it is dangerous.

Cut some word from php available?

Cut some word from php available ?
First access to page for example
www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success
From my php code, i will get $curreny_link_redirect = test.php?ABD_07,_oU_876.00/8999&message=success
And i want to get $curreny_link_redirect_new = test.php?ABD_07,_oU_876.00/8999
( Cut &message=success )
How can i do ?
<?PHP
$current_link = "$_SERVER[REQUEST_URI]";
$curreny_link_redirect = substr($current_link,1);
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
echo $curreny_link_redirect_new;
?>
Your str_replace call is inverse of what it should be. What you want to replace should be the first parameter, not the second.
//Wrong
$curreny_link_redirect_new = str_replace('', '&message=success', $curreny_link_redirect);
//Right
$curreny_link_redirect_new = str_replace('&message=success','', $curreny_link_redirect);
While simple way to do this is to use regex (or even static with str_replace()), I recommend to use built-in functions for url handling. This may be useful when working with complex parameters or multiple parameters:
$data = 'www.mysite.com/test.php?ABD_07,_oU_876.00/8999&message=success';
$url = parse_url($data);
parse_str($url['query'], $url['query']);
//now, do something with parameters:
unset($url['query']['message']);
$url['query'] = http_build_query($url['query']);
$url = http_build_url($url);
-please, note, that http_build_url() is a PECL function (pecl_http to be precise). The way above may look more complex, but it has benefits - first, as I've already mentioned, this will be easy to modify for working with complex parameters or multiple parameters. Second, it will produce valid url - i.e. encode such things as slashes, spaces, e t.c. - in result. Thus, result will always be correct url.
Do like this
<?php
$str = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $str = array_shift(explode('&',$str));
Try this:
$current_link_path = substr($_SERVER['PHP_SELF'], 1);
$params = $_GET;
if ($params['message'] == 'success') {
unset($params['message']);
}
$current_link_redirect = $current_link_path . '?' . http_build_query($params);
Maybe not an answer, but a disclaimer for future visitors:
1) I would strongly recommend the function: http://pl1.php.net/parse_url.
And in that case:
$current_link = "$_SERVER[REQUEST_URI]";
$arguments = explode('&', parse_url($current_link, PHP_URL_QUERY));
print_r($arguments);
2) To build new url, use http://pl1.php.net/manual/en/function.http-build-url.php. This is the best, future modifications ready solution I think.
In that case this solution is a little overkill, but these functions are really great, and worth to introduce here.
Best regards

Request url on a save way

I would like to read a url. www.domain.com?cookie=set&redirect=yes
Now I want to use $ _SERVER['REQUEST_URI'] but this does not work with strip_tags and htmlspecialchars.
Also many I read that you should watch for XSS.
Does anyone know how to save a URL can be used by GET?
$url = "http://'.$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI];
$url = strip_tags($url);//doesnt work
$url = htmlspecialchars($url);//doesnt work
Thanks!
Edit to (doesnt work):
$url = "http://".$_SERVER[HTTP_HOST]."".$_SERVER[REQUEST_URI];
$url = strip_tags($url);
echo $url;
for example
www.domain.com?cookie=set&redirect=yes
output => index.php?cookie=se%3Cscript%3Et&re%3Cb%3Ed%3C/b%3Eirect=yes
This line
$url = "http://'.$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI];
Needs to be either
$url = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
or
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
The way you are currently doing it will not concatenate the data correctly.
Issues with the your line:
Your mixing quotes around the protocol " to open and ' to close
You are not quoting the $_SERVER params e.g $_SERVER['PARAM']
You are not joining the 2 $_SERVER vars with anything so you'll get a syntax error

How to write a PHP script to find the number of indexed pages in Google?

I need to find the number of indexed pages in google for a specific domain name, how do we do that through a PHP script?
So,
foreach ($allresponseresults as $responseresult)
{
$result[] = array(
'url' => $responseresult['url'],
'title' => $responseresult['title'],
'abstract' => $responseresult['content'],
);
}
what do i add for the estimated number of results and how do i do that?
i know it is (estimatedResultCount) but how do i add that? and i call the title for example this way: $result['title'] so how to get the number and how to print the number?
Thank you :)
I think it would be nicer to Google to use their RESTful Search API. See this URL for an example call:
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:stackoverflow.com&filter=0
(You're interested in the estimatedResultCount value)
In PHP you can use file_get_contents to get the data and json_decode to parse it.
You can find documentation here:
http://code.google.com/apis/ajaxsearch/documentation/#fonje
Example
Warning: The following code does not have any kind of error checking on the response!
function getGoogleCount($domain) {
$content = file_get_contents('http://ajax.googleapis.com/ajax/services/' .
'search/web?v=1.0&filter=0&q=site:' . urlencode($domain));
$data = json_decode($content);
return intval($data->responseData->cursor->estimatedResultCount);
}
echo getGoogleCount('stackoverflow.com');
You'd load http://www.google.com/search?q=domaingoeshere.com with cURL and then parse the file looking for the results <p id="resultStats" bit.
You'd have the resulting html stored in a variable $html and then say something like
$arr = explode('<p id="resultStats"'>, $html);
$bottom = $arr[1];
$middle = explode('</p>', $bottom);
Please note that this is untested and a very rough example. You'd be better off parsing the html with a dedicated parser or matching the line with regular expressions.
google ajax api estimatedResultCount values doesn't give the right value.
And trying to parse html result is not a good way because google blocks after several search.
Count the number of results for site:yourdomainhere.com - stackoverflow.com has about 830k
// This will give you the count what you see on search result on web page,
//this code will give you the HTML content from file_get_contents
header('Content-Type: text/plain');
$url = "https://www.google.com/search?q=your url";
$html = file_get_contents($url);
if (FALSE === $html) {
throw new Exception(sprintf('Failed to open HTTP URL "%s".', $url));
}
$arr = explode('<div class="sd" id="resultStats">', $html);
$bottom = $arr[1];
$middle = explode('</div>', $bottom);
echo $middle[0];
Output:
About 8,130 results
//vKj
Case 2: you can also use google api, but its count is different:
https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=ursitename&callback=processResults
https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=site:google.com
cursor":{"resultCount":"111,000,000","
"estimatedResultCount":"111000000",

php escaping when I don't need it to

I've got an issue whereby PHP is escaping where I really don't want it to in this code:
$url_ = stripslashes(((substr(strtolower($url),0,7)!="http://")? "http://".$url:$url));
$host = $this->googleDomains[mt_rand(0,count($this->googleDomains)-1)];
$target = "/search?";
$querystring = sprintf("client=navclient-auto&ch=%s&features=Rank&q=%s",
$this->CheckHash($this->HashURL($url_)),urlencode("info:".$url_));
$contents="";
$this->debugRes("host", $host);
$this->debugRes("query_string", $querystring);
$this->debugRes("user_agent", $this->userAgent);
thus producing a URL like this which causes the script to fail:
{"urls":[{"url":"hostcule.com","converted_url":"http:\/\/toolbarqueries.google.com\/search??client=navclient-auto&ch=74451333464&features=Rank&q=info%3Ahttp%3A%2F%2Fhostcule.com"}]}
How do I stop it?
Magic Quotes are Off.
Here's the $url comes from:
foreach (preg_split('#[\r\n]+#', $_POST['urls']) as $url) {
$url = trim($url);
if ($url)
$_SESSION['converted_urls'][] = array('url' => $url, 'converted_url' => $pr->GetPR($url, true, true));
}
At this stage, $_POST['urls'] looks like:
{"urls":[{"url":"hostcule.com","converted_url":"http:\/\/www.google.com\/search??client=navclient-auto&ch=74451333464&features=Rank&q=info%3Ahttp%3A%2F%2Fhostcule.com"}]}
whilst $url looks like
{"urls":[{"url":"hostcule.com","converted_url":"http:\/\/www.google.com\/search??client=navclient-auto&ch=74451333464&features=Rank&q=info%3Ahttp%3A%2F%2Fhostcule.com"}]}
There is nothing in that code that would produce the code you quote.
My suspicion is that $url already contains the garbled http\/\/, and therefore your http:// recognizing mechanism never triggers.
You need to step back and look where $url comes from. There is where your problem will be.
The code you have there doesn't do any escaping at all. You'll need to post what you do to that $url_ after this line.
use ' instead of "

Categories