How to get the hostname without TLD from a url - javascript

I'm in the process of creating a website. Every time the user uploads a link, I need to save the link and its name/value. This is hard to explain.
Here's what I'm trying to say. Lets say the user pastes a link in an input. https://www.google.com/ The link needs to be saved in an XML file. When I call the link:
I want to also call the name:
Google
I want to extract "google" from "https://www.google.com/"
I know I could use:
str_replace(' ', '', )
But not all links are the same.
I know this code won't work because I already tried it.
I know the right code is simple probably 3 lines. So I would really appreciate it if you guys could help me out.
Thank you.

parse the url. get the host part and explode the string with a dot (.) as delimiter.
$url="https://google.com/";
$parts = parse_url($url);
$parts=explode('.',$parts['host']);
echo $parts[0]; // parts[1] contains com, parts[0] contains google
To work with urls that contain 'www' you might do something like this. Mind that this is not working with subdomains.
echo getName("http://www.google.com"); //prints google
function getName($url){
$parts = parse_url($url);
$parts=explode('.',$parts['host']);
$data=$parts[0]=="www"?$parts[1]:$parts[0];
return $data;
}
To work with every url, including subdomains I think it is more easy to use a regex. I adapted the function from this question to fulfil your needs.
function getName($url){
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return explode('.',$regs['domain'])[0];
}
return false;
}

Related

Real url not working for url build by javascript TYPO3

I configured the extension tt_address in my page. I need to filter the address by its year. So I build a select box. I need to append some query parameter with its url to access in controller for implementing the filter.
The functionality is done successfully. But realurl is not working for this particular functionality.
main.js
function initYearFilter() {
var selectedItem = sessionStorage.getItem('year');
if (selectedItem !== null) {
$('.year-filter select').val(selectedItem);
}
$('.year-filter select').on('change', function () {
var loc = location.href.match(/.*people\/alumni\/+/)[0],
url;
if ($(this).val() == 'reset') {
url = loc + '?no_cache=1';
} else {
url = loc + '?ts_address[year]=' + $(this).val() + '&no_cache=1';
}
sessionStorage.setItem("year", $(".year-filter select").first().val());
window.location.href = url;
});
}
My realurl config
'postVarSets' => array(
'_DEFAULT' => array(
'year' => array(
array(
'GETvar' => 'ts_address[year]',
),
),
),
)
Don't let urls being generated manually in frontend, like you do in Javascript.
My advice here would be to generate the urls backend side and attach it to a option attribute (data-reset-url, data-url).
// maybe a foreach here
$GLOBALS['TSFE']->cObj->typolink_URL([
'parameter' => '_PAGEUID_',
'additionalParams' => '?ts_address[year]=' . $year, // suppose in foreach have year var
'no_cache' => true
]);
If you think ext:realurl is the culprit deactivate ext:realurl and look if it works then.
I think it still will not work, but you will see something in the url that should give you the neccessary hint.
You probably stumble over a security feature of TYPO3: cHash.
With a cHash URL parameter TYPO3 secures it's URLs against injection of unrelated parameters for a cached version of a page. If TYPO3 builds an URL it hashes all parameters and appends this hash to the url. If such a cHash is found in an URL the parameters are fetched from database and all current URL parameters are ignored. especially any additional parameters. So the cached page matches the given url.
If you use ext:realurl, this cHash parameter is hidden in a 'normal' URL path. If you add parameters, like in your javascript, they are removed as they are not encoded in the cHash, which is encoded in the speaking URL.
In your case the additional parameter would change the content of the page. This page could be cached if the additional parameter is included in a cHash.
Here you must help realurl to either build an URL without cHash, or build URLs which contain these individual cHashes:
You could build a menu of available years and also configure a pathsegment for the year. In this way you can get individual cHashes for each year. You need to change your javascript to add a path-segment instead of a parameter.

Transliterate text from PHP to JavaScript

INTRODUCTION
I am working on personal project and using Symfony3.
In order to upload files i am using OneUpUploaderBundle.
And I am not accepting file name that consists of characters with accents, Cyrillic characters, etc.
In order to do so - I am using function from CODE section
TARGET
I would like to use PHP function in CODE section in JavaScript!
CODE
// transliterate text
public function transliterateText($input_text)
{
$input_russian = transliterator_transliterate('Russian-Latin/BGN', $input_text);
$input_german_french = transliterator_transliterate('Any-Latin; Latin-ASCII', $input_russian);
$input_baltic = iconv('UTF-8', 'ASCII//TRANSLIT', $input_german_french);
$transliterated_text = preg_replace('/[^a-zA-Z_0-9\(\)\n]/', '_', $input_baltic );
$transliterated_text = strtolower($transliterated_text);
return $transliterated_text;
}
EXAMPLE
input: "12345 Rūķīši Проверка äöüß àâæçéèêëïîôœùûüÿ.txt"
output: "12345_rukisi_proverka_aouss_aaaeceeeeiiooeuuuy.txt"
QUESTION
I did not found many information about this problem on the Internet.
May be it is not a good idea to use JavaScript for this task...
Or maybe I should create service in Symfony3, that is accessible through AJAX and returns transliterated text instead?
CONCLUSION
Please advise.
Thank You for your time and knowledge.
UPDATE
I would like to use this function in JavaScript in order to show user what the filename would look like when on the server. (File names are going to be transliterated on server anyway). At the moment I am sending (in the UploadListener) following information for each file [{'error':'none'}{'orig':'my file name.txt'}{'t13n':'my_file_name.txt'}]. I would like to send as little as possible informātion from server to browser. So if there was "translation" of the CODE I would need only to send error for each file...

passing data to a new html window

Sorry guys but this is a little broad, I've searched but there are a few things coming up but I wanted a direct answer for my question.
First I am a mechanic at a truck dealership in Dallas, TX. I am writing a web based application that will make it easier for me to organize all my jobs. I'm using this project to teach myself HTML, PHP, PDO, javascript ect. Right now I'm in design and organization phase meaning I'm getting everything I want figured out so when I start the hard coding I know ahead of time where to go.
Now when a tech logs in they will be brought to the tech landing page. I'm going to have a php script that will retrieve all the 20 most recent "active" Ro's (repair orders) assigned to that particular tech. A table will display summary info on a line at the end of each line there will be a button (or I might make the RO # clickable not sure yet.
My question is what is the best way to open a new window and pass the RO# of the clicked option so scripts on the new page can begin populating the detailed RO information from the database??
I'm not necessarily looking for the code but something I can search to narrow down my options.
Thanks
There are a few ways you could do this.
A simple link with querystring:
-------------------------------
<a href='/repairs.php?mechanic=bob' target='_blank'>Bob's Repair Orders</a>
<a href='/repairs.php?mechanic=curly' target='_blank'>Curly's Repair Orders</a>
A simple link with a javascript function:
-----------------------------------------
<a href='#' onclick='getRepairs('bob')'>Bob's Repair Orders</a>
<a href='#' onclick='getRepairs('curly')'>Bob's Repair Orders</a>
javascript:
function getRepairs(name){
window.open('/repairs.php?mechanic='+name );
}
You have 2 options to do this:
(Recommended) Pass RO# (id) in address page.php?id=1001 and fetch id using get method
on new page. It will be a full page with all bars and every thing
enabled.
Collect data in a DIV and open a new page and populate data to it.
Code for Option 1:
Page 1: ROlist.php (Which Contains list of 20 ROs)
RO#1001
Page 2: ROdetails.php (Which will open only id based details)
<?php
$ROid=$_GET['id'];
$result=mysql_query("SELECT * FROM table where id='$ROid'");
if($result)
{
while($list=mysql_fetch_array($result))
{
echo $list['Id'];
echo $list['clientName'];
echo $list['foo'];
echo $list['bar'];
}}
?>
You can call the following in JavaScript:
window.open("<yourUrl to open>?ro=someValue")
and pass the ro value to the new window as a query paramter (?ro=someValue where someValue will be replaced by the value to pass over and is the url of the page to load in the new window).
In the new window you can retrieve it using:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var ro = getParameterByName('ro')
Note: getParameterByName is from How can I get query string values in JavaScript?
Use a GET parameter : index.php?ro_id=1
Now this URL should be generated through PHP, where 1 is a variable and is the RO#.
Other solutions told how to open it in a new window, you don't need JS to read $_GET though.
Like what Uchiha comment is suggesting, you can put your RO# into a link.
In your html you can put something like this:
<a target="_blank" href="ro_table.php?ro_number=RO number here"> RO# </a>
and in your ro_table.php or any php file you prefer to receive the RO# you can get the RO# by: $_GET["ro_number"] and use that to your database query.

How to validate Stock Market data

Honestly, I am not an expert & right now very much confused about how to even state my problem...so please forgive my lack of knowledge and this long confusing question.
I was assigned a project today where the clients are displaying stock market's info on their page (image attached below). And when you click on any one of the buttons (for example, NASDAQ) more info is displayed in a pop-up box.
They are using onClick() to send the whole string to this third party to collect the data. Here is the HTML code for NASDAQ link:
<li>
<a href="#" onClick="open('https://app.quotemedia.com/quotetools/clientForward?symbol=^NASD&targetURL=http://app.quotemedia.com/quotetools/popups/quote.jsp?webmasterId=99944&locale=en_US','miniwin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=550,height=270,top=20,left=0'); return false;">
NASDAQ
<span id="imageNASDAQ"></span>
<span id="valueNASDAQ" class="share_value"></span>
<span id="textNASDAQ"></span>
</a>
<script type="text/javascript" src="/getStockInfo.php?Stocks[NASD]=NASDAQ"></script>
</li>
And then in getStockInfo.php file they are collecting the data as a JSON string and then parsing it. Here's how they are collecting the data:
<?php
if (array_key_exists("Stocks", $_GET)) {
foreach($_GET['Stocks'] as $symbol=>$stock) {
print file_get_contents("https://app.quotemedia.com/quotetools/jsVarsQuotes.go?webmasterId=99944&symbol=$symbol");
?>
So far pretty simple. But now the client wants to do some
"user input validation"
"Only accept 4 symbols: SP500, SPX, DOW & NASDAQ"
This is where I am getting confused. From their code (HTML part) looks like everything is hard coded (open('...symbol=^NASD...'); or open('...symbol=^SPX...'); or open('...symbol=^DJI...');) and each button/link is sending specific Stock symbol's info to the getStockInfo.php file (src="/getStockInfo.php?Stocks[NASD]=NASDAQ" or src="...Stocks[SPX]=SP500" or src="...Stocks[DJI]=DOW") where the stock quotes are being fetched. There is absolutely NO way my client's users can provide any other stock symbols through the site to change the display, the only way to manipulate the symbols are by changing the code itself.
BUT, my client wants to implement these above 2 conditions in the code anyhow. And I am not sure how to do this.
Not sure if I was able to explain my problem properly :( But I really need some help. Also I'm sorry for not being able to provide any link to the actual page here. Thank you so much for reading my confusing post and investing your time!! :)
Here's a proof of concept:
if (array_key_exists("Stocks", $_GET)) {
$stocks = array_filter($_GET['Stocks'], 'filterStocks');
foreach ($stocks as $symbol => $stock) {
print file_get_contents(…);
}
}
function filterStocks($symbol) {
return in_array(
$symbol,
array('SP500', 'SPX', 'DOW', 'NASDAQ')
)
}
Now getStockInfo.php will only return data for the four symbols. If you need that configurable on an individual user basis, a simple solution would be to do change the filterStocks function and callback to
function filterStocksForLoggedInUser($symbol) {
return in_array($symbol, getAllowedSymbolsForUser());
}
function getAllowedSymbolsForUser()
{
$permissions = include '/path/to/permissions/file.php';
return isset($permissions[$_SESSION['username']])
? $permissions[$_SESSION['username']]
: array();
}
}
and then in the permissions file put
return array(
'Walahh' => array('SP500', 'SPX', 'DOW', 'NASDAQ'),
'JohnDoe' => array('SP500', 'GOOG')
);
Note 1: the above assumes you have some sort of way to identify users, here $_SESSION['username']. Change that with whatever you are using and adjust the permission file accordingly.
Note 2: the permissions file will be read each time from disk. Disk I/O is usually slow, so you might want to consider moving the permissions to someplace faster.
Note 3: this is just a proof of concept. It's very pragmatic. You can certainly improve the design and structure, but I guess it's good enough to illustrate how to approach the problem.

Adding new words to the game

In my spelling game new words will be added all the time so there is always a fresh selection of words to spell.
Each word added to the game has a "src" to an image and a sound that will prompts the user into getting the spelling correct in gameplay.
When I have completed making the game, the job of adding the new words in is down to one of my colleagues. This means he will have to add a link for the pic and audio as well as the word.
As they have little knowledge with this sort of thing I want to make it as easy as possible for him to add the images and sounds when adding the words I want to create a default path to a shared location where he will store all this stuff.
This way he can just type in "bug" for the word, ".bug-pic" for the picture and ".bug-audio" for the sound making it simple for him to add into the HTML.
Is this the best way to do it?
What would be the simplest way for them to input these things?
Here is how I store the word, sound and image at the moment...
<ul style="display:none;" id="wordlist">
<li data-word="mum" data-audio="file:///C:/smilburn/AudioClips/mum.wav" data-pic="http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
<li data-word="cat" data-audio="file:///C:/smilburn/AudioClips/cat.wav" data-pic="http://www.clker.com/cliparts/c/9/9/5/119543969236915703Gerald_G_Cartoon_Cat_Face.svg.med.png"></li>
<li data-word="dog" data-audio="file:///C:/smilburn/AudioClips/dog.wav" data-pic="http://www.clker.com/cliparts/e/9/4/1/1195440435939167766Gerald_G_Dog_Face_Cartoon_-_World_Label_1.svg.med.png"></li>
<li data-word="bug" data-audio="file:///C:/smilburn/AudioClips/bug.wav" data-pic="http://www.clker.com/cliparts/4/b/4/2/1216180545881311858laurent_scarabe.svg.med.png"></li>
<li data-word="rat" data-audio="file:///C:/smilburn/AudioClips/rat.wav" data-pic="http://www.clker.com/cliparts/C/j/X/e/k/D/mouse-md.png"></li>
<li data-word="dad" data-audio="file:///C:/smilburn/AudioClips/dad.wav" data-pic="http://www.clker.com/cliparts/H/I/n/C/p/Z/bald-man-face-with-a-mustache-md.png"></li>
</ul>
THANKS
I'm going to break your mold a bit here, and suggest something that looks simple enough for me in the long run (at least, simpler than what you have here).
The problems with using HTML markup to store your words is that:
it's HTML --- the browser will have to parse this, but then not display it because you've got the <ul> element as display:none (it's just sort of wasted effort), and
XML (or HTML, whichever) is pretty bloated, in the sense that there's a lot of text needed to represent information. If you're going for a spelling game, I'm assuming that you'll have hundreds, or thousands of such words, and the HTML representation for your words will be a huge crapload of bandwidth bloat.
So! Here's what I'd suggest:
// create an external JS file to store your words,
// let's say, [words.js].
// then let's just store your words in an array
var words = [
{ word : "foo" , audio : "file:///C:/smilburn/AudioClips/foo.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" },
{ word : "bar" , audio : "file:///C:/smilburn/AudioClips/bar.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" },
{ word : "mum" , audio : "file:///C:/smilburn/AudioClips/mum.wav", pic : "http://www.clker.com/cliparts/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png" }
];
It's just a plain Javascript array that holds a collection of Javascript objects. Each object has three properties: word, audio and pic.
Load that file into your page, and have a script read from that. It'll be much easier and faster to traverse, use and apply to your page. Reading to and fro a JS object is generally faster than having to parse and read the same information from the DOM.
Additionally, the markup is more compact, and you're not [misusing] HTML DOM for something it (arguably) wasn't supposed to be doing.
Thirdly, it's much more organized and cleaner to look at than HTML markup, and I imagine that that will be much easier for your colleagues to update and adapt to.
Lastly, one nice thing about this approach is how easy it is to write your code into modules, so you can work with stuff like expansions / word packs easier:
// something like this can work:
// [words.js]
var words = [
// some base words
{ word : "foo", audio : "foo.wmv", pic : "foo.pic" }
// ...
];
// [words.animals.js]
(function () {
// do not do anything if the base [words.js] isn't loaded
if (!words) { return; }
// extend the base words
words = words.concat([
// new animal words!
{ word : "dog", audio : "bark.wmv", pic : "brian.jpg" }
// ...
]);
})();
The idea being, you can load the words.js file into your game and it'll work perfectly. However, if the user would also like to add new words (say, words for animals) then they (you) can just load auxiliary files to augment your base words list.
This is much easier to do with JS objects than with HTML markup.
EDIT
If you really positively final-answer must have to use HTML, I recommend chopping off the data-word attribute off your <li> and just use it's text value instead.
<li data-audio="dog.wmv" data-pic="dog.jpg">dog</li>
I would recommend, that you simply store the info like this:
<li data-word="mum" data-audio="mum.wav" data-pic="/5/e/7/f/1195445022768793934Gerald_G_Lady_Face_Cartoon_1.svg.med.png"></li>
After reading your jsFiddle i would recommend you crate a playAudio function like this:
function playAudioFile (audioFileName) {
audioFileName = "http://www.wav-sounds.com/cartoon/" + audioFile;
$("#mysoundclip").attr('src', audioFileName);
}
after that you can replace this:
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
by something like this:
playAudioFile(listOfWords[rndWord].audio);
You have to use attr() to store images in default location. Here they explain the default location to store images.
You might want to consider what server side technology you'll have available too.
If you have to add the options through html, then what you can probably do in that portion of the page, is have the html elements generated dynamically by the server.
'ASP Classic example
<%
set fs = server.createObject("scripting.filesystem")
set folder = fs.getFolder("your path here")
for each file in folder.getFiles("*.wav")
strWord = left(file.name, length(file.name)-4)
%><li data-word="cat"
data-audio="path/to/folder/<%=strWord%>.wav"
data-pic="path/to/folder/<%=strWord%>.png"></li>
<%
next
%>
This is just an asp classic example, I'm sure you'll find others out there specific to the platform your using.
But basically... you have to have SOMETHING on the server tell the output page what is available if you want to make it a drop-in-and-go operation. Otherwise you might as well be doing the html as you have been. Technology isn't always going to replace plain ol data entry.
Well, in my opinion, you can use a database, a server side script and a form for your colleague. Create a form which he will use to upload the information to the server and store the paths into the database.
The form:
<form method="POST" action="myscript.php" enctype="multipart/form-data">
<p>Word:<input type="text" name="my-word" id="my_word"></p>
<p>Audio:<input type="file" name="audio" id="my_audio" /></p>
<p>Picture:<input type="file" name="picture" id="my_picture" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The script:
<?php
$conn = mysql_connect("your_host", "your_user", "your_pass") or die (mysql_error());
mysql_select_db("your_database", $conn) or die (mysql_error());
if( ( $_FILES[ 'audio' ][ 'error' ] > 0 ) || ( $_FILES[ 'picture' ][ 'error' ] ) ){
echo "Error" . "<br />";
}
else{
move_uploaded_file($_FILES["audio"]["tmp_name"], "your/upload/directory/for/audio/" . $_FILES["audio"]["name"]);
move_uploaded_file($_FILES["picture"]["tmp_name"], "your/upload/directory/for/images/" . $_FILES["file"]["name"]);
mysql_query( 'INSERT INTO your_table ( word, audio, image ) values ( "' . $_POST[ 'word' ] . '", "' . $_FILES[ 'audio' ][ 'name' ] . '", "' . $_FILES[ 'picture' ][ 'name' ] . '" )', $conn );
}
?>
Of course your database should have a table which stores those 3 values plus some id.
I think you can add more entries to a list like this in javascript:
function addLI(id){
var Parent = document.getElementById(id);
var NewLI = document.createElement("LI");
NewLI.innerHTML = "this is a test";
Parent.appendChild(NewLI);
}
which I found from here: http://bytes.com/topic/javascript/answers/520885-add-new-list-item
I recommend having input fields with the name, location and picture for your friend to add more entries with, then use something like this js function to add a new child entry.
If you have access to a server with PHP, I would suggest putting all them items in a array and then looping through them.
I have written an example here:
<?php
$wordsArray = array(
array('word'=> 'randomword' , 'audio' => 'test.mp3', 'picture' =>'pic.jpg'),
array('word'=> 'randomword2' , 'audio' => 'test2.mp3', 'picture' =>'pic2.jpg')
);
$html = '';
foreach($wordsArray as $word){
$html .= '<li data-word="'.$word['word'].'" data-audio="'.$word['audio'].'" data-pic="'.$word['picture'].'"></li>';
}
?>
<html>
<head>
<title></title>
</head>
<body>
<ul>
<?php echo $html; ?>
</ul>
</body>
</html>

Categories

Resources