if / and statement for URL with strpos - php

I have the following three possible urls..
www.mydomain.com/445/loggedin/?status=empty
www.mydomain.com/445/loggedin/?status=complete
www.mydomain.com/445/loggedin/
The www.mydomain.com/445 part is dynamically generated and is different each time so I can't do an exact match, how can i detect the following...
If $url contains loggedin but DOES NOT CONTAIN either /?status=empty OR /?status=complete
Everything I try fails as no matter what it will always detect the logged in part..
if(strpos($referrer, '?status=empty')) {
echo 'The status is empty';
}
elseif(strpos($referrer, '?status=complete')) {
echo 'The status is complete';
}
elseif(strpos($referrer, '/loggedin/')) {
echo 'The status is loggedin';
}

Slice up the URL into segments
$path = explode('/',$referrer);
$path = array_slice($path,1);
Then just use your logic on that array, the first URL you included would return this:
Array ( [0] => 445 [1] => loggedin [2] => ?status=empty )

You could do something like this:
$referrer = 'www.mydomain.com/445/loggedin/?status=empty';
// turn the referrer into an array, delimited by the /
$url = explode('/', $referrer);
// the statuses we check against as an array
$statuses = array('?status=complete', '?status=empty');
// If "loggedin" is found in the url, and count the array_intersect matches, if the matches = 0, none of the statuses you specified where found
if( in_array('loggedin', $url) && count(array_intersect($url, $statuses)) == 0 )
{
echo 'The user is logged in';
}
// if the complete status exists in the url
else if( in_array('?status=complete', $url) )
{
echo 'The status is complete';
}
// if the empty status exists in the url
else if( in_array('?status=empty', $url) )
{
echo 'The status is empty';
}
I would recommend looking at array_intersect, it is quite useful.
Hope it helps, not sure if this is the best way of doing it, but might spark your imagination.

Strpos is probably not what you want to use for this. You could do it with stristr:
if($test_str = stristr($referrer, '/loggedin/'))
{
if(stristr($test_str, '?status=empty'))
{
echo 'empty';
}
elseif (stristr($test_str, '?status=complete'))
{
echo 'complete';
} else {
echo 'logged in';
}
}
But it's probably easier/better to do it with regular expressions:
if(preg_match('/\/loggedin\/(\?status=(.+))?$/', $referrer, $match))
{
if(count($match)==2) echo "The status is ".$match[2];
else echo "The status is logged in";
}

Related

Check if part of a string is a number

Im building an API which can read messages from a SQL database. I check the URL with the following if statement: if ($uri[0] == "/rooms/1/messages"). The 1 is the room number requested, but there are more rooms than "1".
What I want is an if statement like this: if ($uri[0] == "/rooms/" . $thisHasToBeANumber . "/messages")
I have thought about exploding the URL on the "/" but I dont know from the beginning how much slashes there are in the URL.
My whole function:
function checkUrl()
{
// Variables about URL, first explode with "api" then with "?"
$uri = explode('api', $_SERVER['REQUEST_URI']);
$uri = explode('?', $uri[1]);
// Check the url path for "/rooms/1/messages/" and check request method
if ($uri[0] == "/rooms/ " . $thisHasToBeANumber . "/messages") {
if ($_SERVER["REQUEST_METHOD"] === "GET") {
$roomId = explode('/', $uri[0])[2];
getMessages($roomId);
} else {
header("HTTP/1.0 400");
die("Wrong request method");
}
}
// Check the url path for "/messages/" and check request method
elseif ($uri[0] == "/messages") {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Get POST parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if (!empty($input['content']) && !empty($input['roomId'])) {
$messageContent = $input['content'];
$roomId = $input['roomId'];
$userId = getUserId($_GET['token']);
sendMessage($userId, $messageContent, $roomId);
} else {
header("HTTP/1.0 400");
die("Missing arguments");
}
} else {
header("HTTP/1.0 400");
die("Wrong request method");
}
}
// Check the url path for "/rooms/" and check request method
elseif ($uri[0] == "/rooms") {
if ($_SERVER["REQUEST_METHOD"] === "GET") {
getRoomNames();
} else {
header("HTTP/1.0 400");
die("Wrong request method");
}
}
// Path is not found
else {
header("HTTP/1.0 404");
die("Path not found");
}
}```
I think you are looking for regular expressions.
And preg_match ( documentation ) is the thing you are looking for.
If we do something like this:
if ( ( preg_match( "rooms/([\d]+)/messages", $uri[0], $match ) === 1 ) {
if ($_SERVER["REQUEST_METHOD"] === "GET") {
//$roomId = match[1];
getMessages($match[1]);
} else {
header("HTTP/1.0 400");
die("Wrong request method");
}
}
!Note
The reason why we use preg_match( ... ) === 1 is because of the return value.
I don't know exactly what kind of data you will receive, but it looks like you can use a regular expression. For example, assume that $uri is the string and you want a number in the format: "/room/NUMBER/messages". You can use:
preg_match("~/room/([0-9]+)/messages~", $uri, $matches);
If the pattern fits, $matches[1] will contain the room number.
You can put this into an if-else with:
if(isset($matches[1])) {
$roomnumber = $matches[1];
// do what you want
} else {
// There is no room number
}
I would expect the URL to always come in the same format, so using explode should be safe. You would need to work out what the format was and then extract the number from the right position.
Alternatively, you could use RegEx. That will allow you to be more flexible in extracting the room number. Some example code you could use would be:
$uri = '/room/123/abc'; // test code
if (preg_match('/(^|\/)room\/(\d+)($|\/)/', $test, $matches)===1) {
$roomId = $matches[2];
} else {
// no match
}
To explain, preg_match will take a RegEx pattern and apply it to the URL and return an array of matches. The RegEx in the example will look for the sequence "room/" following a slash or at the beginning of your URL and then followed by one or more numerical digits (which are returned in the array) and finally by either another slash or the end of the string. The numerical digits are returned as the third match.

check if a url is reachable, always returning false

My problem is that it returns an error for every url entered:
The below code takes and checks the url entered, if i enter 'http://eample.com' it would return success but for some reason it returns all urls as unreachable.
<?php
Global $excludeLocal;
$excludeLocal = true; // Whether to exclude checking links on the same host as the plugin resides
// Hook our custom function into the 'shunt_add_new_link' filter
yourls_add_filter( 'shunt_add_new_link', 'churl_reachability' );
// Add a new link in the DB, either with custom keyword, or find one
function churl_reachability( $churl_reachable, $url, $keyword = '' ) {
global $ydb, $excludeLocal;
// Check if the long URL is a different type of link
$different_urls = array (
array ( 'mailto://', 9 ),
array ( 'ftp://', 6 ),
array ( 'javascript://', 13),
array ( 'file://', 7 ),
array ( 'telnet://', 9),
array ( 'ssh://', 6),
array ( 'sip://', 6),
);
foreach ($different_urls as $url_type){
if (substr( $url, 0, $url_type[1] ) == $url_type[0]){
$churl_reachable = true; // No need to check reachability if URL type is different
break;
} elseif ($excludeLocal) {
if (substr($url, 0, strlen('http://'.$_SERVER['SERVER_NAME'])) == 'http://'.$_SERVER['SERVER_NAME']) {
$churl_reachable = true;
break;
}
}
}
// Check if the long URL is a mailto
if ($churl_reachable == false){
$churl_reachable = churl_url_exists( $url ); // To do: figure out how to use yourls_get_remote_content( $url ) instead.
}
// Return error if the entered URL is unreachable
if ( $churl_reachable == false ){
$return['status'] = 'fail';
$return['code'] = 'error:url';
$return['message'] = 'The entered URL is unreachable. Check the URL or try again later.';
$return['statusCode'] = 200; // regardless of result, this is still a valid request
return yourls_apply_filter( 'add_new_link_fail_unreachable', $return, $url, $keyword, $title );
} else {
return false;
}
}
function churl_url_exists( $churl ){
$handle = #fopen($churl, "r");
if ($handle === false)
return false;
fclose($handle);
return true;
}
is there something i might have did wrong ?
Any help is appreciated
check allow_url_fopen directive in your php.ini
Try to run the command $handle = fopen($churl, "r"); without a # symbol and see the error

PHP Array to return a URL

I am trying to return a specific iframe URL depending ont he input of a specific number of zip codes.
Example- zip code x returns url x
zip code y returns url y
I have a list of several zip codes per URL. The URL purpose is to redirect to a specific (3rd party) page based on the location input from the user.
Here is what I have so far:
<?php
$userzip = $_POST['ZipCode'];
echo $userzip;
$array = array(
'22942' => 'URL1',
'22701' => 'URL2');
// print_r($array);
foreach( $array as $key => $value ){
// echo "Output of Key=>Value pair:\r\n";
// echo $key . "->" . $value . "\r\n";
// echo "Testing $key...\r\n\r\n";
if(preg_match('/23456/',$key)){
echo "Service exists in: $value\r\n";
break;
} else {
echo "No Match for $key.\r\n\r\n";
}
}
?>
So, my first mistake is that only the zip code entered is returned for the moment. I can comment that out but left it in to show my thinking. Help?
If I have understood your request correctly then this code should work:
<?php
$userzip = $_POST['ZipCode'];
echo $userzip;
$array = array(
'22942' => 'URL1',
'22701' => 'URL2');
// print_r($array);
foreach( $array as $key => $value ){
// echo "Output of Key=>Value pair:\r\n";
// echo $key . "->" . $value . "\r\n";
// echo "Testing $key...\r\n\r\n";
if(strstr($key, $userzip)) {
echo "Service exists in: $value\r\n";
break;
} else {
echo "No Match for $key.\r\n\r\n";
}
}
?>
To actually handle the redirect then after echo "Service exists in: $value\r\n"; you can use one of these options:
header("Location: " . $value);
Or if you want to use the iFrame approach you have mentioned in the comment then:
echo '<iframe src="'.$value.'" border="0" frameborder="0" style="width:500px; height:700px;"></iframe>';
You should try to avoid loops as much as possible. You can easily check if a key/value exists in an array with isset:
$userzip = $_POST['ZipCode'];
echo $userzip;
if( isset($zipcodesA[$userzip]) ){
echo "Service exists in A: ".$array[$userzip]."\n";
} elseif( isset($zipcodesB[$userzip]) ){
echo "Service exists in B: ".$array[$userzip]."\n";
}elseif( isset($zipcodesC[$userzip]) ){
echo "Service exists in C: ".$array[$userzip]."\n";
} else {
echo "No Match for $userzip.\n\n";
}
In this case, you have no need to check every value in the array, just if one specific exists.

How to check for existence of parameter in url?

I want to output a message,
whenever the url includes any parameter that start with p2, for example in all the following instances:
example.com/?p2=hello
example.com/?p2foo=hello
example.com/?p2
example.com/?p2=
I've tried:
if (!empty($GET['p2'])) {
echo "a parameter that starts with p2 , is showing in your url address";
} else {
echo "not showing";
}
this should cover all your cases
$filtered = array_filter(array_keys($_GET), function($k) {
return strpos($k, 'p2') === 0;
});
if ( !empty($filtered) ) {
echo 'a paramater that starts with p2 , is showing in your url address';
}
else {
echo 'not showing';
}
Just iterate over the $_GET array and add a condition for the key to start with p2 when matching do what you need to do.
foreach($_GET as $key=>$value){
if (substr($key, 0, 2) === "p2"){
// do your thing
print $value;
}
}
substr($key,0,2) takes the first two characters from the string
try
if (isset($GET['p2'])) {
echo "a paramater that starts with p2 , is showing in your url address";
} else {
echo "not showing";
}
fastest way is
if(preg_match("/(^|\|)p2/",implode("|",array_keys($_GET)))){
//do stuff
}

PHP - Apply code to subpages

I have this code:
<?php $url = JURI::getInstance()->toString();
if ($url == "http://example.com/news/latest/"){
echo "This is latest page";
} else {
echo "This is not latest page";
}
?>
What I'm trying to do is instead of 'http://example.com/news/latest/', how can I select the pages/items under /latest/. If it makes any more sense, here's a syntax:
if ($url == "http://example.com/news/latest/" + ANYTHING UNDER THIS)
I cannot use not equal to ($url !=) since it will include other parent pages not equal to /latest/. I just want what's under it. If anyone understands it, I need help on how to put it into code.
Update:
What I'm trying to do is if the page is example.com/news/latest, it will echo "Latest". And if for example, I am in example.com/news/latest/subpage1/subpage2, it will echo "You are in a page that is under Latest." Anything beyond "Latest" will echo that.
$str = 'example.com/news/latest/dfg';
preg_match('/example.com\/news\/([^\/]+)\/?(.*)/', $str, $page);
if(isset($page[2]) && $page[2])
echo 'You are under: ' , $page[1];
elseif(isset($page[1]))
echo 'At: ' , $page[1];
else
echo 'Error';
Edit: after clarification switched to regular expression.
Use a regular expression:
$matches = array();
if((preg_match('#http://example\.com/news/latest/(.*)#', $url, $matches)) === 1) {
if(strlen($matches[0]) > 0) {
echo "You're at page: $matches[0]";
} else {
echo "You're at the root";
}
} else {
// Error, incorrect URL (should not happen)
}
EDIT: Fixed, untested so you may have to tweak it a little

Categories