I want to write a PHP script which will first detect URL's and see if they have sub dir or not, if they are simple URL like site.com then it would write 1 in one of the DB's table but if the URL is something like this site.com/images or site.com/images/files then it should'nt do the query..
EDIT: Answer by Mob it works but doesnt work if there are more than one url
$url = "http://lol.com";
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
echo "yeah";
} else {
echo "nah";
}
Use parse_url
$url = "http://lol.com";
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
echo "yeah";
} else {
echo "nah";
}
EDIT:
To parse multiple urls;
Store the urls in an array.
Use a loop to iterate over the array while passing the values to a function that performs the check
Here:
<?php
$arr = array("http://google.com",
"http://google.com/image/",
"http://flickr.com",
"http://flickr.com/image" );
foreach ($arr as $val){
echo $val." ". check($val)."\n";
}
function check ($url){
$v = parse_url($url);
if (isset( $v['path']) && (!empty($v['path'])) && ($v['path'] != "/") ){
return "true";
} else {
return "false";
}
}
?>
The output is :
http://google.com false
http://google.com/image/ true
http://flickr.com false
http://flickr.com/image true
Try strpos()
Syntax: strpos($haystack, $needle)
You could use something like:
if (!strpos($url, '/'))
{
do_query();
}
edit
Remember to strip the slashes in http://, of course.
$_SERVER is what you need. I'll let you google it.
Related
I have an if in a foreach in a while loop. I'm searching for a string in another string of text.
$base = 'someurl';
$url = $base;
while(1){
$json = json_decode(file_get_contents($url));
$more = $json->next_page;
$next = $json->next_page_number;
if($more){
$url = $base.'&page='.$next;
}else{
break;
}
foreach($json as $data){
$c = $data->text; // search in
$s = 'string';
$t = 'prefix1'.$s; // search for
$m = 'prefix2'.$s; // search for
if( (strpos($c, $t) || strpos($c, $m)) !== false ){
echo '<p>hello, i found one or more ($t and/or $m) of the search criteria in the text string $c .</p>';
break;
}
}
}
The problem is that I get the echo from the if statement twice :(
What I want to achieve is to only make the echo happen ONCE, if $t and/or $m is present in $c.
Well, i guess you're receiving the echo twice because you found 2 records that match your condition, is that possible?
If so, and you only want to check that your condition matches at least once on the array, you could break the foreach after you found your first match, like:
if( ( strpos( $c, $t ) || strpos( $c, $m ) ) !== false ){
echo '<p>hello, I was told I was true</p>';
break;
}
OK, so found a working solution for my particular problem (although I'm still not clear as to why the if statements response got echoed twice?).
Using preg_match instead of strpos gave me a working solution :)
if(preg_match('('.$t.'|'.$m.')', $c) === 1){
// tis' the truth echoed thru eternity
}
I have a function to clean a link when I filter my search results
function cleanLink($url,$remove){
$aQ = explode("&",str_replace("?", "", $url));
foreach ($aQ as $part) {
$pos = strpos($part, $remove);
if ($pos === false)
$queryClean[] = $part;
}
$line = implode("&", $queryClean);
return "?".$line;
}
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
This works fine, for example if my url is
www.mysite.com/?q=wordx
I want to add an "order alphabetic desc" so my url returns
www.mysite.com/?q=wordx&order=desc
but if my query string is empty (e.g. www.mysite.com/) the return is
www.mysite.com/?&q=word
How can I remove the & if the query string is empty?
Change
if ($pos === false)
to
if ($pos === false && $part)
to omit empty $part string (will evaluate as false). You also should initialize $queryClean
$queryClean = array();
You can use parse_str and http_build_str to remove a parameter from the query string. You just to make sure pecl_http >= 0.23.0 is installed
function cleanLink($queryString, $remove)
{
parse_str($queryString, $query);
if (array_key_exists($remove, $query)) {
unset($query[$remove]);
}
return http_build_str($query);
}
$linkACTUAL = $_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q");
echo $linkACTUAL . "&q=" . $word;
For more information see http://php.net/manual/en/function.http-build-str.php and http://php.net/manual/de/function.parse-str.php
If your function is running fine when there are query string then you can simply put your function call inside if statement like
if(!empty($_GET))
{
$linkACTUAL = "".$_SERVER["QUERY_STRING"];
cleanLink($linkACTUAL, "q=");
echo $linkACTUAL."&q=".$word;
}
Updated:
echo (false === strpos($linkACTUAL, "&")) ? $linkACTUAL."q=".$word : $linkACTUAL."&q=".$word;
I'm trying to check if the following is empty or not.
{"players":""}
I have a function that gets that from an api/site and.. well, heres the code.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
}
However, using !=, empty(), or isset(), I still get an empty string, example:
https://minotar.net/avatar//32
Where it should be..
https://minotar.net/avatar/Notch/32
When it's empty, I'd like it to just return 'empty'.
I'm not sure what I'm doing wrong. Any ideas?
In pure php you can check the url segments like
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
if($segments[2] == '') {
}
//or
if(empty($segments[2])) {
}
//or do your condition
if you are using codeigniter you might say
if(empty($this->uri->segment(2)))
But be sure you loaded the url helper
Hope I understand your question!
Since you were able to have some output, see my changes in the codes.
function getPlayers($server) {
// Fetches content from url and json_decodes it
$playersList = getUrl('http://api.iamphoenix.me/list/?server_ip=' . $server);
// Attempting to check if it's empty.
if ($playersList != "") {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
// check conversion
if(is_array($players) && !empty($players){
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
} else {
return 'empty';
}
}
You should do this;
print_r($playersList);
just after you set it to see what it actually is. My guess is that you are not getting what you suspect from the getURL call.
Add one more equals sign to take type comparison into account as well
if ($playerList !== '')
try this
if (isset($playersList) && is_array($playersList) && !empty($playersList)) {
// convert list of comma-separated names into array
$players = explode(',', $playersList->players);
foreach ($players as $player) {
echo '<img title="'.$player.'" src="https://minotar.net/avatar/'.$player.'/32">';
}
} else {
return 'empty';
}
I have a path that I want to check for in a url. How would I isolate
'pages/morepages/'
http://www.mypage.com/pages/morepages/
I've tried running a parse url function on my url and then I get the path. I don't know how to access that key in that array though. For example..
$url = 'http://www.mypage.com/pages/morepages/';
print_r(parse_url($url));
if ($url['path'] == '/pages/morepages/') {
echo 'This works.';
};
I want to run an if conditional on if that path exists, but I am having trouble accessing it.
If you're just looking for one string within another, strpos() will work pretty well.
echo strpos( $url, $path ) !== false ? 'Exists' : 'Does Not Exist' ;
something like find in string ?
if ( strpos($url['path'], '/pages/morepages/') !== false ){
//echo "this works";
}
Here you go
$url = 'http://www.mypage.com/pages/morepages/';
if (strpos($url, '/pages/morepages/') !== false) {
echo "found";
} else {
echo "not found";
}
You can simply use
if (parse_url($url['path'], PHP_URL_PATH) == '/pages/morepages/') {
echo 'This works.';
} // No semicolon
It's probably better to use strpos() though, which is a LOT faster.
Just assign function's result to any variable:
$parts = parse_url($url);
if ($parts['path'] == '/pages/morepages') {
}
Parse_url needs to return something to a new array variable. So use:
$parsedUrl = parse_url($url));
if ($parsedUrl['path'] == '/pages/morepages/') {
echo 'This works.';
};
You are not assigning the output of parse_url to a variable. $url is still equal to the string (parse_url returns an array, it doesn't modify the string passed in).
$url = parse_url($url);
I have a form that passes something like in a URL
?choice=selection+A&choice=selection+C
I'm collecting it in a form with something like (I remember that $_GET is any array)
$temp = $_GET["choice"];
print_r($temp);
I'm only getting the last instance "selection C". What am I missing
I am assuming 'choice' is some kind of multi-select or checkbox group? If so, change its name in your html to 'choice[]'. $_GET['choice'] will then be an array of the selections the user made.
If you don't intend to edit the HTML, this will allow you to do what you're looking to do; it will populate the $_REQUEST superglobal and overwrite its contents.
This assumes PHP Version 5.3, because it uses the Ternary Shortcut Operator. This can be removed.
$rawget = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : false;
$rawpost = file_get_contents('php://input') ?: false;
$target = $rawget;
$_REQUEST = array();
if ($target !== false) {
$pairs = explode('&',$rawget);
foreach($pairs as $pair) {
$p = strpos($pair,'=');
if ($p === false && !empty($pair)) {
$_REQUEST[$pair] = null;
}
elseif ($p === 0 || empty($pair)) {
continue;
}
else {
list($name, $value) = explode('=',$pair,2);
$name = preg_replace('/\[.*\]/','',urldecode($name));
$value = urldecode($value);
if (array_key_exists($name, $_REQUEST)) {
if (is_array($_REQUEST[$name])) {
$_REQUEST[$name][] = $value;
}
else {
$_REQUEST[$name] = array($_REQUEST[$name], $value);
}
}
else {
$_REQUEST[$name] = $value;
}
}
}
}
As it stands, this will only process the QueryString/GET variables; to process post as well, change the 3rd line to something like
$target = ($rawget ?: '') . '&' . ($rawpost ?: '');
All that having been said, I'd still recommend changing the HTML, but if that's not an option for whatever reason, then this should do it.