Change all domains in links on a website - php

need some advice on how to fix an ugly situation. our forum has resided on a couple of different domains over the years. we lost one domain that was in use 5-6 yrs ago and apparently some posts on our forum still have links in the threads that point to the old domain. what would be the most efficient way to change all links that point to
http://www.olddomain.com/stuff
point to
http://www.newdomain.com/stuff
the only part that has changed is the domain name, all thread variables in the url remain the same. is this something that is best done client side with javascript/jquery or should it be handled on a server level with a PHP function (dont know where to begin here..)? some pseudocode that doesn't seem to do what I need it to on the client side...
$('a').each(function() {
var domanin = 'newdomain';
if(href.search('olddomain.com') != -1) {
$(this).attr('href', newdomain);
}
});
thank you

I think it will make more sense if you handle this in the back end. Search engines will not notice the change you make through JavaScript.
So I advise you search for those domains in your database and replace them there.

Well you should probably do this on the server side, as it was said before, but if you can't for whatever reason, here is what you could do on the javascript side of things.
$('a').each(function() {
this.host = 'www.newdomain.com';
});
Note that this example uses jQuery, but you could do the same in plain javascript with getElementsByTagName.

To do this in JavaScript (w/ jQuery):
$('a').each(function() {
var link = this.href;
if(link.search('olddomain.com') != -1) {
this.href = link.replace('olddomain.com', 'newdomain.com');
}
});
Here is a jsfiddle: http://jsfiddle.net/tHXxK/
However I would suggest changing the links in the database, just get rid of all the old references. To do this create a script that searches for the old URLs and replaces them, something like:
$query = mysql_query("SELECT [id], [link] FROM [table] WHERE [link] LIKE '%//olddomain.com/%' OR [link] LIKE '%//www.olddomain.com/%'", $db) or trigger_erroR(mysql_error());
while ($row = mysql_query($query)) {
$iQuery = mysql_query("UPDATE [table] SET [link]='" . mysql_real_escape_string(str_replace(array('//olddomain.com/', '//www.olddomain.com/'), array('//newdomain.com/', '//www.newdomain.com/'), $row['link']) . "' WHERE [id]=" . $row['id']), $db) or trigger_error(mysql_error());
}

If it'd be me, I would have used a server side script to replace all instances of the old domain with the new one and be done with it once and for all.
I assume your forum DB is rather a large one. For the sake of system resources you can write a multi-step script and do the job in multiple steps.
This is a better approach as it can improve the data consistency for search engines as well.

Related

codeigniter attribute/filter system

I've searched a lot for answers to this question, but I can't find them. Maybe because I'm not searching for the right keywords (because I don't know the right name) or there might be few resources on this subject.
I'd like to build a 'sorting system' in codeigniter for database results. Much like the magento layered navigation or the sorting that's on this site: http://www.wintersporters.nl/skigebieden. On there you can filter ski resorts by price, country, amount of slopes etcetera and the results are automatically updated via AJAX.
another example -> http://www.beslist.nl/products/cddvdrom/cddvdrom_5035278/ where you can sort by date, publisher, genre etcetera.
I'd like the system to be able to pass multiple variables like on wintersporters.nl where you can select multiple countries instead of only one and this way you're able to narrow down your search more and more by selecting multiple attributes until you've found the ski resort that fits you best. So every time you select an option it's preserved in the URL.
How do I achieve something like this? Via the $_GET[] array, with uri's or something totally different? Can anyone point me to a tutorial, snippet of code, explanation or anything related as I can't find out the right way to do this.
I'd be really grateful!
I was also thinking about the component or control which will give me the same functioalities for my web portal but then I developed by own by HTML and Ajax.
In Ajax, you can use
var checkboxValueArray = [];
var val = [];
$('input[name="subcatcheckbox"]:checked').each(function(i){
val[i] = $(this).val();
checkboxValueArray.push($('#subcat'+val[i]).text());
});
checkboxValueString = checkboxValueArray.toString();
checkboxValueString = checkboxValueString.replace(/\ /g, "-");
checkboxValueString = checkboxValueString.replace(/\_/g, "-");
checkboxValueString = checkboxValueString.replace(/\,/g, ":");
var checkboxValueNumberString = val.toString();
var checkboxValueNumberString = checkboxValueNumberString.replace(/\,/g, ":");
var pathName ='';
if(checkboxValueNumberString != ''){
pathName = "events_categories="+checkboxValueString+"&catid="+checkboxValueNumberString;
}
if(pathName != ''){
window.location.hash = "#!" + pathName;
}
if(pathName == ''){
window.location.hash = '';
}
getEventsParsedJSON(val);
By this way, I am creating an array on onClick event and then passing to the string to the URL through window.location.hash(ajax method). I developed this in a day. It's easy to develop.

pass a value from one page to another outside querystring and without javascript?

One solution to automatically building navigation for a site is by scanning a folder for documents like this:
foreach(glob('pages/*.pg.php') as $_SITE_NAV_filePath):
$_SITE_NAV_filePath = explode('.pg',pathinfo($_SITE_NAV_filePath,PATHINFO_FILENAME));
$_SITE_NAV_fileName = $_SITE_NAV_filePath[0];
$_SITE_NAV_qv = preg_replace('/([A-Z])/','-$1',$_SITE_NAV_fileName); $_SITE_NAV_qv = trim($_SITE_NAV_qv,'-');
$_SITE_NAV_name = preg_replace('/([A-Z])/',' $1',$_SITE_NAV_fileName);
?>
<li><?=$_SITE_NAV_name?></li>
<?php
endforeach;
This code will turn "AnAwesomePage.pg.php" into a menu item like this :
<li>An Awesome Page</li>
This might be bad practice (?).
Anyway; I don't use this method very often since most of the time the sites have a database, and with that comes better solutions...
But my question is this:
Is there a way to prefix the filename with a integer followed by and underscore (3_AnAwesomePage.pg.php), for sorting order purposes, and pass it somehow to the destination page outside of the querystring and without any async javascript?
I could just explode the filename once again on "_" to get the sort order and store it somewhere, somehow?
This is the code for handeling the page query request:
$_SITE_PAGE['qv'] = $_GET['page'];
if (empty($_SITE_PAGE['qv'])){ $_SITE_PAGE['qv'] = explode('-','Home'); }
else { $_SITE_PAGE['qv'] = explode('-',$_GET['page']); }
$_SITE_PAGE['file'] = 'pages/'.implode($_SITE_PAGE['qv']).'.pg.php';
This code turns "An-Awesome-Page" back into "AnAwesomePage.pg.php" so it's possible to include it with php.
But with a prefix, it's not so easy.
The probliem is; Now there's no way to know what prefix number there was before since it has been stripped away from the query string. So I need to send it somehow along in the "background".
One very bad solution I came up with was to transform the navigation link into a form button and just _POST the prefix interger along with the form. At fist it sounded like a nice solution, but then I realized that once a user refreshes their page, it didn't look very good. And after all, that's not what forms are for either...
Any good solutions out there?
Or some other and better way for dealing with this?
There are two ways to keep that number saved, you can use cookies or php session variables.
But in this case, if user first enter the url in the browser or in a new browser, then he should be taken to default number.
Like you have:
1_first-page.php
2_first-page.php
3_first-page.php
If user enter the url like: domain.com/?page=first-page, you have to take him to 1_first-page.php to any number which you want to be default.

Enter a code to go to a specific page

I want to use an idea that I have seen on another website where I enter a "keyword", press Enter, and it then takes the client to a specific page or website.
I have seen something like this on http://qldgov.remserv.com.au, On the right side there is a field called "My Employer", type in "health" for example and you will be provided with relevant content.
Essentially I have client branded mini sites where we want to assign a "keyword" for each client brand so all of their employees will be able to go to their site entering this one keyword without all of them having individual logins. I want to be able to link to a URL that I can define in some manner.
I have looked at the source code of the site mentioned above and see they are using a form but I am not sure how they have assigned the keywords or if its even possible to do this without a database or anything like that. Trying to keep it as simple as possible as I am not a PHP/Java expert by any means.
Any help would be appreciated, even if its not code but an idea of the direction I need to go in to make this work. Thanks in advance!! :-)
The easiest way in my eyes would be to define an array that contains all of the keywords and respective urls client side (in JS). For example:
​var array = { 'health' : '/health.php', 'sport' : '/swimming.php' };
You would then get the user input on onSubmit and if it exists modify the window.location appropriately.
if ( array[user_input] !== undefined ) {
window.location = array[user_input];
}
else {
alert ( 'not found' );
}
If the user supplied health they will be redirected to /health.php, if they supply sport they will be redirected to /swimming.php (JSFiddle). Alternatively you can use server-side (PHP, JAVA) to handle the request but this may not be worth the effort.
Goodluck.
By using php (rather than javascript), you're not relying on javascript + making it seo friendly.
Firstly you're going to need either some sort of database or a list of keywords/urls
$keywords = array('keyword1' => 'path/to/load.php', 'another keyword' => 'another/path');
Then you'll need a basic form
<form action="loadkeyword.php">
<input name="query">
<button type="submit">Go</button>
</form>
Then in loadkeyword.php
$keywords = array('keyword1' => 'path/to/load.php', 'another keyword' => 'another/path');
$query = $_GET['query'];
if (isset($keywords[$query])) {
$url = $keywords[$query];
header("HTTP/1.0 301 Moved Permanently");
header('location: '.$url);
exit;
} else {
header("HTTP/1.1 404 Not Found");
die('unable to locate keyword');
}
If you have a large list of keywords, I would suggest using a database instead of an array to keep track of your keywords.
The site you link to is doing it server-side, either via a keyword-list that matches content or a search function (I suspect the latter).
There are a few different ways you could achieve your goal, all of them to do with matching keywords to content and then redirecting, either with an array, a list, or a database - the principle will be the same.
However, I would respectfully suggest this may not be the best solution anyway. My reasoning is that (based upon the example you give) you're effectively making your users guess which keyword matches which minisite (even if you have many keywords for each site). Why not just have some kind of menu to choose from (i.e. a selector with a list of minisites)?

Request to Apache server in chat app

I'm writing a chat application for joomla (apache server) and use this construction to emulate long-polling (server side):
function get_messages($last_id) {
$time = time();
while((time() - $time) < 25) {
$sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
$db->setQuery($sql);
$rows = $db->loadAssocList();
if (count($rows)>0) {
echo 'JSON STRING HERE';
} else {
flush();
}
usleep(5000000);
}
}
How Can I optimize this part of code.
Should I use infinite looping or should I avoid while construction?
P/S: I know Apache is not best choice to write chat app for and node.js is better.
Thanks!
Infinite loops are never a good idea because they hammer your server resources. You are better off having JS providing the intermittent polling to your get_messages function. Use a timeout and embed the script on any page that shows the messages.
I'm going to answer based on the limited information I've got to help you in the broadest way possible following industry standards. You need to not code in the way you currently are because it is very inefficient and quite frankly dangerous.
Here is the mootools code required to run an intervaled polling (I've used Mootools as you said you're using Joomla, I've assumed you're using 1.6+ as 1.5 is EOL this month):
//this sets how often you want to update (in milliseconds).
setInterval('chatPoll()',2000);
//this function essentially just grabs the raw data
//from the specified url and dumps it into the specified div
function chatPoll()
{
var unixTimestamp Math.round(new Date().getTime() / 1000)
var req = new Request({
method: 'get',
url: $('ajax-alert').get('http://www.yoururltoupdate.com/file.php?last=' + (unixTimestamp-2),
data: { 'do' : '1' },
onComplete: function(response) { response.inject($('my-chat-wrapper')); }
}).send();
}
Your PHP file should look something look like this:
get_messages($_GET['last']);
function get_messages($last_id) {
$sql = 'SELECT * FROM #__messages WHERE `id` >'.intval($last_id);
$db->setQuery($sql);
$rows = $db->loadAssocList();
if (count($rows)>0) {
echo json_encode($rows);
}
}
I haven't fully tested this code but it should work and if not will definitely help answer your query as to how what you're trying to do should be achieved rather than the way you originally posted. If you really wanted to get fancy you could check out node.js as well. There is also tons of extensions for Joomla which work as chat mediums for support purposes if that's what you were after.

Authentication for Small Website, example?

I need a login to let 10 students to view educational material. Simple is good.
Perhaps it just redirects to a page if student logs in correctly. Can you send me a link or example, or best tutorial?
I was told JavaScript alone doesn't work, so the next simplest thing is preferred.
If there's an example where I don't have to rename all of my pages 'php', that would be better.
Thanks,
I used this when I was learning to do secure logon using PHP.
http://www.devshed.com/c/a/PHP/Creating-a-Secure-PHP-Login-Script/1/
Found it quite helpful.
Simple...
Create a file called functions and insert the following:
session_start();
$_GLOBALS['users'] = array(
//'username' => 'password'
'robert' => 'my_pass'
);
function isAuthed()
{
if(empty($_SESSION['logged_in']))
{
if(!empty($_REQUEST['username']) || !empty($_REQUEST['password']))
{
if(isset($_GLOBALS['users']) && is_array($_GLOBALS['users']))
{
if(isset($_GLOBALS['users'][$_REQUEST['username']]) && $_GLOBALS['users'][$_REQUEST['username']] === $_REQUEST['password'])
{
$_SESSION['logged_in'] = true;
return true;
}
}
}
}else
{
return true;
}
return false;
}
and then in your secured pages just do:
if(!isAuthed())
{
die("You're not authorized to see this page");
}
and on your login page just create a form that sends the username, password to the an area of your site that your authorizing
Note: This is not copy and past'able code, this is for example purposes only.
You could possibly "do" it with JavaScript if you did some kind of AJAX function which called a php page, and then returned your value. This could work, and it's how a lot of sites do their logins actually. So, your client wouldn't have to rename their site, and you could just set up an array of logins on the php page.
This would NOT be secure at all, but it would work just fine.
I guess you would do something like this (I'm going to use jQuery because it's easier to do Ajax with it. It's really easy to use, and if you're going to learn Javascript, it's probably better nowadays to know the basics and then use a framework library like jQuery)
$(document).ready(function(){
$("#NAME-OF-SUBMIT-BUTTON").submit(function(){
var username = $(this).find("#username");
var password = $(this).find("#password");
$("NAME-OF-DIV-FOR-RETURN").load('login.php', {['parameters']:,[username,password]},function(responseText){
if(responseText == 'SUCCESSFUL-RESPONSE-TEXT'){
$("#NAME-OF-FORM").html("Login Successful");
}
});
});
});
and of course you're going to want to set a session variable or cookie or something on your php page to indicate the user has logged in. Again, this is not very secure, but it's what I would do if it were like a homework assignment or just SUPER temporary. Of course, I would suggest making hard-coded usernames and passwords in an array on your original page in PHP with a postback to itself if you were going to go that temporary. Using Javascript and Ajax for this just seems like a bit much.
But, you requested it!
It depends on exactly what you're trying to do. If you want a pure-JS login system, you could do something fairly simple like XOR'ing a redirect page with a password, storing that in the page and then XOR'ing it again when they type in a password.
If you want an actual login-system, you need a back-end running some server (perhaps Node.js if you're trying to learn JavaScript), some type of database (e.g. MySQL), users stored in that database.
The front-end javascript might be responsible for validating the login via ajax. Using jQuery, something like:
function validateLogin(user, pass, successCallback, errorCallback){
$.get('/login', {user: user, pass:pass}, function(data){
if(data.status == 'success'){
successCallback();
}else{
errorCallback();
}
}
}

Categories