» Programming » PHP » File & URL Functions

mkdir (recursive)


1
2
3
4
5
6
7
8
function mkdir_x($path, $mode=0777) {
  $exp = explode("/",$path);
  $dir = '';
  foreach ($exp as $n) {
    $dir .= $n . '/';
    if (!file_exists($dir)) mkdir($dir, $mode);
  }
}

 
 

Get Contents of a URL


PHP compiled with “‘–with-curlwrappers” option enabled can sometimes cause unwanted results when attempting to use fopen() to URLs that send responses other than “200 OK” (eg: “404 NOT FOUND“). To get around this issue, we use this basic yet configurable function: url_get_contents()

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
function url_get_contents($url, $followRedirect=true, $failOnError=true) {
  if (strpos($url, '/', 9) === false) $url .= '/';
 
  $ch = curl_init($url);
 
  curl_setopt($ch, CURLOPT_AUTOREFERER,    true);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  curl_setopt($ch, CURLOPT_FAILONERROR,    $failOnError);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $followRedirect);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
  curl_setopt($ch, CURLOPT_TIMEOUT,        20);
 
  $agent = ini_get('user_agent');
  if (is_string($agent)) {
    curl_setopt($ch, CURLOPT_USERAGENT,    $agent);
  }
 
  $contents        = curl_exec($ch);
  $data            = curl_getinfo($ch);
  $data['error']   = curl_error($ch);
  $data['errno']   = curl_errno($ch);
  $data['content'] = $contents;
 
  curl_close($ch);
 
  return $data;
}

 
 

Generate Short URLs


Repost.Me is a service for shortening URLs, as well as analytics tracking. This function will take in a URL, pass it to the Repost.Me service, and then return a short URL.

1
2
3
4
5
6
7
8
9
10
11
12
function repostme($url, $style=false) {
  $url  = 'http://make.repost.me/?url=' . rawurlencode($url);
  if ($style) $url .= '&style=' . rawurlencode($style);
  $file = false;
  $file = @fopen($url, 'rb');
  if (!$file) return false;
  $data = '';
  while (!feof($file)) $data .= fread($file, 1024);
  fclose($file);
  if (substr($data, 0, 17) !== 'http://repost.me/') return false;
  return $data;
}