Monday, 15 November 2010

PHP Mail By Different SMTP Server

Senareo;

I've just had to upload a php website to an IIS 6 web server. Amazingly, everything worked apart from the ability to send email. I informed the hosing provider and they set up a different SMTP server to send email from. I now needed to tell my website where the different smtp server resided.

The Solution

I used the ini_set command in php. It allowed me to override the default php setup, and add it to a config file. I believe this can also be achieved by .htaccess, however having the setting in a config file in php suited me better.

<?

ini_set('SMTP','yourmailserver.com');

?>

Note: The ideal solutions would have been to have php.ini changed, but this solution works for now.

Friday, 2 April 2010

php exchange rate

Making multi currency websites can be a complete nightmare. Exchange rates change at a moments notice and it can be a constant struggle to keep yourself from losing money if one of the many markets crash.

Therefore I did a little bit of research and found you can get a rough idea of exchange rates by using yahoo finance. Yahoo provide a csv download from their site with live data. It's probably not as reliable as a feed from xe.com, but it's free and gives you a good indication of the exchange rate.

Here's a funscion i've made fo get this data;


function fget_exchange_rate($into, $infrom='GBP'){
$lcsv = file_get_contents('http://download.finance.yahoo.com/d/quotes.csv?s='.$infrom.$into.'=X&f=sl1d1t1ba&e=.csv');
$la = split(',',str_replace('"','',$lcsv));
if($la[1] != '') return $la[1];
return false;
}

echo('US $'.fget_exchange_rate('USD').'
');
echo('AU $'.fget_exchange_rate('AUD').'
');
echo('Euro '.fget_exchange_rate('EUR').'
');
echo('Japan '.fget_exchange_rate(JPY).'
');



You could add this to an automatic script to update the prices on your site daily. However, please be aware that you still need to keep an eye on things just incase you encounter problems.

Friday, 19 February 2010

Vi delete line if search does not exist

Right, if you have ever had to scroll through an endless text file looking for the needle in a haystack, there is a simpler way using the vi editor. Using vi, You can use a simple search and delete command to search the file and delete lines where a phrase doesn;t exist, like so;

:g!/text to look for/d

The example above searches all lines for text containing 'text to look for' and deletes the line if the text does not exist.

You could do the opposit and delete lines where the text exists like so;

:g/text to look for/d

Tuesday, 16 February 2010

json_decode Fatal error: Cannot use object of type stdClass as array

You may receive the following error when encoding and decoding information using json in php

Fatal error: Cannot use object of type stdClass as array

When using json_decode, information is by default converted into an object. You need to use the function get_object_vars to convert the object into an array, like so;


$new_data = get_object_vars(json_decode($data));

print_r($new_data);

?>

Thursday, 17 December 2009

Enable php5 on 1and1

Arrrggg - made a website in php5 and then get loads of errors when uploading to 1and1? Luckily you can change the default setting by adding the following line to a .htaccess file;


AddType x-mapp-php5 .php

Hope this helps - I found this information on the following link;

Source
http://tech.xptechsupport.com/using-php-5-with-1and1-hosting.html

Sunday, 4 October 2009

PHP convert minutes to hours

PHP convert minutes to hours

Just a little function i made;

function minutes_to_hours($inmin){
$lh = floor($inmin/60);
$lm = $inmin - ($lh*60);
if ($lh > 0) return $lh.'h '.$lm.'m';
return '0h '.$lm.'m';
}

So calling minutes_to_hours(125) = 2h 5m

Tuesday, 22 September 2009

Retrieve Mysql Lost Data

Right, well have you ever been in a position where you have lost information on websites through incorrect sql? Well, chances are that not everything is lost, especially with mysql.

Mysql records all sql statements run on mysql a compressed binary log. Everytime mysql restarts, a new log is created. In fedora, these logs are located in /var/lib/mysql/. For example, you will see files named mysql-bin.000001. However, to make use of them, first you must extract them into a readbale forma using the mysqlbinlog tool.

mysqlbinlog takes a binary log file and then does something with it. For example, to view the file, simply use the following example;

mysqlbinlog mysql-bin.000001

To write the log to a singel file, use the following command;

mysqlbinlog mysql-bin.000001 > all_sql_statements.sql

Then you can simply read the fil and take the statements you need from it.

Thursday, 16 July 2009

PHP Session Test

Recently, i've had problems setting a clients site live on a 3rd party providers hosting. The problem is the site wouldn't allow sessions to be written so login scripts and catcha codes did not work as intended. The main problem is that technical support always blame programmers code before actually investigating the problem (sigh).

Therefore here is a simple php script to prove to the technical support that sessions are not working as they should;

<?
session_start();
if($_GET["test"] == '1'){
if($_SESSION['atest'] == 'yes'){
echo('Your hosting supports sessions');
} else echo('Your hosting does not support sessions');
} else {
$_SESSION['atest'] = 'yes';
echo '
<head>
<script type="text/javascript">
<!--
function delayer(){
window.location = "'.$_SERVER['PHP_SELF'].'?test=1";
}
//-->
</script>
</head>
<body onLoad="setTimeout(\'delayer()\', 5000)">
About to test sessions.
<br /><br />
please wait...
</body>
';
}
?>

The script performs a 301 redirect to test if sessions are working correctly when a page is refreshed.

Sunday, 25 January 2009

Mysql Remove Line Breaks

I've recently had line breaks added to some data i've imported. Here's how you remove line breaks at the beginning and end of a field in mysql;

update temp_table set fieldname=trim(both char(13) from fieldname)

The above is only if you are in windows. I believe you can also use the folowing for linux;

update temp_table set fieldname=trim(both '\n' from fieldname)

You should also be able to use reaplce usinng the char method, e.g.

update temp_table set fieldname=replace(fieldname, char(13), '-')

I've not tested it though - I hope this helps!

Friday, 16 January 2009

MySQL Monthly Report

Here is is brief howto on generating a Monthly MySQL report from an orders table.

This example assumes you have a table called orders a stored date field called added and a price field for each order - in this example the price is stored as a varchar so it is casted using a (0+price).

The fist column returned is the current month, the second is the total price for that month. Here is the MySQL SQL Monthly Report Query;


SELECT TIMESTAMPDIFF(MONTH, STR_TO_DATE(concat(month(added),'/1/',year(added)), '%m/%d/%Y'), STR_TO_DATE(concat(month(now()),'/',DAYOFMONTH(LAST_DAY(now())),'/',year(now())), '%m/%d/%Y')) as tmonth,
sum(0+total_price) as lprice
from orders
where valid=1 and total_price > 0
group by tmonth


There probably are quicker ways of doing this but it seems like the best solution for reporting on a single orders table. This example basically makes the date as a string using CONCAT and then compare it.

I hope this helps.

Saturday, 22 November 2008

Sendmail stat=Deferred: Name server: host name lookup failure

It's a saturday. I have just spent 4 1/2 hours making sendmail actually work on a development server. All other websites I found gave me useless information on how to fix this, So I thought I'd post my fix here to Save countless hours of your weekend....

I kept receiving the followingerror

stat=Deferred: Name server: host name lookup failure

in my maillog file.

The main crox of the problem is that I set up a FC9 development server on my local network without installing Bind. At the time I didn't want to use Bind, which is a common thing not to have on a development server. However, sendmail doesn't look at my hosts file to resolve network addresses... oh no, why be so simple! instead isendmail decides to ignore my hosts file and visits the router to find out where localhost is. Therefore, to fix this problem, you need to install bind and just setup a localhost.

You Need to install Bind on your server to get Sendmail to work.



Don't rely on your hosts file. If you are unfamiliar with using Bind, on fedora you can just type; yum install bind bind-chroot. You can setup a simple configuration using this guide.

After you have Bind setup, you will then need to edit your network settings to make sure all DNS requests look to your server first, before going to the internet to resolve. So edit this file;

vi /etc/sysconfig/networking/devices/ifcfg-eth0

and change

DNS1=192.168.1.1

to

DNS1=127.0.0.1
DNS2=192.168.1.1

Restart your server and make sure that sendmail and bind are both up and running. Then try crossing your fingers, finding some wood to touch and then sending an email.

For me, this worked a treat and shows in my case that Sendmail completely ignores my hosts file and goes straight for the servers primary DNS setting.

Friday, 19 September 2008

Apache Automatic Sites Using VirtualDocumentRoot

Right, so i hate having to go edit config files when i'm editing and changing loads of new sites every day. It's time consuming and it breaks up my development.


I have a Fedora linux development server setup. I have a staic ip address and I have bind setup and a domain (*.mydomain.com) with wildcard subdomains pointing to it. That allows me to make a new site on my subdomain per website i'm editing and then i can demonstrate that to clients without ftp-ing the site and uploading databases.


For example if i'm editing newsite.com, i download a copy to my dev server, then log into my dev server apache config file and add a virtualhost for newsite.com.mydomain.com I can then edit this version of the site, allow the client to approve the site, then ftp up my changes.


However, if you have over 20 of these sites it gets a bit confusing in your apache file, and it also breaks up development time when you edit the file, not to mention increasing the chance of you fucking things up.


Therefore, on a recent new install of my dev server, i decided to spend some time researching into apaches ability to rewrite stuff. I use mod_rewrite quite heavily and I wondered if it allows you to edit things before apache runs any php code. After much reading of peopletrying to do stupid nonsensical things with apache that have no real point... I happend across a way of doing this using the apache VirtualDocumentRoot. Here's an example;


<virtualhost>

ServerAlias *.mydomain.com

DocumentRoot /home/www/sites

VirtualDocumentRoot /home/www/sites/%-3+/

</virtualhost>


So, if you have <strong>sitea.com.mydomain.com</strong> this now maps to /home/www/sites/sitea.com/.


There is one small problem with this; If you use $_SERVER['DOCUMENT_ROOT'] in php, then this causes problems as document_root point to /home/www/sites. But, there's a work around for this. You have to make a php file to reset document_root and make that file run before anything else when the server requests this page. Here's an example of the php file;


<?

$location = explode(".",$_SERVER['HTTP_HOST']);

for($i=sizeof($location)-6; $i>=0; $i--) $lurl = '.'.$location[$i].$lurl;

$lurl = '/'.ltrim($lurl, '.');

$_SERVER[DOCUMENT_ROOT] .= $lurl;

?>


The above script resets the document_root variable correctly, Now you just need to edit the Apache config file;


<virtualhost>

ServerAlias *.mydomain.com

DocumentRoot /home/www/sites

VirtualDocumentRoot /home/www/sites/%-3+/

php_admin_value auto_prepend_file /home/www/set_path.php

</virtualhost>


Voila! You should now be able to make dev sites without having to worry about the apache config files ever again!

Monday, 9 June 2008

MySQL PHP Database Ripper

Recently, I've been working on several projects where direct database access has been an issue.

To get around this, i've made a php mysql Database Ripper. It reads the database schema and then prints out the table structure and information for each table.

Here's the source - Enjoy :)


/************************************

db connection

************************************/

$host = "localhost";

$user = "dbuser";

$pass = "dbpassword";

$dbname = "dbname";


$db = mysql_connect($host, $user, $pass) or die(mysql_error());

mysql_select_db($dbname, $db) or die(mysql_error());


/***********************************************************/


$ic = 0;


$lsql = "show tables;";

if ($result = mysql_query($lsql)){

while ($row = mysql_fetch_array($result, MYSQL_NUM)){

$mySQLArray[$ic++] = $row[0];

}

mysql_free_result($result);

}


foreach ($mySQLArray as $litem){

$lsql = "SHOW COLUMNS FROM ".$litem.";";

$lreturn .=("create table ".$litem."(\r\n");

$lcount = 0;

if ($result = mysql_query($lsql)){

while ($row = mysql_fetch_array($result, MYSQL_NUM)){

if ($lcount > 0) $lreturn .=(",\r\n");

$lreturn .=($row[0]." ".$row[1]);

if ($row[2] == "NO") $lreturn .=(" NOT NULL ");

if ($row[4] != "") $lreturn .=(" default '".$row[4]."' ");

if ($row[3] == "PRI") $lreturn .=(" primary key ");

$lreturn .= (" ".$row[5]." ");

$lcount++;

}

mysql_free_result($result);

}

$lreturn .=(") ENGINE=InnoDB DEFAULT CHARSET=latin1;\r\n\r\n");

$lsql = "select * FROM ".$litem.";";

if ($result = mysql_query($lsql)){

while ($row = mysql_fetch_array($result, MYSQL_NUM)){

$lreturn .= "insert into ".$litem." values (";

$lstr = "";

foreach($row as $lrow){

$lstr .= "'".mysql_real_escape_string($lrow) . "',";

}

$lreturn .= rtrim($lstr ,",").");\r\n";

}

mysql_free_result($result);

}

$lreturn .= ("\r\n\r\n\r\n");

}


echo($lreturn);


?>

Thursday, 31 January 2008

fedora yum mysql install guide

Here is a basic setup guide for installing mysql on a fedora systemusing the package manager yum.

First thing's first, you need to download and install mysql with the following command;

#> yum install mysql mysql-server mysql-devel

Next, open up your firewall on port 3306 - that's the port external connections (like mysql administrator) use to interact with the database.

#> vi /etc/sysconfig/iptables

Press i (to enter insert mode) and add these lines in an appropriate place;

-A RH-Firewall-1-INPUT -p tcp -m state -m tcp --dport 3306 --state NEW -j ACCEPT
-A RH-Firewall-1-INPUT -p udp -m state -m udp --dport 3306 --state NEW -j ACCEPT


Press esc to stop insert mode.
Type :wq

Next restart your firewall for the settings to take effect;

#> service iptables restart

Now navigate to the default mysql-server document directory, and edit the example large confige file for mysql;

#> cd /usr/share/doc/mysql-server-*/
#> vi my-large.cnf

Press esc
Type :w!/etc/my.cnf
Type :q

You have now overwritten your basic configuration file for mysql server. Once you have restarted the mysqld service (using #> service mysqld restart), these settings should now take effect and you should have the mysql service listening on port 3306.

However, you still require a mysql database user who can access the database from an external computer (using mysql administrator) and you also need to set your root password. For the sake of simplicity and to get you connected, i'm going to use the root user in mysql, however I would recomend you use different users to manage your server for security reasons.

Anyway, here's how to set the root password;

#> mysql -u root

use mysql
update user set Password=PASSWORD('yourpassword') where User like '%root%';
quit

Finally, restart the mysql service, for everything to take effect;

#> service mysqld restart

Voila, a workin mysql server which you can connect from external computers to port 3306 on your server.

Tuesday, 20 November 2007

Windows 2003 Shutdown Restart Command with Examples

Have you ever found loads of windows 2003 command examples, which say they work when the truth is they don't?

Well here are a couple of examples that do shutdown or restart the Server;

Shutdown Windows 2003



  • SHUTDOWN /s /d P:2:17



Restart Windows 2003



  • SHUTDOWN /r /d P:2:17

These two commands appear to work for me. visit this link (http://www.ss64.com/nt/shutdown.html) for further information.

Saturday, 29 September 2007

ie css bug fixes

Well, there are many problems that ie appears to have when it comes to css. Most problems can be fixed fairly easily when you know what the problem is, so I thought i'd list a few common fixes i use from time to time.


IE Position, Stretch or Browser Resize Problem


IE stretches too wide or after the browser is resized, ie doesn't reposition elements correctly.

ie fix

Apply position:relative to the body tag, the element and containing elements, which are effected by the bug. e.g. in your css file add

body,
#element_container,
#element{position:relative;}

You may also have to play around with width but the above code should work a treat!


IE White Space Bug

This usually occurs when you've been floating elements around each other. This manifests itself in in ie either as a big line space appears at the bottom of the elements or the elements don't stretch the page relative to each other.



IE White Space Fix

at the bottom of the elements, add a new block element like a paragraph tag with a style of clear:both; e.g.

You may also need to adjust the height, line height and the font size so the block element doesn't appear as a new line, e.g.;


Thursday, 30 August 2007

MySQL Password Reset Root

AAAAAAARRRRRRRRGGGGGGGGGHHHHHHHHHHHHHHHHHH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

If you're reading this - chances are, you're an idiot. I know this as I am also an idiot as I installed a development server recently and forgot the root password for mysql. Yes I should have written the password down, no I didn't. here's the steps for resetting the root password on a working linux server;

1.) First login as root via ssh
2.) kill the mysqld service and all other mysql running processes e.g.
#> service mysqld stop
#> ps waux

ps waux gets a list of all running processes

use kill to stop any running mysql processes eg kill 6194 (kill pid).

3.) After stopping/killing mysqld, run the foillowing line;
#> mysqld_safe --skip-grant-tables &

4.) You are now logged into mysql safe mode. Cut and paste the following lines

mysql -u root mysql
UPDATE user SET password=PASSWORD("your_password") WHERE User="root";
FLUSH PRIVILEGES;
exit;


5.) then start up the mysqld service;

#> service mysqld start

That's it - all done. Now remember to write down ur password this time u idiot!

Tuesday, 28 August 2007

SELinux CURL Problem

skip to solution



Recently, I made a recursive xml sitemap generator tool, which quickly generates a sitemap, calculating how popular certain pages are related to how may linke they have internally. This helps make quick, good xml sitemaps that google likes as it follows the rough popularity that google sees of each page.

So I spent about 3 hours on this script - making it proper kick ass only to discover that when I upload the script from my dev server to my live server - the fucker doesn't work! not only that, but there's nothing reported in /var/log/messages.

After updating php-curl using yum and turning my firewall off with still no luck - I decided to get heavy handed and ask my server people to reinstall a newer version of fedora.

so afterspending another half a day setting up ftp/httpd/iptables/mysql/php/bind/etc. I uploaded the xmlsitemap generator and it still doesn't fucking work!

Oh where do I start? 'Livid' doesn't even come close - not only had i wasted the best part of a day updating my server - I didn't even manage to fix my sitemap script!!!

However, i did now have a message in /var/log/messages;

comm="httpd" dest=80 scontext=root:system_r:httpd_t:s0 tcontext=system_u:object_r:http_port_t:s0 tclass=tcp_socket

After much googling, I found this solution;

Solution

in the cli, type the following

#> getsebool -a
#> setsebool httpd_can_network_connect true


The first command displays the current SELinux settings, the second should change the SELinux setting so that httpd can access tinterweb.

I think this is one of thise annoying SELinux bugs that no-one really understands as there's not much on google about it - however i've found loads of people moaning about it and not getting it to work. Therefore I hope this helps someone!

Saturday, 11 August 2007

Vi Search and Replace

Sometimes when working with Linux cli, you have to edit files and make bulk changes to configuration files.

I use vi as a text editor and I thought I'd add this example fo search and replace using vi;

:1,$s/sometexttoreplace/newtext

In the above example, 1 represents the first line, $s represents the end line.

One important thing to note is that you need to escape any characters like dots, for example;

:1,$s/suffolkweb-design\.co\.uk/suffolk-web-design\.com

would be the way you change domain names from suffolk-web-design.co.uk to suffolk-web-design.com

Wednesday, 8 August 2007

Fedora Startup Scripts

I have a fedora core box which needs to run different scripts on startup to connect to other boxes on the network.

After a bit of fiddling around, I found what appears to be the best solution for me, using ntsysv and init.d. Here's how it's done;

1.) make a new file in the /etc/init.d/ directory
2.) add your script to this file with the following lines at the top;
#!/bin/bash
# chkconfig: 345 85 15
# description: of your file

3.) enter this in the shell;
chkconfig --add startup_filename

4.) type ntsysv - your startup script should now be in the list, checked and ready for action!

It's that easy!