Detect if URL equals to value and preforme action - php

I want to make action if the current url only equals to this: https://www.example.co.il/index.php?id=1000&2222
$url = 'https://www.example.co.il/index.php?id=1000';
if(strpos($url,'&2222'))
{
// Do something
echo "2222";
}
else
{
// Do Nothing
}

To exactly do what you are asked, try this
//actual link (http or https)
$actualUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = 'https://www.example.co.il/index.php?id=1000';
if($actualUrl === $url) {
//do something
}
But if you just want to retrieve the id :
$id = $_GET('id');
//return 1000 in your case

You're able to read the parameters in the URL using the $_GET object. It lists the keys and values in the querystring, i.e. in your example,
https://www.example.co.il/index.php?id=1000
if you use:
print $_GET['id'];
you'll see 100.
so you could simply check for the existence of the key 2222:
if (isset($_GET['2222'])) { /** do something **/ }
bear in mind, this is only the case if you're actually reading a URL the script is running on.
your method of searching for a string within the URL is appropriate if you simply want to match a value in a string, whether its a URL or not.

USE THIS
// Assign your parameters here for restricted access
$valid_url = new stdClass();
$valid_url->scheme = 'https';
$valid_url->host = 'www.example.co.il';
$valid_url->ids = array(1000,2222);
$url = 'https://www.example.co.il/index.php?id=1000&2222';
$urlinfo = parse_url($url); // pass url here
$ids = [];
parse_str(str_replace('&', '&id1=', $urlinfo['query']), $ids);
if($urlinfo['scheme'] == $valid_url->scheme && $urlinfo['host'] == $valid_url->host && count(array_intersect($valid_url->ids, $ids)) == count($valid_url->ids)){
echo 'valid';
// Do something
}else{
echo 'in valid';
// error page
}

Related

Why Re-Arranging Code Outputs Differently?

Good Day,
Below I have provided 2 codes, which I did not write but grabbed from a forum. I really need to learn the solution to this new mystery. Both make use of the urlencode(). They are nearly the same code.
I notice that, only the 1st code's output is normal and not encoded while the 2nd one's output is encoded. Why ?
Since both are making use of the urlencode() then shouldn't both their outputs be in encoded format ? This has been greatly puzzling me for days now. I give-up. What's the mystery behind this ?
1st Code:
$url = 'http://nogdog.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=12';
echo prepare_url($url) . "\n";
function prepare_url($url) {
$url_parts = parse_url($url);
if($url_parts === false or empty($url_parts['host'])) {
return false;
}
$url_out = preg_match('/^https?/i', $url_parts['scheme']) ? strtolower($url_parts['scheme']) : 'https';
$url_out .= "://{$url_parts['host']}{$url_parts['path']}";
if(!empty($url_parts['query'])) {
parse_str($url_parts['query'], $query_parts);
foreach($query_parts as $q_key => $q_value) {
$query_string_parts[] = urlencode($q_key).'='.urlencode($q_value);
}
$url_out .= '?'.implode('&', $query_string_parts);
}
return $url_out;
}
2nd Code:
function prepare_url2($url) {
$url_parts = parse_url($url);
if($url_parts === false or empty($url_parts['host'])) {
return false;
}
// re-assemble the start of url string
$url_start = preg_match('/^https?/i', $url_parts['scheme']) ? strtolower($url_parts['scheme']) : 'https';
$url_start .= "://{$url_parts['host']}{$url_parts['path']}";
// rawurlencode the start of url string
$url_out = rawurlencode($url_start);
if(!empty($url_parts['query'])) {
parse_str($url_parts['query'], $query_parts);
foreach($query_parts as $q_key => $q_value) {
// assemble and check if value is numeric
$query_string_parts[] = urlencode($q_key).'='.(is_numeric($q_value) ? intval($q_value) :urlencode($q_value));
}
$url_out .= '?'.implode('&', $query_string_parts);
}
return $url_out;
}
$url = 'http://zorg.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=13';
echo prepare_url2($url);
NOTE
The difference between the two codes are that, the 1st one defines the $url and calls the prepare_url() function at the top. (Before the prepare_url() function's code).
$url = 'http://nogdog.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=12';
echo prepare_url($url) . "\n";
While, the 2nd one defines the $url and calls the prepare_url() function at the bottom. (After the prepare_url() function's code).
$url = 'http://zorg.com/cat/subcat?var 1=value 1&var2=2&this other=thing&number is=13';
echo prepare_url($url);
Apart from that, both codes are the same.
So, if both the codes are the same (so to speak), then why does the 1st code output like this:
http://nogdog.com/cat/subcat?var_1=value+1&var2=2&this_other=thing&number_is=12
And, why does the 2nd code output like this:
http%3A%2F%2Fzorg.com%2Fcat%2Fsubcat?var_1=value+1&var2=2&this_other=thing&number_is=13

PHP Not Running On Page Until Refresh

bit of a strange one that I've not been able to resolve for months so I finally have given in and have come here for the answer. Hopefully.
I have the below shortcode that when ran returns the phone number depending on what variable has a value. This PHP code works as expected, the one thing that doesn't work as expected however, is the first ever page load.
When someone goes to the site for the first time (or in incognito mode) the shortcode doesn't output anything, however, refresh the page just once and it'll display the output of the correct value and I have no idea why.
<?php function gw_cookie($atts) {
extract(shortcode_atts(array(
"value" => ''
), $atts));
$getVariable = isset($_GET[$value]) ? $_GET[$value] : '';
$newGetVariable = str_replace('_', ' ', $getVariable);
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
$acfField = get_field('page_cookie_'.$value.'');
$optionsACF = get_field('options_company_details', 'options');
$area = $optionsACF['options_area'];
$phone = $optionsACF['options_telephone'];
if(!empty($cookiePhone) && $cookiePhone !== 'undefined') { //If cookie is not empty do the following
echo '1';
} elseif(!empty($newGetVariable)) { //If cookie is empty and get variable is not
echo '2';
} elseif($acfField) { //If ACF field is not empty do the following
echo '3';
} elseif ($value == "phone") {
return '4';
}
} add_shortcode("gw-cookie", "gw_cookie");
This codes file is being imported into the functions.php file using the following line:
require_once( __DIR__ . '/shortcodes/gw-cookies.php' );
A cookie itself would be created on the first run and your criteria requires cookiePhone which is why you have to refresh to make it work.
As per the comments, change:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : '';
to:
$cookiePhone = isset($_COOKIE[$value]) ? $_COOKIE[$value] : NULL;

POST without POST data?

I am using the following statement to check for post data and set a variable if it comes through via the URL:
if($_SERVER['REQUEST_METHOD']=='POST')
{
$sort = $_GET['sort'];
} else {
$sort = "mgap_ska_id";
}
I need the variable to be assigned a value via POST, but only if the value is passed through the URL. If the URL doesn't contain the variable, the value needs to the a string I can pass to a query. Is it better to use if/then or is some other method better?
Thanks
You have two conditions:
If it's a post request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
Use the get variable if present
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'mgap_ska_id';
Just put them together:
$sort = 'default'; // If it's a get request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'mgap_ska_id';
}
just check
if(isset($_GET['sort']){
$sort = $_GET['sort'];
}
else{
$sort = "mgap_ska_id";
}
but don't forget to check for valid data. Never trust a users input.
also you may try following will work with POST and GET Methods
if(isset($_REQUEST['sort']){
$sort = $_REQUEST['sort'];
}
else{
$sort = "mgap_ska_id";
}
For your reference
You should use $_GET when someone is requesting data from your
application.
And you should use $_POST when someone is pushing (inserting or
updating ; or deleting) data to your application.
Either way, there will not be much of a difference about performances : the difference will be negligible, compared to what the rest of your script will do.
Make sure you have a form input field named "sort":
$sort = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
// Sent by POST
$sort = $_POST['sort'];
} else if ($_SERVER['REQUEST_METHOD']=='GET'){
// Sent by GET
$sort = $_GET['sort'];
} else {
// Neither - set a default.
$sort = "mgap_ska_id
}
echo $sort;

PHP GET String with explode and if statements

I am writing what I thought would be a simple script but I am stuck.
The scenario is that I want to create 2 strings from the GET request.
eg: domain.com/script.php?Client=A12345
In script.php it needs to grab the "Client" and create 2 variables. One is $brand and needs to grab the A or B from the URL. The Other is $id which needs to grab the 12345 from the URL.
Now, after it has these 2 variables $brand and $id it needs to have an if statement to redirect based on the brand like below
if ($brand=="A") {
header('Location: http://a.com');
}
if ($brand=="B") {
header('Location: http://b.com');
At the end of each URL I want to apend the $id though and I am unsure on how to do this.
So for example I would access the script at domain.com/script?Client=A1234 and it needs to redirect me to a.com/12345
Thanks in advance!
$fullCode = $_REQUEST['Client'];
if(strpos($fullCode, 'A') !== false) {
$exp = explode('A',$fullcode);
header('Location: http://a.com/' . $exp[1]);
}
else if(strpos($fullCode, 'B') !== false) {
$exp = explode('B',$fullcode);
header('Location: http://b.com/' . $exp[1]);
}
else {
die('No letter occurence');
}
You can easily do,
$value = $_GET['Client'];
$brand = substr($value, 0, 1);
$rest = substr($value, 1, strlen($brand)-1);
now you have the first character in $brand string and you can do the if statement and redirect the way you want...
You mean like this?
Notice: this will only work if brand is just 1 character long. If that's not the case, please give better examples.
<?php
$client = $_GET['Client'];
$brand = strtolower(substr($client, 0, 1));
$id = substr($client, 1);
if ($brand == 'a')
{
header("Location: http://a.com/$id");
}
elseif ($brand == 'b')
{
header("Location: http://b.com/$id");
}
?>
Try using:
preg_match("/([A-Z])(\d*)/",$_GET['Client'],$matches);
$matches[1] will contain the letter and $matches[2] will contain your id.
Then you can use:
if ($matches[1]=="A")
{
header('Location: http://a.com/{$matches[2]}');
}
if ($matches[1]=="B")
{
header('Location: http://b.com/{$matches[2]}');
}
suggest you could also try
$requested = $_GET["Client"];
$domain = trim(preg_replace('/[^a-zA-Z]/',' ', $requested)); // replace non-alphabets with space
$brand = trim(preg_replace('/[a-zA-Z]/',' ', $requested)); // replace non-numerics with space
$redirect_url = 'http://' . $domain . '/' . $brand;
header('Location:' . $redirect_url);
but it'd be better if you could get the domain name and brand as two individual parameters and sanitize them individually before redirecting them to prevent the overhead of extracting them from a single parameter.
Note: this expression might be useless when the domain name itself has numerics and because the Client is obtained through get a good deal of validation and sanitation would be required in reality.
$brand = strtolower($_GET['Client'][0]);
$id = substr($_GET['Client'], 1);
header("Location: http://{$brand}.com/{$id}");
If for some purpose you want to use explode, then you need to have a separator.
Let's take '_' as the separator, so your example would be something like this: domain.com/script.php?Client=A_12345
$yourstring = explode("_",$_GET["Client"]);
echo $yourstring[0];
//will output A
echo $yourstring[1];
//will output 12345
//your simple controller could be something like this
switch($yourstring[0]){
case: 'A':
header('Location: http://a.com?id='.$yourstring[1]);
exit();
break;
case: 'B':
header('Location: http://b.com?id='.$yourstring[1]);
exit();
break;
default:
//etc
}

How to parse a youtube url to obtain the video or playlist ids?

I'm looking for a way to extract both (partials) youtube urls and single ids from a user input string.
This article How do I find all YouTube video ids in a string using a regex? got me going quite well but still i'm struggling a bit.
Is there a way to find both playlist and/or video ids from a strings from:
E4uySuFiCis
PLBE0103048563C552
Through:
?v=4OfUVmfNk4E&list=PLBE0103048563C552&index=5
http://www.youtube.com/watch?v=4OfUVmfNk4E&list=PLBE0103048563C552&index=5
use:
$urlInfo = parse_url($url); // to get url components (scheme:host:query)
$urlVars = array();
parse_str($queryString, $urlVars); // to get the query vars
check out the youtube api for more details on the format
I wrote a script to do this once where the YouTube URL is posted via "POST" under the key "l" (lowercase "L").
Unfortunately I never got round to incorporating it into my project so it's not been extensively tested to see how it does. If it fails it calls invalidURL with the URL as a parameter, if it succeeds it calls validURL with the ID from the URL.
This script may not be exactly what you're after because it ONLY retrieves the ID of the video currently playing - but you should be able to modify it easily.
if (isset($_POST['l'])) {
$ytIDLen = 11;
$link = $_POST['l'];
if (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $link)) {
$urlParts = parse_url($link);
//$scheme
//$host
//$path
//$query["v"]
if (isset($urlParts["scheme"])) {
if ( ($urlParts["scheme"] == "http" ) || ($urlParts["scheme"] == "https") ) {
//$scheme = "http";
} else invalidURL($link);
} //else $scheme = "http";
if (isset($urlParts["host"])) {
if ( ($urlParts["host"] == "www.youtube.com") || ($urlParts["host"] == "www.youtube.co.uk") || ($urlParts["host"] == "youtube.com") || ($urlParts["host"] == "youtube.co.uk")) {
//$host = "www.youtube.com";
if (isset($urlParts["path"])) {
if ($urlParts["path"] == "/watch") {
//$path = "/watch";
if (isset($urlParts["query"])) {
$query = array();
parse_str($urlParts["query"],$query);
if (isset($query["v"])) {
$query["v"] = preg_replace("/[^a-zA-Z0-9\s]/", "", $query["v"]);
if (strlen($query["v"]) == $ytIDLen) {
validUrl($query["v"]);
} else invalidURL($link);
} else invalidURL($link);
} else invalidURL($link);
} else invalidURL($link);
} else invalidURL($link);
} else invalidURL($link);
} else invalidURL($link);
} else invalidURL($link);
}

Categories