PHP change href on specific pages - javascript

I am new to PHP. I am trying to replace the hash tags in the headers of all the pages that aren't part of the index page. I am using this code
$content = file_get_contents('includes/header.php');
if ( strpos( $_SERVER['SCRIPT_NAME'], 'index.php' ) === false ){
preg_replace( 'href="#', 'href="index\.php#', $content );
}
However I am getting "Warning: preg_replace(): Delimiter must not be alphanumeric or backslash in " and I don't know how to escape the characters more than using backslash.
Should I just run some javascript instead?
Thanks

preg_replace expects parameter 1 to be a pattern and is missing the delimiters. So you need to do something like:
preg_replace('/href="#/', 'href="index\.php#', $content);
http://www.php.net/preg_replace

The 'hash' of the url cannot be accessed by the server, only by the client.
The only way to manipulate this part of the URL is by using a client side scripting language, e.g. JavaScript.

Related

javascript new regexp dynamic

I am creating a dynamic regex but I have a problem with how to escape character so can one put some light on this?
I am using PHP with some backend configuration and admin can add regexp from backend to validate invalidate character and I am getting this value on the PHP so what I did
var regex = RegExp(<?php echo $regex ?>);
but I am getting the error like SyntaxError: Invalid regular expression: I know I need to escape the dynamic character but not sure how.
EDIT
I am trying this value from backend
<>{}[\]!##$+=%^*()/;
New EDIT
As per the #anubhava suggested I am escaping the special character by preg_quote() but on Regex.test it always fails I mean it always getting the false even though It should return true.
Here is my code,
var invalidCharRe = new RegExp(SOME_MY_VARIABLE);
var result = invalidCharRe.test(value)
Where SOME_MY_VARIABLE is a dynamic special character(which I am getting from PHP by preg_quote() and value is my textbox value
Since you're using php to echo your regex you can leverage php's preg_quote function to escape all special regex meta-characters beforehand like this:
var regex = /<?php echo preg_quote($regex, '/'); ?>/
Note that there is no need to call new RegExp here since Javascript will be always be getting a static string for regex.

javascript function with parameters doesnt work with IE

Im calling the function getStateCityZip from inside a php function from line
$result = '<select name="'.$name.'" id="'.$name.'_new_id"'.$css_class.' '.$att.' onChange="getStateCityZip(this.value,`'.$userType.'`);"> ';
and the javascript function is
function getStateCityZip(customer_id,userType){
var userType= String(userType);
alert(customer_id + userType);
$.post( "start_quote.php", { "action":"get_state_city_zip",
"customer_id" : customer_id})
.done(function( data ) {
var obj = jQuery.parseJSON ( data );
if (userType=='shipper'){
$('#s_country').val(obj.billAddress.bill_country);
$('#s_state').val(obj.billAddress.bill_state);
$('#s_city').val(obj.billAddress.bill_city);
$('#s_zip').val(obj.billAddress.bill_zip);
}
}
This works fine on chrome but on IE it doesnt even give alert. If I were to remove the parameters from function definition and from the point where I call the function and hardcode the values inside the function defintion then it works just fine. In all the other cases I have tried it doesnt work for IE. All help will be appreciated
IE doesn't support template literals. You've used template literals around your $userType (the backticks).
In general, it's a bad idea to stuff strings into onClick attributes like this. But if you want to, you need to:
Ensure that all characters with special meaning in JavaScript string literals are escaped, and
Ensure that characters with special meaning in HTML are encoded (because the text in an onClick attribute — as with all attributes — is HTML text).
To do that:
'...onChange="getStateCityZip(this.value, '.htmlspecialchars(json_encode($userType)).'...'
json_encode handles ensuring that a valid JavaScript string is output, and htmlspecialchars ensures that any HTML special characters (like &) are property encoded (as & in the case of &). The characters your JavaScript function sees will be faithfully replicated, because the HTML parser consumes the encoded entities and emits the original character, and the JavaScript parser handles the escaped characters.
Escape ' instead of using backticks:
$result = '<select
name="'.$name.'"
id="'.$name.'_new_id"'.$css_class.' '.$att.'
onChange="getStateCityZip(this.value, \''.$userType.'\');"> ';
// ^ here and here ^

# in URL skipping all parameter after that

When submitting form using get method if we pass # character in any field it skips all parameter after that field.
e.g.
bookmy_car.php?pod=6&room_id=32&starthour=14&startminute=00&startday=07&startmonth=08&startyear=2015&endhour=16&endminute=00&endday=07&endmonth=08&endyear=2015&end_date=1438927200&email_conf=1&cost_code=&desc=Trip description&trip_comment=#&day_rate=68.00&hourly_rate=6.60&hourly_km_rate=0.35&dur_hours=2
hours&location_charge=0.00&damage_cover_charge=5.00&total_free_kms=&longterm=0&rt=&minbooking=3600&returl=&returl_newid=&rep_id=&edit_type=&insPlanid=3&plan_name=goOccasional&id=3&driver_username_id=2&
How do we protect it? I tried escape() and encodeURI() function of JavaScript, it does not help.
I agree with #dgsq . But i prefer using only encodeURI so that he can get the uri as it is in the next page.
alert( encodeURI('&trip_comment=#&day_rate=68.00') )
It happens because with hashbang in query string # it is interpreted as location.hash and hot processed as GET parameters. You need to properly encode URI before you use it. For example with encodeURIComponent:
alert( encodeURIComponent('trip_comment=#') )

Escaping special characters in javascript in a link

Not sure if I'm asking the right question. But this is what I want:
I have this code:
$content = rawurlencode(file_get_contents("c://Server/www/Codice/LOGS/".$user."/".$file));
$thelist .= "<li class=files><a href=javascript:alert('".$content."') class=filelink>".$file."</a></li>";
echo $thelist;
What I want is to alert (actually this is just a test, I want to use the $content as argument in a function) the $content when I click the link. How should I do this?
I'm guessing it would work fine if the file is a simple txt file. But the file I'm using here is a C++ program, which contains characters <>, obviously
First you need to get the file contents. This is pretty straight forward, except that you need to make sure that $user and $file don't contain any unexpected characters, such as "../" that would take you outside of the designated directory. Example using preg_match():
if (!preg_match ('/^[\w\d]+$/', $user) ||
!preg_match ('/^[\w\d]+$/', $file)) {
/* Error */
return;
}
$content = file_get_contents("c://Server/www/Codice/LOGS/".$user."/".$file);
Next, you need to turn the contents into a valid javascript string. To do this, you need to escape the backslash, double or single quote and line terminator characters (including U+2028 and U+2029). I believe the easiest way to do this is using json_encode():
$code = json_encode ($content);
The code (after the javascript: part) is technically a URL so it has to be escaped with rawurlencode():
$href = 'javascript: ' . rawurlencode ("alert ($code)");
The href (and also the file name) then needs to be suitably escaped with htmlspecialchars() to be used as an HTML attribute. I think this can actually be skipped for $href because the string is HTML-safe after rawurlencode()
$href_h = htmlspecialchars ($href);
$file_h = htmlspecialchars ($file);
Now we are finally ready to output the result. I like using HEREDOC when mixing variables with HTML:
echo <<<_
<li class=files><a href="$href_h" class=filelink>$file_h</a></li>
_;

Unexpected token ILLEGAL

var url = "C:\xampp\htdocs\wcf2\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
results in Uncaught SyntaxError: Unexpected token ILLEGAL. Is there any way to fix it in javascript or do I need to escape it before in PHP?
Edit: My script looks like this:
<script>
window.onload = function() {
thingiurlbase = "{#$__wcf->getPath('td')}js";
thingiview = new Thingiview("viewer");
thingiview.setObjectColor('#C0D8F0');
thingiview.initScene();
var url = "C:\\xampp\htdocs\\wcf2\\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
thingiview.loadSTL(url);
thingiview.setRotation(false);
}
</script>
You need to escape the backslash characters.
var url = "C:\\xampp\\htdocs\\wcf2\\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
Otherwise, JavaScript tries to interpret \x, \h, and \w as escaped special characters.
In this particular case, though, it looks like you could just replace the \ with / instead:
var url = "C:/xampp/htdocs/wcf2/wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
You need to escape backslashes.
var url = "C:\\xampp\\htdocs\\wcf2\\wcf/attachments/5d/18-5dffacdfe6d2cf1db8dfabbb5b53ae8dc65bd325";
If the string is printed from PHP, you can use addslashes to do the work for you.
$test = 'C:\xampp\htdocs\wcf2\wcf/attachments/5d/18-...';
echo $test . "\n";
echo addslashes($test);
>> C:\xampp\htdocs\wcf2\wcf/attachments/5d/18-...
>> C:\\xampp\\htdocs\\wcf2\\wcf/attachments/5d/18-...
Side Note
By the way, two things are incorrect with your approach:
The slashes in your string should all point the same way. If you want it to be used as a URL, use forward slashes e.g. http://stackoverflow.com/posts/17775495
If you want to give the browser a URL that it can use to access some resource on your server, this URL cannot be a file path (such as C:\xampp\htdocs\....) Instead, it has to be either relative to your site root, or an absolute URL (such as http://dropbox.com/my/file.pdf). Don't forget that a web user can only access files on your server through the web server.

Categories