I am filtering a page with $_SERVER['HTTP_REFERER'].
Let "pageb.php" filter whether a user have come from "pagea.php" (although it is not reliable) by $_SERVER['HTTP_REFERER'].
It works well until "pagea.php" has a preceding query string like "pagea.php?q=10". Then if a user goes from "pagea.php?q=10" to "pageb.php" it is not detected by "pageb.php":
if($_SERVER['HTTP_REFERER']='http://pagea.php'){
echo 'This user has come from page a';
}else{
echo 'This user has come from another page';
}
How can I detect a user came from "pagea.php" even with preceding query string q=10?
Use strpos() to check if a string contains another string:
<?php
if (strpos($_SERVER['HTTP_REFERER'], 'pagea.php') !== false) {
echo 'from page a';
}
use comparision operator not assignment
if($_SERVER['HTTP_REFERER']='http://pagea.php'){
= will be ==
Related
I am building an admin panel that can be used on different sites. I need to show some specific HTML if the url contains a specific domain, and something else if not.
So, if the URL is something like this http:// (something) .mydomain.com/admin.... I would like to show some HTML.
If the URL is something like this http:// anotherdomain.com/admin... I would like to show something else.
Í have tried with this, but somehow didn't get that to work. What am I doing wrong?
Edit: Wrong code. See code below...
<?php
if (substr($_SERVER['REQUEST_URI'], 0, 5) !== '/mydomain.com') {
echo '<div id="stuff"></div>';
}
?>
Sorry: Posted the wrong php code. A bit too tired I think...
This is the one I messed with:
<?php
if (substr($_SERVER['SERVER_NAME']) !== 'mydomain.com') {
echo '<div id="stuff">test</div>';
}
?>
Please try below code
<?php
$url_segments = parse_url("http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
if (strpos($url_segments['host'],'mydomain.com') !== false) {
echo 'true';
}else{
echo 'false';
}
?>
Thanks,
Try with that code:
if (preg_match ( string $pattern , string $subject)){}
http://php.net/manual/de/function.preg-match.php
http://php.net/substr
Your current substr is saying "If the first 5 characters of the request URI aren't /mydomain.com, print the stuff below."
You could try to do this correctly in a few ways. You could use strpos and checking to see if mydomain.com appears in the request URI, or a more complicated regex to find something like (mydomain.)
Change $_SERVER['REQUEST_URI'] for $_SERVER['SERVER_NAME'] if mydomain.com it's your domain name.
Also, the substr is returning 5 chars and you are comparing against 13 chars
I have an example.php form when posted to perl script example.pl which responds either this
<!-- comments disabled -->
or this
<!-- comments enabled -->
The above response is stored in php get request in $commentstatus variable
Response may be a multiline or single line !
How to build an expression or verify the response using php preg_match or a normal validation for if else condition in php?
You can check for the presence of a string, within a string with strpos().
So the actual code would be:
<?php
if (strpos($commentstatus, "<!-- comments disabled -->") !== false)
{
}
elseif(strpos($commentstatus, "<!-- comments disabled -->") !== false)
{
}
function commentsEnabled($str){
preg_match_all('/^.*?<!--\s*comments\s+(en|dis)abled\s*-->.*$/m', $str, $m);
return !count($m[1]) ? null : array_pop($m[1]) == 'en';
}
demo
enlarge image
Credits to #lbu for the SIMPLEST solution who commented under the Op
This works excellently and is the easiest
$content= trim($commentstatus);
if ($content == "<!--commentsdisabled-->"){
print "Dear User Comments are disabled for your access";
}else if($content == "<!--commentsenabled-->"){
print "Dear User Comment added to blog post entry";
}else{
print "You are Banned for Spamming";
}
#degenerate
"Learn how to read the PHP documentation," - rude and assumptious
But your code works, even for line breaks read in from a file.
if (preg_match('#enabled#', $commentstatus)){
// Enabled code
}else{
// Everything else code
}
I don't know how it works, because the documentation you linked says to use the 's' switch :
"The s tells the code NOT TO stop searching when it encounters \n (line break)"
This works is with preg_match_all & preg_match !!
It's a plus 1 even with the ending snark!
Not sure what #BetaCoder is on about, but it's obviously not a question.
Not sure if you are simply asking this?
if (preg_match('#enabled#', $commentstatus)){
// Enabled code
}else{
// Everything else code
}
Learn how to read the PHP documentation, please:
http://us1.php.net/preg_match
I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!
I'm trying to display a custom welcome message to visitors based off what social media site they are coming in from. I can't get this string to work but it is echoing back no matter what the refering site is. Can anyone help me get this to work? Many thanks!
<?php
if (strpos("twitter.com",$_SERVER[HTTP_REFERER])==0) {
echo "Welcome, Twitter User! If you enjoy this post, don't hesitate to retweet it to your followers";
}
?>
Tried using
<?php
if(isset($_SERVER['HTTP_REFERER'])) {
echo $_SERVER['HTTP_REFERER'];
}
?>
to get this to work but no luck.
strpos returns false when the search word does not appear in the string. 0 also evaluates to false when compared to a boolean. So false == 0, and your code always runs.
Use a strict comparison to require both value and type match instead of ==
if (strpos("twitter.com", $_SERVER['HTTP_REFERER']) === 0) {
echo "Welcome, Twitter User! If you enjoy this post, don't hesitate to retweet it to your followers";
}
However, the referrer will not start with twitter.com, it'll start with http:// or https:// so your condition wasn't right in the first place. To search for twitter.com anywhere else in the string:
if (strpos("twitter.com", $_SERVER['HTTP_REFERER']) !== false) {
echo "Welcome, Twitter User! If you enjoy this post, don't hesitate to retweet it to your followers";
}
I think you may have confused strpos() with strcmp(), being strcmp() returns 0 when two strings are equal. strpos() returns the position at which a string was found. Try:
<?php
if (strpos('twitter.com', $_SERVER['HTTP_REFERER'] != 0)) {
echo "Welcome, twitter user.";
}
?>
I want to create a URL redirect based on a URL variable.
so, if student%20gender (student gender) is male then go to www.one.com, if female, go to www.two.com.
couldn't figure this one out yet. any help?
Question could use a little bit of a better explanation. Do you mean that someone is going to
http://www.yoursite.com/yourscript.php?student%20gender=male and you want them to be redirected to http://www.one.com?
If this is the case, PHP has a built in variable known as $_GET which stores the values listed after a ? in a URL. So in the above example, we'd see:
$_GET['student gender'] = male;
You can use this to access any number of parameters separated by &
So the URL http://www.site.com/index.php?val1=a&val2=b&val3=c would give us:
$_GET['val1'] = a;
$_GET['val2'] = b;
$_GET['val3'] = c;
After this, to do a redirect in PHP the easiest way is to send a Location: header. This is done like so:
<?php
header("Location: www.newsite.com");
?>
Combining this with our $_GET variable and some simple logic:
<?php
if($_GET['student gender'] == 'male'){
header("Location: www.one.com");
die();
} else {
header("Location: www.two.com");
die();
}
?>
$var = $_GET['yourvar'];
if($var == 'one'){
header("Location: http://www.one.com/");
}else if ($var == 'two'){
header("Location: http://www.two.com/");
}
then do http://www.yoururl.com?yourvar=one
You also have to make sure you look at the security aspects here, the best way yo accomplish this is
$gender = isset($_REQUEST['gender']) ? $_REQUEST['gender'] : false;
switch($gender)
{
default: //The default action
//Send back to the gender select form
break;
case 'male':
//Send to male site!
break;
case 'female':
//Send to female site!
break;
}
This should be sufficient, but please never use $_X['?'] in functions that execute either shell or database queries without sanitation.
Note: _X being (GET,POST,REQUEST,FILES)