https://www.php.net/

Assign range of number to array

Easier way:

1
2
$foo = range(1, 5);
print_r($foo);

Harder way:

1
2
$foo = array();
for($i = 1; $i <= 5; $i++) $foo[] = $i;

both will output:

1
2
3
4
5
6
7
8
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Reference:

Move a file in server

1
2
3
4
var $source      = '/source/path/to/your/file.jpg';
var $destination = '/destination/path/to/your/file.jpg';

rename($source, $destination);
Reference:

Create intermediate directory

1
2
$path = '/path/to/your/dir';
mkdir($path, 0777, true);

The 3rd argument is allowed to create intermediate directory.

Reference:

Get client located country info

We make use of hostip.info api to get the location details.

1
2
3
4
5
6
7
8
9
10
11
$url = 'http://api.hostip.info/get_json.php?ip=' . $_SERVER['REMOTE_ADDR'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
ob_start();
curl_exec($ch);
$content = ob_get_contents();
ob_end_clean();
curl_close($ch);

$result = json_decode($content);

Get the date x days before

1
2
3
4
5
6
/*
* The format is 'Y-m-d' (i.e. 2013-02-26)
*/
function getPreviousDateFromDate($date, $days_ago) {
return date('Y-m-d', strtotime($date . ' -' . $days_ago . ' days'));
}

Inner function to access outer function’s variable

1
2
3
4
5
6
7
8
function outer($foo) {
// now the inner want to use the variable 'foo'
$inner = function() use ($foo) {
echo $foo;
}

$inner();
}

the use keyword is to let the inner function to access the outer function’s variable

Reference:

Convert array to query string

1
2
3
4
5
6
7
$params = array(
'p1' => 'value1',
'p2' => 'value2',
);
$query_string = http_build_query($params);

echo $query_string; // p1=value1&p2=value2
Reference:

Removed attributes accept href

1
2
3
4
5
6
7
<?php
$html = 'This is a <a id="lnk" href="http://www.google.com" id="lnk">Google link</a> for you.'
. ' This is another <a id="lnk" href="http://www.facebook.com">Facebook link</a> for you';

$new_content = preg_replace('/<a\s[^>]*href=\"([^\"]*)\"[^>]*>(.*)<\/a>/siU', '<a href="$1">$2</a>', $html);

echo $new_content;

The result will be

1
This is a <a href="http://www.google.com">Google link</a> for you. This is another <a href="http://www.facebook.com">Facebook link</a> for you
Reference:

Check whether is POST request

1
2
3
4
<?php
function is_post() {
return $_SERVER['REQUEST_METHOD'] === 'POST';
}
Reference:

URL from text (href)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
function url_from_text($text) {
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
return preg_replace($reg_exUrl, '<a href="' . $url[0] . '">' . $url[0] . '</a>', $text);
} else {
// if no urls in the text just return the text
return $text;
}
}
Reference:

Get last month date range

1
2
$first_day_prev_month = date('Y-m-1', strtotime('first day of previous month'));
$last_day_prev_month = date('Y-m-t', strtotime('first day of previous month'));
Reference:

fgetcsv read all as ONE line

This is due to End-of-Line (EOL) problem in different environment (Windows is different from UNIX)

The EOL in Windows is ^M, you can see this if you try to open via VIM.

1
2
3
while (($data = fgetcsv($handle, 10000)) !== FALSE) {
print_r($data);
}

If you read the file which contains of ^M character, then everything will be in a single line.

In order to solve this, add this before the while statement

1
ini_set('auto_detect_line_endings', true);
Reference:

Loop through dates

1
2
3
4
5
6
7
8
9
// Start date
$start_date = '2013-12-06';
// End date
$end_date = '2014-04-20';

while (strtotime($start_date) <= strtotime($end_date)) {
echo "$start_date\n";
$start_date = date('Y-m-d', strtotime('+1 day', strtotime($start_date)));
}
Reference:

Get image type

1
2
3
4
5
6
7
8
9
10
switch(exif_imagetype('image/foo.jpg')) {
case IMAGETYPE_JPEG:
echo 'JPEG';
break;

case IMAGETYPE_PNG:
echo 'JPEG';
break;
...
}
Reference:

Insert a string into another string

1
2
3
4
5
6
$str = 'abc123';
$result = substr_replace($str, '-', 3, 0);
echo $result;

// output
// abc-123
Reference:

Re-format date using preg_replace

e.g. Format a date with dd/mm/yyyy to yyyy-mm-dd

1
2
3
4
5
6
7
$date = '31/08/1987';

$pattern = '/^(\d{2})\/(\d{2})\/(\d{4})$/';
$replacement = '$3-$2-$1';

$formatted_date = preg_replace($pattern, $replacement, $date);
echo $formatted_date;

Output:

1
1987-08-31
  • (\d{2}) - the braces is to keep a reference that can use it later (i.e. $1). Where \d is to match integer only and {2} is exactly 2 characters
  • \/ - because the slash (/) is a special character, so have to use backslash (\) to escape it
  • $3-$2-$1 - is the sequence of the submatch (i.e. (\d{2}) those inside the braces)
Reference:

iPad photo orientation issue by rotate image manually

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function resample($jpgFile, $thumbFile, $width, $orientation) {
// Get new dimensions
list($width_orig, $height_orig) = getimagesize($jpgFile);
$height = (int) (($width / $width_orig) * $height_orig);
// Resample
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($jpgFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Fix Orientation
switch($orientation) {
case 3: // 180 rotate left
$image_p = imagerotate($image_p, 180, 0);
break;
case 6: // 90 rotate right
$image_p = imagerotate($image_p, -90, 0);
break;
case 8: // // 90 rotate left
$image_p = imagerotate($image_p, 90, 0);
break;
}
// Output
imagejpeg($image_p, $thumbFile, 90);
}
Reference:

Remove all html tags & replace &nbsp; to <space>

1
str_replace('&nbsp;', ' ', strip_tags($description));

Replace new line character with

1
$new_text = str_replace(array("\r", "\r\n", "\n"), ' ', $text);
Reference:

Regex match any characters INCLUDING

1
2
3
4
5
6
7
8
9
10
11
12
$content = <<<EOD
<html>
<title>Test</title>
<body>
<div id="some-div">
Some text here
</div>
</body>
</html>
EOD;
$pattern = '/<body.*>(.*)<\/body>/s'; // the last characters 's' is to match new line as well
preg_match($pattern, $content, $result);

$result[0] will give you

1
2
3
<div id="some-div">
Some text here
</div>
Reference:

Receive json value from HTTP POST

This will show nothing

1
print_r($_POST);

In order to get the value

1
2
3
4
5
6
$json = file_get_contents('php://input');
if ($json) {
$post = json_decode($json, true);
}
print_r($post);
// access via $post['param1']
Reference:

Error on mysqli

The error message was No such file or directory

Solution
simply change the host to 127.0.0.1 instead of localhost

Reference:

Save web image into file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function save_image($url, $dest_path) {
// get the file extension
$ext = pathinfo($url, PATHINFO_EXTENSION);

// make sure the file name is unique, so use microtime here
$filename = str_replace(array('0.', ' '), array('', ''), microtime()) . '.' . $ext;

$ch = curl_init($url);
$fp = fopen($dest_path.'/'.ltrim($filename, '/'), 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
// return the new filename at the end
return $filename;
}
References:

Regex validation for color code hex

1
2
3
4
if(preg_match('/^#?([a-f0-9]{6}|[a-f0-9]{3})$/', $hex))
{
// correct format
}

The regex above check the optional hash (#) and accept either 3 or 6 characters.

Reference:

Updated all null to empty string in an array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function null_to_empty_str($obj) {
$new_json_array = array();
foreach ($obj as $k => $v) {
if (is_array($v)) {
$new_json_array[$k] = null_to_empty_str($v);
continue;
}
if ($v === null) {
$new_json_array[$k] = '';
continue;
}
$new_json_array[$k] = $v;
}
return $new_json_array;
}

phpMyAdmin auto login

Edit the file config.inc.php

1
2
3
4
5
// change from 'cookie' to 'config'
$cfg['Servers'][$i]['auth_type'] = 'config';
// add root username & password
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'root_pass';
Reference:

Make use of array_map to create key-value array

1
2
3
4
5
6
7
8
9
10
11
$original = [
0 => ['id' => 'js', 'name' => 'foo'],
1 => ['id' => 'lim', 'name' => 'bar'],
];

$options = [];
array_map(function($obj) use (&$options) {
$options[$obj['id']] = $obj['name'];
}, $original);

print_r($options);

Result will be:

1
2
3
4
Array(
'js' => 'foo',
'lim' => 'bar',
)
Reference:

Call static method by dynamic class

1
2
3
<?php
$class_name = 'FooBar';
$class_name::callMethod($arg1...);

If want to initialize

1
2
<?php
$obj = new $class_name();

Replace html tag by regex

Let say replace <a> to <em>

1
2
3
<?php
$html = '<strong>No 1.</strong> This is a <a href="...">Link</a>';
preg_replace_callback('(<a.*>(.*?)</a>)', function($a) {return '<em>' . $a[1] . '</em>');}, $html);
Reference:

Call dynamic class static function

1
2
3
<?php
$class_name = 'Helpers\DateHelper';
$result = call_user_func($class_name . '::convert', '2018-04-30', 'M d, Y');

This is equivalent to Helpers\DateHelper::convert('2018-04-30', 'M d, Y')

Reference:

DOMDocument

Using this with Symfony DomCrawler.

Append new element

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
use Symfony\Component\DomCrawler\Crawler as DomCrawler;

$html = ....;
$doc = new \DOMDocument;
$doc->loadHtml($html);
$crawler = new DomCrawler($doc);
$row_nodes = $crawler->filter('.rows');
// loop through each .row
foreach ($row_nodes as $node) {
$div_col = $doc->createElement('div');
$div_col->setAttribute('class', 'col-md-12');
$div_col->textContent = 'This is the inner html content';
$node->appendChild($div_col);
}

echo $crawler->html();
Reference:

Facebook

Initialize the facebook object

1
2
3
4
$facebook = new Facebook(array(
'appId' => '<your app id here>',
'secret' => '<your app secret here>',
));

Get current user’s allowed permission

1
2
$permissions = $facebook->api('/me/permissions');
print_r($permissions);

Get current user’s info

1
$user = $facebook->api('/me');

TCPDF

Align height of HTML table row

Adjust the line-height & font-size, otherwise it won’t work.

Example

1
2
3
4
5
<table cellpadding="0">
<tr style="line-height: 5px; font-size: 4px;">
<td>Your content here</td>
</tr>
</table>

NOTE: margin & padding properties won’t work here

Reference: TCPDF - Is there a way to adjust single table row height?

WideImage

Resize image proportionally by height

Example shows resize the image to any width but exactly 100px height

1
2
$img = WideImage::load('/path/to/image.jpg');
$img->resize($img->getWidth(), 100)->saveToFile('/destination/image.jpg');

Set the width to original image size will achieve this.


Create empty image from text

1
2
3
4
5
6
7
8
9
10
11
12
// create emptye image with 100x100 size
$wideImage = \WideImage_TrueColorImage::create(100, 100);
// set the background transparent
$wideImage->fill(0,0, $wideImage->getTransparentColor());
// get the canvas and write text on it
$canvas = $wideImage->getCanvas();
// set the font with size 30 and font color to white
$canvas->useFont('/path/to/fonts/Helvetica-Bold.otf', 30, $wideImage->allocateColor(255, 255, 255));
// write text to canvas
$canvas->writeText('center', 'center', 'Your text goes here');
// save to file
$wideImage->saveToFile('output.png');
Reference: