"Ph" is most commonly used in words that come from Greek, like "philosophy". The Greek letter that makes the "F" sound is "phi", written like φ.
As for "Gh", most of the words containing it come from German and old English. It was pronounced then as it"ch" is in German today - as a rasp in the back of the throat, like the "ch" in "Loch Ness". Nobody really knows why, but around the same time that vowels shifted and English spelling was regularized, the "gh" sound was removed from English entirely. In some cases, it was just made silent (knight, sigh), and in some others it changed into a lot of different sounds. Now it's just one of the exceptions learners - both foreign and native - have to live with.
[source]