determine the URL in the browser address bar (NOT the real address) - javascript

I have two urls - biothoughtblog.co and playfight.co. The first is forwarding to the second and masking is used. I am using this
<?php
function curPageURL() {
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
?>
<?php
echo curPageURL();
?>
on the page http://www.biothoughtblog.co/test.php - however, it echoes the real URL which is http://www.playfight.co/test.php. I need it to echo the URL that is in the address bar. I know very very little Javascript - is it what I need to be using here?
Thanks a lot.
P.S Oh, and the purpose is to run the same website under two different domains and different branding (logo, etc).

That's because http://www.biothoughtblog.co/test.php is framing http://www.playfight.co/test.php.
<frame src="http://www.playfight.co/test.php" frameborder="0" />
PHP has no way of knowing that it is loaded inside a frameset, and how to get the URL of the parent frame.
You want to avoid using the "masking" feature of your registrar or DNS provider. Point the biothoughtblog.co domain to the same hosting server, ensure that your hosting account is setup for both domains. Then biothoughtblog.co wil be hitting your website directly, and PHP will know what it is.

You don't need to do anything in PHP to run the same website under two different domains.
If you are using apache, open your conf file, locate your virtual host config and add a serverAlias.
Example:
<VirtualHost *:80>
DocumentRoot "/var/www/html"
ServerName biothoughtblog.co
ServerAlias playfight.co
<Directory "/var/www/html">
AllowOverride All
</Directory>
</VirtualHost>

Related

js.map files being unnecessarily tracked by php logging script - huh?

I have a weird problem with my .js.map files being unintentionally logged.
In php files I include a header.php file for, well, my header. In my header I include logUserData.php - in which I get the user ip, account info, and log stuff in the database. Basic intention is to track where our users go (not in Analytics, just for our data uses).
Everything works fine, all traffic is logged - but, the .js.map files are tracked. You probably know these aren't listed anywhere in my source. I don't include my logging script in these files, which would be weird anyway.
I have zero purpose to track these files. I don't ever really care if they're called... I can filter them out with the script but that avoids the problem and doesn't fix it.
I have tried moving the include from the header to the footer basically as a shot in the dark. Totally at a loss. I have put the call before and after these scripts, before the html and after.
These are the scripts that have their associated maps called:
<script src="/js/toastr.min.js"></script>
<script src="/js/popper.min.js"></script>
<script src="/js/socket.io.js"></script>
And here are the only relevant parts of the logging script in case it helps, the rest is just user account and db stuff:
$browser = $_SERVER['HTTP_USER_AGENT'];
$ip = $_SERVER['REMOTE_ADDR'];
$CurUrl = $_SERVER['REQUEST_URI'];
$refer = $_SERVER['HTTP_REFERER'];
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if (isset($_SERVER['HTTP_F ORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if (isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if (isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
Does anyone have any clue why this might be? I'm totally at a loss.
EDIT: the map files are NOT in my network activity in dev tools and served as application/javascript

Echo file contents to javascript from PHP using fopen(), file_exists() not working

I know there are many different posts concerning this, but none of the posts seemed to help.
I have tried inputting
include_path=".:/path/to/dir"
along with
safe_mode_exec_dir=".:/path/to/dir"
into php.ini. I have tried turning safe_mode on, turning allow_url_fopen to On and then putting ftp:// in front of the path, and without the ftp://. I have tried using multiple different ways of opening it including...
$folder = $_GET['dir'];
$path = $folder;
$file = fopen($path, 'r');
$lines = array();
while(!feof($file)){
$lines[] = fgets($file);
}
fclose($file);
and
$lines = explode("\n", file_get_contents('doc.txt'));
I have tried setting permissions to 777 under /var/www/html and permissions on the other directory which is under /home/pi/
Nothing seems to be working.
So. I am completely out of ideas. Please help before my head banging becomes dangerous.
Here is my code for what I am trying to do...
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$folder = $_GET['dir'];
$path = $folder."/myfile.txt";
$file = fopen($path, 'r');
$lines = array();
while(!feof($file)){
$lines[] = fgets($file);
}
fclose($file);
for($x = 0; $x < sizeof($lines); $x++){
echo $lines[$x];
}
echo '</response>';
?>
xmlHttp = createXmlHttpObject();
xmlHttp.open("GET", "getClientData.php?folder="+dir, false);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && (xmlHttp.status == 200 || xmlHttp.status == 206)) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.textContent;
}
};
xmlHttp.send();
I am running this on a Raspberry Pi 3 Model B, Rasbian Jessie, if that has anything to do with it. And Apache2.
It's interesting to note that when I change the php file a little bit to have an if/else statement like "if(file_exists($path)){}else{echo "null"}", if I call alert() in javascript from the input, I DO get "null". That's why my first assumption was a file permission thing or php.ini setting.
So I have solved it. And I will give a detailed description as to how I solved it.
First of all, do make sure that allow_url_fopen to be On and to have safe_mode off. Look through both the Apache2 php.ini and the regular php.ini as there is two of them and I believe both have to be set in order for it to work. If you installed php with apache2 on your platform, both php.ini files should be under "/etc/php5". There will be a folder called "apache2" and "cli". Each one has a file.
Secondly, Chrome Web Development Tools are amazing. Press F12 with Chrome open and go to the "Networks" tab. There will be a checkbox that says "Disable Cache" at the top of the tab. This makes sure that Chrome won't cache the results of your changes to your website. KEEP THIS WINDOW OPEN BECAUSE IF YOU CLOSE IT, IT WON'T DISABLE THE CACHE ANYMORE!!! You can also download a Chrome extention like "cache killer" which will disable cached results just the same. Also, with CWDT, the Console Tab is a debugging miracle. I have been programming the site on Aptana, which is not very good at all at noticing small semi colon or bracket errors. Utilize this tool! It will save your life as it did mine!!
Please ask questions or comments if I didn't explain something in detail.

.htaccess File Extension Remover Code Breaks Website Form

So I had this code in my HTACCESS which was great because it first removes the .php file extension from my pages if the visitor enters the page with the .php file extension, and then it allows the page to load without the extension. (So it's just prettying up the URL)
# REMOVE FILE EXTENSIONS
RewriteEngine On
# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]
# check to see if the request is for a PHP file
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^/?(.*)$ /$1.php [L]
It works great, but then I run into problems on the page: http://www.CyberBytesInc.com/contact because I have a form which calls out to a .php file to send:
<form id="request-form" action="resources/script/question-send.php" method="post">
And the above htaccess code removes the .php for this file and I get the error code "Direct access to this page is not allowed." which is inside of the script, it's the
} else {
die('Direct access to this page is not allowed.');
}
Once I remove this from htaccess though then it starts working:
# browser requests PHP
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]
But then I don't get the perk of it removing the file extension if .php is placed at the end of the page (which much of Google is indexed with the file extension and I'm trying to remove this.
I guess if I could somehow make it so the htaccess code work except for when accessing a file from my /resources/scripts/ folder, I don't know the best way to fix this.
You can go to the site right now to see that it's not working because of this. For the time being I am probably going to remove the above mentioned line of code so my form is atleast working. So if you view the site and the form is working, it's because I removed the above .htaccess until I figure out how to successfully have it in there.
Thanks!
EDIT: Full code for question-send.php
<?php
// Get email address
$email_address = 'email#site.com';
// Ensures no one loads page and does simple spam check
if( isset($_POST['name']) && empty($_POST['spam-check']) ) {
// Declare our $errors variable we will be using later to store any errors
$error = '';
// Setup our basic variables
$input_name = strip_tags($_POST['name']); //required
$input_email = strip_tags($_POST['email']); //required
$input_subject = strip_tags($_POST['subject']);
$input_message = strip_tags($_POST['message']); //required
// We'll check and see if any of the required fields are empty
if( strlen($input_name) < 2 ) $error['name'] = '<label for="question-name">Please enter your <b>Name</b></label>';
if( strlen($input_message) < 5 ) $error['message'] = '<label for="question-message">Please leave a longer <b>Message</b></label>';
// Make sure the email is valid
if( !filter_var($input_email, FILTER_VALIDATE_EMAIL) ) $error['email'] = '<label for="question-email">Please enter a valid <b>Email Address</b></label>';
// Set a subject & check if custom subject exist
if( $input_subject ) $subject = "(Question) - $input_subject";
else $subject = "(Question) - No Subject";
// $message .= "$input_message\n";
$message .= "\n\n---\nThis email was sent by $input_name from $input_email";
// Now check to see if there are any errors
if( !$error ) {
// No errors, send mail using conditional to ensure it was sent
if( mail($email_address, $subject, $message, "From: $input_email") ) {
echo '<p class="success"><b>EMAIL SENT SUCCESSFULLY.</b><br />' . "Dear $input_name, " . 'thank you for contacting CyberBytes Inc. Please allow us <b>24-48</b> hours to review your request and get back to you. If you need a response sooner, please contact us via telephone at (716) 876-1824.<br /><br /><b>Please verify that this is your correct Email Address:</b><br />' . "Email Address: <i>$input_email</i>" . '<br /><br /><span class="red"><b>PLEASE NOTE:</b></span><br /> If we do not respond to your request within a reasonable amount of time, please give us a call as there may have been an error on our end with your request.</p>';
} else {
echo '<p class="error">There was a problem sending your email! Please give us a call at (716) 876-1824 as there seems to be an error on our end with the form.</p>';
}
} else {
// Errors were found, output all errors to the user
$response = (isset($error['name'])) ? $error['name'] . "\n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "\n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "\n" : null;
echo "<p class='error'>$response</p>";
}
} else {
die('Direct access to this page is not allowed.');
}
Change your rule to skip POST request:
# browser requests PHP
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^\s/([^\ ]+)\.php
RewriteRule ^/?(.*)\.php$ /$1 [L,R=301]

Auto-login into the IP Camera

I have a IP Camera and I would like to show liveview at my webpage.
IP Camera don't allow for anonymous log in so I need to put username and password while connecting.
I have javascript:
<img src="http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi?" width="640" height="480" name="refresh">
<script language="JavaScript" type="text/javascript">
image = "http://camera_ip_address/cgi-bin/jpg/image.cgi?"
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime()
document.images["refresh"].src = image+tmp
setTimeout("Start()", 100)
}
Start();
</SCRIPT>
And it works ok in firefox but:
http://user:password#camera_ip_number
don't work in other browsers (it popup a form to enter username and password).
But in PHP you can use user:password I've check it by using:
<?php
header('Content-type: image/jpeg');
print( file_get_contents( 'http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi?' ));
?>
of course it shows only one frame but you don't have to enter username and password.
How can I log in into IP Camera using PHP ? If I could log in one time while enetering webpage, my javascript will work ok because browser will remember username and password until I close the browser.
I don't know how to send username and password to log in.
Sorry for my English.
Ok, so I've made it work using PHP and JavaScript. Maybe it will be helpful for someone else:
Save the PHP file as, for example, snapshot.php:
<?php
$img="http://user:password#camera_ip/cgi-bin/jpg/image.cgi?";
header ('content-type: image/jpeg');
readfile($img);
?>
In the HTML file, add this script:
<img src="http://domain.com/snapshot.php" width="640" height="380" name="refresh">
<script language="JavaScript" type="text/javascript">
image = "http://domain.com/snapshot.php"
function Start() {
tmp = new Date();
tmp = "?"+tmp.getTime()
document.images["refresh"].src = image+tmp
setTimeout("Start()", 300)
}
Start();
</script>
It works ok under every browser. If I set timeout to less then 300, there is some lag. I don't know why that would be caused by; maybe internet connection or website speed.
You may be able to use Apache mod_rewrite instead - Less overhead from the PHP stack, and probably generally faster. See this page for more information.
Choose one of these.
Apache .htaccess - Your page requests http://yoursite/livecam/image.jpg, which is run through Apache's proxy to your camera.
RewriteEngine on
RewriteBase /livecam/
RewriteRule ^image.jpg$ http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi [P]
ProxyPassReverse /livecam/image.jpg http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi
In PHP, create a file called image.php - Your page requests http://yoursite/image.php, which streams the image to whatever requests it.
<?php
$file = 'http://user:password#camera_ip_address/cgi-bin/jpg/image.cgi';
if (file_exists($file)) {
header('Content-Type: image/jpeg');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
Both will proxy the image through your server. It's generally bad practice to give the username and password on any public page, even if an attacker can't damage anything of concern.
See readfile() on PHP.net
Your code would look like (replace image.php with livecam/image.jpg if using the Apache version). I also shortened your code a bit.
<img src="http://yourserver/image.php" width="640" height="480" name="refresh">
<script language="JavaScript" type="text/javascript">setTimeout(function() {document.images["refresh"].src = "http://yourserver/image.php?"+math.random();}, 100);</SCRIPT>
IP:port/cgi-bin/jpg/image.cgi?&user=XXX&pwd=XXX
IP:port/cgi-bin/jpg/image.cgi?&usr=XXX&pwd=XXX
IP:port/snapshot.cgi?&user=XXX&pwd=XXX';
IP:port/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr=XXX&pwd=XXX';

Workflow with (non-) minified js/css files for development and production

I'm looking for a way to structure my workflow so I don't get confused/into trouble when working with "uncompressed" js/css files for development and minified ones for production.
I don't want to have two html versions (one with development and one with minified js/css files) of the same source. Or do I have to?
Also whats the best way to automate the actual minify process?
NOTE: I'm looking for a local solution. Server side is not an option.
I've been using this in PHP – you might use it for inspiration:
<?
$test_server = $_SERVER['SERVER_NAME'] == "127.0.0.1" || $_SERVER['SERVER_NAME'] == "localhost" || substr($_SERVER['SERVER_NAME'],0,3) == "192";
function caching_headers ($timestamp) {
global $test_server;
if (!$test_server) {
$gmt_mtime = gmdate('r', $timestamp);
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
if ($_SERVER['HTTP_IF_MODIFIED_SINCE'] == $gmt_mtime) {
header('HTTP/1.1 304 Not Modified');
exit();
}
}
header('Last-Modified: '.$gmt_mtime);
}
}
header ("Content-Type: application/javascript; charset=utf-8");
include ($_SERVER['DOCUMENT_ROOT']."/media/js/jsmin.php");
$libs = explode("|",$_GET['libs']);
$uniq_string = "";
foreach ($libs as $lib) {
$uniq_string .= filemtime($_SERVER['DOCUMENT_ROOT']."/media/js/$lib.js");
}
$hash = md5($uniq_string);
$cachefile = $_SERVER['DOCUMENT_ROOT']."/cache/".$hash.".js";
if(file_exists($cachefile)) {
$last_mod = filemtime($cachefile);
caching_headers ($last_mod);
include($cachefile);
echo "//Cached on ".gmdate('r', $last_mod)." to ".$hash;
exit;
} else {
$combined = "";
foreach ($libs as $lib) {
if (substr($lib, strlen($lib)-3, 3) == "min") {
$combined .= file_get_contents($_SERVER['DOCUMENT_ROOT']."/media/js/$lib.js")."\n";
} else {
$combined .= JSMin::minify(file_get_contents($_SERVER['DOCUMENT_ROOT']."/media/js/$lib.js"))."\n";
}
}
$fp = fopen($cachefile, 'w');
fwrite($fp, $combined);
fclose($fp);
$last_mod = filemtime($cachefile);
caching_headers ($last_mod);
include($cachefile);
echo "//Cached on ".gmdate('r', $last_mod)." to ".$hash;
}
?>
alongside JSMin-php.
I then use:
<script src="/media/js/combined.php?libs=jquery-1.5.1.min|behaviour|jquery.form"></script>
in my pages.
It stores the cached minified file at /cache/, so make sure that folder exists if you are trying this.
Currently the best solution is the HTML5 boilerplate build script.
Beware that there is a learning curve before being able to use the complete power.
Also it's worth mentioning, that the build script optimized for websites, where every page uses the same JavaScript and CSS files. So if you have certain pages, that have additional CSS and JavaScript files that you want to have optimized/minified you might need to do this separately.
The script also compresses HTML and (optionally) leaves PHP stuff untouched.
HTML5 boilerplate build script is awesome. It's open source, please contribute!
Note: Most of my infos are 3+ month old. Let me know about new developments.
You could dynamically inject the appropriate js include depending on the URL. In essence, you check to see if it's the production URL, and if it is include the minified version. Then use an else branch to handle non-production URLs and inject the development version (this way someone can't see your staging URL).

Categories