<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'>$file</a>
The above code is a link which passes its name to the variable 'file' which then gets displayed in the URL as:
http://example.com?file=thefile.html (whatever the file is)
Using PHP, I can now retrieve the variable from the URL and then process it (in this case the variable is 'thefile.html'.
How would I use Sessions to prevent variables from getting passed onto the URL. So instead of:
http://example.com?file=thefile.html
I would have:
http://example.com
And the variable 'thefile.html' would be stored in a Session.
If you need more info on what I am trying to ask, then please ask.
You've got to create a valid page for receiving the query string you're passing in the url
suppose the link you have is on index.html and your link destination is result.php, then you'd write the following code in result.php
<?php
session_start();
if( isset($_GET["filename"]) ){
$fname = $_GET["filename"];
//code to deal with filename
//save in session variable
$_SESSION['UploadedFilename'] = $fname;
}
?>
<!-- html -->
<?php
session_write_close();
?>
If you wanted to pass the file name from the browser (where the link is) to the host without a parameter, you would need to use a cookie. Sessions are a host concept.
So, as a simple example, you could use:
<a class='okok' id='$file' href='" . $_SERVER['PHP_SELF'] . "' onclick="document.cookie='filename=" . $file . "';">$file</a>
This creates a cookie with the filename in it.
On the host side, you retrieve the name with $_COOKIES['filename'].
Related
My website allows users to input and upload 2 things:
Their name - which they type into a textfield in an HTML form
And a photo - which they upload from their computer also using this same form.
Upon hitting "submit" my Javascript code calls a PHP script sitting on my server, that PHP script takes that data and writes it into a JSON file, puts that file in the right folder, also puts the image where it needs to go - and it all works perfectly thus far.
However, it just dawned on me that anyone reading my Javascript code can find the URL of my PHP script - which means they can then copy-paste that URL directly into the browser - and wreak all sorts of havoc.
Obviously I need to go about all this in a different way.
Should I just not use PHP for this? If so, what other languages or platforms are available for me to do what I just described - in a way that's impossible to hack?
Or is there a way to obfuscate the URL of my PHP script so that no one can copy-paste it into the browser address bar?
Any advice would be greatly appreciated!
================================
UPDATE:
Here’s my PHP script:
<?php
$tokenID = $_POST["tokenIDNum"];
$fileName = "TokenMetadata/token". $tokenID .".json";
$userName = $_POST["userName"];
$imageURL = $_POST["userImageURL"];
// Log out for verification:
echo "Here's what I got so far:<br/>";
echo "tokenID: " .$tokenID ."<br/>";
echo "userName: " .$userName ."<br/>";
echo "imageURL: " .$imageURL ."<br/>";
// CREATE AND SAVE THE NEW METADATA-FILE:
$newMetadataFile = fopen($fileName, "wb");
if( $newMetadataFile == false ) {
// Do debugging or logging here:
echo "OPPS! We got an 'fopen' problem!";
}
else {
$contentString = "{\r\n";
$contentString = $contentString. ' "name" : “Fun Token # ' . $tokenID . '",';
$contentString = $contentString. "\r\n";
$contentString = $contentString. ' "description" : "Another token from our FUN Collection.",';
$contentString = $contentString. "\r\n";
$contentString = $contentString. ' "image" : "' .$imageURL;
$contentString = $contentString. "\r\n}";
fwrite($newMetadataFile, $contentString);
fclose($newMetadataFile);
}
// or die("Unable to open file!");
// $myfile = fopen("token.json", "w") or die("Unable to open file!");
?>
When I copy-paste the URL for this script into my browser - which is what I worry some bad actor might do - it creates a new EMPTY JSON file - and that's without me passing any arguments into that URL. So I'm pretty sure right now someone could not only create new phoney JSON files in this manner, but also rewrite existing ones with false data if they were to pass values for my arguments.
What I need to know is if it's even possible to prevent bad actors from doing this - or if I have to go about this in some totally different way?
My understanding is that if I add SESSION and perhaps CAPTCH I might be ok? (Obviously, I'm no PHP expert.)
Would love any thoughts/suggestions regarding that - before I spend hours going down that rabbit hole.
I would like to run one of JS scripts while redirecting to another webpage .. Script to change a variable in Index.php like below code:
if ($flag == 1) {
// echo "<h1> Welcome to Website Home Page </h1>";
if(header("Location: ../../index2.php")) {
echo "<script type='text/javascript'> document.getElementById(body).style.color = 'red'; </script>";
};
} else {
// echo "<h1>Try Again!!!</h1>";
echo "<div class='alert alert-danger' role='alert'>
Your are not a Registered User <i class='fas fa-exclamation-triangle'></i> <br> Please Use below registrarion form.</div>";
}
N.B:
Still Junior learning PHP.
An HTTP redirect tells the browser that it should get the data it asked for from a different URL.
The body of a redirect response should be a message telling the user that they need to request a different URL. It is used in clients which either don't have HTTP redirect support or which have it disabled. Today such clients are practically non-existent.
If you want to run JS on the page being redirected to then you need to embed that JS in that page.
The header function not is for check URL, this function for send HTTP header.
For check url path using REQUEST_URI in superglobal variable $_SERVER.
REQUEST_URI - the URI which was given in order to access this page; for instance, '/index.html'.
More: https://www.php.net/manual/en/reserved.variables.php
Run the following code for research:
echo '<pre>';
var_dump($_SERVER)
About your JS code:
You forgot to enclose the body in quotation marks
I think it will help you.
Add a slash before all single quote ' -- > \'
But above code dose not look ok...
You should add an event Listener, onclick, on something(when you check the URL) and then include your js in a function.
Suppose I have an external JavaScript file named myJavascript.js which has 3 functions like the following:
function myFunc1(){
//some code
}
function myFunc2(){
//some code
}
function myFunc3(){
//some code
}
Now, I want to add some PHP script in myJavascript.js like the following, and it's from a separate PHP file named myView.ctp:
<?php
$url = Router::url($this->here, true);
$url = explode('/', $url);
$baseURL = $url[0] . '//' . $url[2] . '/' . $url[3] . '/' . $url[5];
$baseURL2 = $url[0] . '//' . $url[2]. '/' . $url[3];
?>
Why I need to add this PHP script inside myJavascript.js is this - I want to use the PHP variables $baseURL and $baseURL2 inside the 3 functions I've created.
How can I achieve this?
Edit:
I'm sorry I actually made a mistake in my question. The php view file is actually named as myView.ctp, as it's a CakePHP view file. The extension is .ctp and not .php. I've updated my question accordingly.
It's possible if you work into an internal HTML file and the extension is php.
Into your myView.php You can declare a global variable, and assign a response server value, into that file.
For example:
myView.php
<script>
var globalVar = <?php echo "your_value" ;?>
</script>
<script src="external_file.js"></script>
external_file.js
console.log(globalVar) // your_value
You cannot use php variables inside a separate javascript file. Instead what you can do is either to include the script inside the php template like
<script type="text/javascript">
....
</script>
or either to parse the url via javascript if this fits for you. You can get the current url with:
window.loacation.href
then you can parse the string as you wish.
I would definitely not do that but instead passing the args to methods or properties.
We usually have one script that takes care of initialization, lazy loading other stuff and so on. This is done in the layout.
<header>
<script src="/js/app.js">
<script>
app.init(<?php echo json_encode($this->request); ?>);
<script>
</header>
Just make sure you pass only what yo need of the request, it might contain security related data, so be careful by passing the whole thing.
In your specific views:
<script>
app.nameSpaceForView.someMethod('<?php echo $someStringVar; ?>');
</script>
You can even avoid this by implementing some logic in the above app.init() function that will check if app.controllers.ControllerName.ViewName is set based on the passed request info and if it's present execute it.
You won't need much, in the best case any, JS in your views by this.
I'm trying to set the JavaScript value to a PHP Session variable and get this session value to another php page.
here my code.
on the same it will show the value using alert.
here's my first page index_1.php
<Script>
function(no_user){
`var num_user = no_user;
'<?php $_SESSION["num_user"] = "' + no_user+ '"; ?>';
//alert('<?php echo $_SESSION["num_user"] ?>');*/
window.open("demo.php");
}
</script>
another page index_2.php
<?php
if(isset($_SESSION['num_user'])){
$a = $_SESSION['num_user'];
echo "Number of user: ". $a;
?>
You can not set php variable in js try to set it another location(demo.php)
<script>
function(no_user){
var num_user = no_user;
window.open("demo.php?no_user="+no_user);
//or window.location = 'index2.php?no_user'+no_user;
}
</script>
and set session on demo.php/index2.php
session_start();
if(!empty($_GET['no_user'])) {
$_SESSION['num_user']= $_GET['no_user'];
}
Just make sure to set session_start() in all PHP.Files before accessing $_SESSION-Variables and you're fine. PHP will automagically take care of re-using that session in other .php-files (same server, same domain etc.).
Evening all.
This is the first post I've made on here, so I hope I get this right.
I've looked everywhere (both on this site, and elsewhere), for a solution to an issue I'm having, but I can't find anything which sounds like my issue, yet I know logically it should be doable!
I maintain two intranet sites - one English and one Welsh. They are mirrors of each other, only the domain and site name change:
Example
http://english-site/news/item/003/170314.htm
http://welsh-site/newyddion/item/003/170314.htm
So far, I've only found this: http://www.codingforums.com/javascript-programming/8523-how-do-i-switch-pages-automatically.html
Which gave me some hope, but I can't work out how to apply it to my situation.
So, the question is this - is there a way to edit and reload the hyperlink switching out this:
english-site/news/
For this:
welsh-site/newyddion/
But keeping the rest of the link the same so the page will load with the Welsh or English equivalent of its self.
I know most modern CMS's could do this kind of thing automatically...but I'm not using a modern CMS...I'm using FrontPage...I'm certain this is possible but cant find anywhere that agrees with me!
Cheers in advance for any help anyone can offer!
FrontPage is ancient and you really shouldn't use it.
That being said, this bit of JS should do what you want:
window.location.href = "http://welsh-site/newyddion" + window.location.pathname.substring(window.location.pathname.indexOf('/', 1));
The current page's path (everything that follows the domain name) is accessible using window.location.pathname. Using indexOf('/', 1) on this gives us the position in the string (starting at 0) of the first / character (we pass 1 as the second parameter so as to ignore the starting slash). We then use substring to get everything from that character on.
Finally, we set the new URL to window.location.href, which performs a redirect.
You could possibly do this using regex, but this works just as well.
I am assuming your page has a button/link/select event which triggers which domain you want to serve from saying English or Welsh. Given this condition, you can do a simple javascript replace shown below :
if (selection === "blah blah"){
domain = "http://domainA...";
} else {
domain = "http://domainB...";
}
window.location.replace(domain);
reference
I wouldn't recommend having urls generated with javascript, but rather links on each of the page to the corresponding translated page using rel="alternative" and hreflang="code" with the language code corresponding to the 2 letter language code standard as depicted in http://googlewebmastercentral.blogspot.mx/2010/09/unifying-content-under-multilingual.html
to instruct the bots the pages are the same content in different languages.
If you could use a bit of php or server side code you could create your link reference very easily by replacing the urls with the new urls you are trying to create out of the current url. This is done by using patterns that perfectly match your criteria of url rewriting, that said, if you dont have any pattern, the best would be to set each link url separate per page.
Lets say you only need to convert english-site domain to welsh-site and news path segment to. According to http://reference.sitepoint.com/html/lang-codes, Welsh lang 2 letter standard would be 'cy'.
<?php
$lang['cy']['domain'] = 'welsh-site';
$lang['cy']['lang'] = 'Welsh';
$lang['cy']['news_slug'] = 'newyddion';
$lang['en']['domain'] = 'english-site';
$lang['en']['lang'] = 'English';
$lang['en']['news_slug'] = 'news';
$lang['default'] = 'en';
Explanation:
We are defining an array of languages where we will setup anything we need to translate. This is a multidimensional array map that defines each language by key in the first dimension, then each segment to translate in the second dimension. In this second dimansion we will setup special keys ending in _slug which will be part of the url to translate. This array can be saved in a special file apart for anything else and where we can go and edit easily without having us to modify the core code.
After defineyour initial language settings, now you need the code to identify the current language and path:
<?php
include('lang.php'); //this is the file where the language array is defined
$path = $_SERVER['REQUEST_URI'];
$host = isset($_SERVER['HTTP_HOST']) ? substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':')) : $_SERVER['SERVER_NAME'];
foreach ($lang as $code => $l) {
if ($l['domain'] == $host) {
$current_lang = $code;
break;
}
}
if ( ! isset($current_lang)) {
$current_lang = $lang['default'];
}
$_ = $lang[$current_lang];
$segment_1 = reset(explode('/', trim($path, '/'));
foreach ($lang[$current_lang] as $section => $url_segment) {
if ($segment_1 == $url_segment && substr($section, -5) == '_slug')
$current_section = $section;
break;
}
}
Explanation:
This code works as a bridge code that obtains the current section and language. First we obtain the host (domain name) and url path. In the first loop we match against any language domain to find the correct language we are on, then in the second loop we try to find the current section we are on with respect to the current language.
Now a little code to write the links using known information :
<head>
<?php foreach ($lang as $code => $l): ?><?php if ($code != $current_lang) : ?>
<?php $lang_path = isset($current_section) ? str_replace('/' . $_[$current_section] . '/', '/' . $l[$current_section] . '/', $path) : $path; ?>
<?php $lang_url = '//' . $l['domain'] . $lang_path; ?>
<link rel="alternative" hreflang="<?php echo $code; ?>" href="<?php echo $lang_url; ?>">
<?php endif; ?><?php endforeach; ?>
</head>
Explanation:
We are adding links that will tell bots the other links in your page are just different representations of this page in a different language. We also specify the lang code inside hreflang attribute (http://googlewebmastercentral.blogspot.mx/2010/09/unifying-content-under-multilingual.html)
Then you create your links (in the body section somewhere) the exact same way:
<ul>
<?php foreach ($lang as $code => $l): ?>
<?php if ($code != $current_lang) : ?>
<?php $lang_path = isset($current_section) ? str_replace('/' . $_[$current_section] . '/', '/' . $l[$current_section] . '/', $path) : $path; ?>
<?php $lang_url = '//' . $l['domain'] . $lang_path; ?>
<li><?php echo $l['lang']; ?></li>
<?php else : ?>
<li class="active"><?php echo $l['lang']; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
For all this to work your server must support PHP extension. I used php code because this is the most common code support to find.
You also need to change your file extensions, from .html to .php for this to work.
Hope it works for you. This might not be what you wanted, but rather what you actually need.