Back to Top

Category: PHP

Setting The Path To Home Directory In PHP

Got two methods, one for WordPress and another for other general PHP scripts.

 

WordPress; Simply use the constant ABSPATH eg file(ABSPATH.”some-other-folder/some-file.txt”); – it returns the path to where wp-config.php is located for the current wordpress install.

 

General: Can use the following to obtain the home or root folder.. $doc_root = preg_replace(“!${_SERVER[‘SCRIPT_NAME’]}$!”, ”, $_SERVER[‘SCRIPT_FILENAME’]);

 

Note: $doc_root won’t include an end / – so on any additional file/path one will need to be added.

 

Posted in PHP, Wordpress |

Making sure php file_get_contents accept all SSL certificates websites

Problem.

When accessing https SSL certified websites, they are often rejected as php cannot process the certificate attached to the website and/or user agent exceptions, one way around that is to make php accept all certificates.

file_get_contents SSL operation failed with code 1 SSL3_GET_SERVER_CERTIFICATE certificate verify failed.

Here is the code to get around that.. also sets a 60 second timeout, and a user agent string.

$dargs=array("ssl"=>array("verify_peer"=>false,"verify_peer_name"=>false),"http"=>array('timeout' => 60, 'user_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.0.0.1'));

$response = file_get_contents("your SSL url entered here", false, stream_context_create($dargs));

echo $response; // or code to handle returned url contents
Posted in PHP |

Checking http header codes for dead links, redirects

Simple code to check the http returned header code of ‘real world’ websites… I say real world websites as many servers these days block invalid user agent strings (mod_security plugins), so need to set a fake valid one first.

$user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.0.0.1';
ini_set('user_agent', $user_agent);

$url = "url to test here"; // eg http://www.google.com
$urlinfo=get_headers($url);
$statuscode= $urlinfo[0];

echo($url." ".$statuscode."\n");

Posted in PHP |

Remote url mime type function

PHP function to return a remote url mime type:

function get_remote_mime_type($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_exec($ch);
return curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
}
Posted in PHP |

Calculating gamma and cumulative gamma distributions in PHP

PHP code to calculate gamma distributions and cumul gamma distributions – similar to excel’s gammadist() functions.

function getgamma($x, $k = 1, $theta = 1) {
		return pow($x, $k - 1)*exp(-$x/$theta)/(gamma($k)*pow($theta, $k));
	}

function getcumulgamma($x, $k = 1, $theta = 1) {
		return lowerGamma($k, $x/$theta)/gamma($k);
	}

function lowerGamma($s, $x) {
		//Special thanks to http://www.reddit.com/user/harlows_monkeys for this algorithm.
		if ($x == 0) return 0;
		$t = exp($s*log($x)) / $s;
		$v = $t;
		for ($k = 1; $k < 150; ++$k) {
			$t = -$t * $x * ($s + $k - 1) / (($s + $k) * $k);
			$v += $t;
			if (abs($t) < 0.00000000001) break;
		}
		return $v;
	}

function gamma($x) {
		if ($x <= 0) {
		return NAN;
		} else {
			return sqrt(2*M_PI/$x)*pow((1/M_E)*($x+(1/(12*$x - 1/(10*$x)))), $x);
		}
	}

Posted in PHP |

Code to remove duplicate piwik domain entries

I have used the following code to remove any duplicate website entries in a piwik site statistics package – sometimes occurs if account addition apis are used elsewhere. Replace yourtoken with your piwik api token, and http://yoursite/piwik with your piwik sites main url path – do not include a final / at the end. Hope this helps someone.


set_time_limit(0);
error_reporting(0);

$token = "yourtoken";
$piwiksite = "http://yoursite/piwik";


$get_sites = $piwiksite."/index.php?module=API&method=SitesManager.getAllSites&format=xml&token_auth=".$token;

$xml=file_get_contents($get_sites);

$rows = new SimpleXMLElement($xml);

$names=array();
$dups=array();
foreach ($rows->xpath('//row') as $row) {
$id=$row->idsite;
$name=$row->name;
$name=str_ireplace('http:','',$name);
$name=str_ireplace('www.','',$name);
$name=strtolower($name);
if(in_array($name,$names)===false) {
$names[]=$name;
} else {
$dups[]=$id;
}
}

if(count($dups)>0) {
foreach($dups as $id) {
$delete_site = $piwiksite."/index.php?module=API&method=SitesManager.deleteSite&idSite=".$id."&token_auth=".$token;
$result=file_get_contents($delete_site);
echo($result);
echo("\n");
}
}

Posted in PHP |

Importance of using XML encoding for doc objects

Unless you want loads of weird characters displayed in a php document object it is very important to use encoding and decode the orginal string to be processed first when loading the org. string

eg this uses utf-8

$xml = new DOMDocument();
$xml->encoding = 'utf-8';
@$xml->loadHTML(utf8_decode($string));

Bye bye weird characters (doc objects in php tend to change the character codings, so this avoids the problem)

Posted in PHP |

Converting wordpress sql xml post table to html and then doc file

Hi, sometimes you only have available from backups an old wordpress post table sql xml file, which you might want to convert to a word doc file for say rewriting for another web site.

The following simple snippet of code I have used successfully to extract each posts title and contents (not excerpt) and add to a html file.

Starting point was a post sql xml file called bhrt.me.wp_posts.xml.. dumped from a mysql database (wp_posts table)/

Script could be called anything, but I called it ‘extract_posts.php’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
 
// replace bhrt.me.wp_posts.xml with your post table sql xml filename
 
$fname = "bhrt.me.wp_posts.xml";
 
$xml=simplexml_load_file($fname);
 
echo("<html>\n
<head>\n
<meta charset=\"UTF-8\">\n
<meta http-equiv=\"Content-Type\" content=\"application/xhtml+xml; charset=utf-8\"/>\n
</head>\n
<body>\n");
 
foreach ($xml->database->table as $table) {
$post_title="";
$post_type="";
$post_content="";
 
foreach ($table->column as $column) {
 
    switch((string) $column['name']) {
    case 'post_title':
        $post_title = $column;
        break;
    case 'post_content':
        $post_content = $column;
        break;
    case 'post_type':
        $post_type = $column;
        break;
    }
 
}
 
if((($post_type=='post')||($post_type=='page'))&&($post_content!="")) {
 
if(stripos($post_content,'[contact-form')===false) {
 
echo "<div>\n";
 
echo "<p><h2>".$post_title."</h2></p>\n";
 
echo("<br>\n");
 
$post_content = preg_replace("/<img[^>]+\>/i", "", $post_content); 
 
echo "<p>".$post_content."</p>\n";
 
echo "</div>\n";
 
echo("<br>\n");
 
}
 
}
 
}
 
echo("</body>\n
</html>");
 
?>

Run locally via ‘php extract_posts.php > output-filename.html’ Then load the html file into your word or openoffice package – tested with libreoffice.

Posted in PHP, Wordpress |

US phone number validation function

A quick function used to validate and format US based phone numbers.. enter phone number into function, and either returns false if deemed to be invalid, or returns better formatted… idea for form validation checks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function VALIDATE_USPHONE($value)
{
$regex = '/(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
        .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
        .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?/'; 
 
    if ($Valid = preg_match($regex, $value, $matches ) ) {
    $formatted = "($matches[1]) $matches[2]-$matches[3]";
    if ($matches[4]) $formatted .= " x$matches[4]";
    return $formatted;
    } else {
    return false;
    }
 
}
Posted in PHP |

A php imap script to download gmail attachments

This is a simple php script to automatically download gmail attachments based on incoming author and subject text of email into folder script is run on, but other imap search queries could be used. I use it locally on my linux box in the form of ‘php download-directly-from-gmail.php’ I hope it helps someone.

eg.

orion@orion-Dimension-2350 ~/Downloads/SHUTTERSTOCK IMAGES $ php download-directly-from-gmail.php
173-shutterstock_117192613.jpg .. saving
174-shutterstock_125141474.jpg .. saving
175-shutterstock_126624197.jpg .. saving
170-shutterstock_107627765.jpg .. saving
171-shutterstock_116964424.jpg .. saving
172-shutterstock_117192571.jpg .. saving
166-shutterstock_77529775.jpg .. saving
167-shutterstock_85118617.jpg .. saving
168-shutterstock_93945283.jpg .. saving
169-shutterstock_107147873.jpg .. saving

Script below.. with password and username nulled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
set_time_limit(0); 
 
 /* connect to gmail with your login account details */
 
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'somebody@gmail.com'; # e.g somebody@gmail.com
$password = 'your-gmail-password';
 
 
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
 
 
$emails = imap_search($inbox,'FROM "person" SUBJECT "something in subject"'); // finds all incoming mail from "person" containing partial text in subject 'something in subject'
 
if($emails) {
 
    $count = 1;
 
 
    rsort($emails);
 
 
    foreach($emails as $email_number) 
    {
 
        $overview = imap_fetch_overview($inbox,$email_number,0);
 
        $message = imap_fetchbody($inbox,$email_number,2);
 
        $structure = imap_fetchstructure($inbox, $email_number);
 
        $attachments = array();
 
        if(isset($structure->parts) && count($structure->parts)) 
        {
            for($i = 0; $i < count($structure->parts); $i++) 
            {
                $attachments[$i] = array(
                    'is_attachment' => false,
                    'filename' => '',
                    'name' => '',
                    'attachment' => ''
                );
 
                if($structure->parts[$i]->ifdparameters) 
                {
                    foreach($structure->parts[$i]->dparameters as $object) 
                    {
                        if(strtolower($object->attribute) == 'filename') 
                        {
                            $attachments[$i]['is_attachment'] = true;
                            $attachments[$i]['filename'] = $object->value;
                        }
                    }
                }
 
                if($structure->parts[$i]->ifparameters) 
                {
                    foreach($structure->parts[$i]->parameters as $object) 
                    {
                        if(strtolower($object->attribute) == 'name') 
                        {
                            $attachments[$i]['is_attachment'] = true;
                            $attachments[$i]['name'] = $object->value;
                        }
                    }
                }
 
                if($attachments[$i]['is_attachment']) 
                {
                    $attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
 
                    if($structure->parts[$i]->encoding == 3) 
                    { 
                        $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    elseif($structure->parts[$i]->encoding == 4) 
                    { 
                        $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                    }
                }
            }
        }
 
        foreach($attachments as $attachment)
        {
            if($attachment['is_attachment'] == 1)
            {
                $filename = $attachment['name'];
                if(empty($filename)) $filename = $attachment['filename'];
 
                if(empty($filename)) $filename = time() . ".dat";
 
                echo($filename." ");
 
                if(file_exists($email_number . "-" . $filename)) {
                echo(".. file already exists! \n");
                } else {
                echo(".. saving \n");
                $fp = fopen($email_number . "-" . $filename, "w+");
                fwrite($fp, $attachment['attachment']);
                fclose($fp);
                }
            }
 
        }
 
    }
 
} 
 
imap_close($inbox);
 
echo "Done";
 
?>
Posted in PHP |