Category "PHP" (56)
Force the browser to download the file instead of opening it ... Reveal Code
$file_text = 'Some text here';
if (isset($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
Header('Content-Type: application/force-download');
else
Header('Content-Type: application/octet-stream');
Header('Accept-Ranges: bytes');
Header('Content-Length: ' . strlen($file_text));
Header('Content-disposition: attachment; filename="downloaded_file.txt"');
echo $file_text;
exit();
Extract .zip files, answered here: http://stackoverflow.com/questions/5653130/extract-zip-files-using-php ... Reveal Code
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
Determination of the country by IP using geoplugin.net OR ipinfodb.com. Will return the country code in "Alpha-2 ISO 3166-1" format (a two-char code) ... Reveal Code
function get_country($ip_addr) {
$curlopt_useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0';
$url = 'http://www.geoplugin.net/php.gp?ip=' . $ip_addr;
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch1);
$geoplugin = unserialize($result);
if ($geoplugin[geoplugin_countryCode] != '') {
return $geoplugin[geoplugin_countryCode];
} else {
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip_addr);
$ch = curl_init();
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $curlopt_useragent,
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
);
curl_setopt_array($ch, $curl_opt);
$content = curl_exec($ch);
if (!is_null($curl_info)) {
$curl_info = curl_getinfo($ch);
}
curl_close($ch);
if (preg_match('{
Country : ([^<]*)}i', $content, $regs))
$country = $regs[1];
return $country;
}
}
Determination of the browser and its version by user-agent string. ... Reveal Code
function user_browser($agent) {
preg_match("/(MSIE|Opera|Firefox|Chrome|Version|Opera Mini|Netscape|Konqueror|SeaMonkey|Camino|Minefield|Iceweasel|K-Meleon|Maxthon)(?:\/| )([0-9.]+)/", $agent, $browser_info);
list(, $browser, $version) = $browser_info;
if (preg_match("/Opera ([0-9.]+)/i", $agent, $opera))
return 'Opera|' . $opera[1];
if ($browser == 'MSIE') {
preg_match("/(Maxthon|Avant Browser|MyIE2)/i", $agent, $ie);
if ($ie)
return $ie[1] . ' based on IE|' . $version;
return 'IE|' . $version;
}
if ($browser == 'Firefox') {
preg_match("/(Flock|Navigator|Epiphany)\/([0-9.]+)/", $agent, $ff);
if ($ff)
return $ff[1] . '|' . $ff[2];
}
if ($browser == 'Opera' && $version == '9.80')
return 'Opera|' . substr($agent, -5);
if ($browser == 'Version')
return 'Safari|' . $version;
if (!$browser && strpos($agent, 'Gecko'))
return 'Browser based on Gecko';
return $browser . '|' . $version;
}
PHP: Game server information
13.12.2013 16:42 Likrion PHP
Информация о игровом сервере на примере Counter strike сервера ... Reveal Code
PHP: Единая страница ошибок
13.12.2013 16:33 Likrion PHP
сохраняем как error.phprn а в делаем метку на нашу страницу ошибокrnrnrnrn ErrorDocument 400 / error.phprn ErrorDocument 401 / error.phprn ErrorDocument 403 / error.phprn ErrorDocument 404 / error.phprn ErrorDocument 500 / error.phprnrn ... Reveal Code
array('400 Плохой запрос', 'Запрос не может быть обработан из-за синтаксической ошибки.'),
403 => array('403 Запрещено', 'Сервер отказывает в выполнении вашего запроса.'),
404 => array('404 Не найдено', 'Запрашиваемая страница не найдена на сервере.'),
405 => array('405 Метод не допускается', 'Указанный в запросе метод не допускается для заданного ресурса.'),
408 => array('408 Время ожидания истекло', 'Ваш браузер не отправил информацию на сервер за отведенное время.'),
500 => array('500 Внутренняя ошибка сервера', 'Запрос не может быть обработан из-за внутренней ошибки сервера.'),
502 => array('502 Плохой шлюз', 'Сервер получил неправильный ответ при попытке передачи запроса.'),
504 => array('504 Истекло время ожидания шлюза', 'Вышестоящий сервер не ответил за установленное время.'),
);
$title = $codes[$status][0];
$message = $codes[$status][1];
if ($title == false || strlen($status) != 3) {
$message = 'Код ошибки HTTP не правильный.';
}
echo 'Внимание! Обнаружена ошибка '.$title.'!
'.$message.'
';
?>
debug doctrine count querys ... Reveal Code
/*
DROP TABLE IF EXISTS shop;
CREATE TABLE shop (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB
AUTO_INCREMENT = 4
AVG_ROW_LENGTH = 5461
CHARACTER SET cp1251
COLLATE cp1251_general_ci;
DROP TABLE IF EXISTS goods;
CREATE TABLE goods (
id INT(11) NOT NULL AUTO_INCREMENT,
id_shop INT(11) DEFAULT NULL,
name VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_goods_shop_id FOREIGN KEY (id_shop)
REFERENCES shop(id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
ENGINE = INNODB
AUTO_INCREMENT = 6
AVG_ROW_LENGTH = 3276
CHARACTER SET cp1251
COLLATE cp1251_general_ci;
INSERT INTO shop VALUES
(1, 'Shop A'),
(2, 'Shop B'),
(3, 'Shop C');
INSERT INTO goods VALUES
(1, 1, 'Goods 1 - A'),
(2, 1, 'Goods 2 - A'),
(3, 2, 'Goods 1 - B'),
(4, 2, 'Goods 2 - B'),
(5, 3, 'Goods 1 - C');
*/
require_once "composer/vendor/autoload.php";
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
$paths = array("/");
$isDevMode = false;
// the connection configuration
$dbParams = array (
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'test',
'dbname' => 'test',
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$logger = new \Doctrine\DBAL\Logging\DebugStack();
$config->setSQLLogger($logger);
$entityManager = EntityManager::create($dbParams, $config);
/**
* @Entity
* @Table(name="shop")
*/
class Shop {
/** @Id @GeneratedValue @Column(type="integer") */
public $id;
/** @Column(type="string") */
public $name;
/**
* @OneToMany(targetEntity="Goods", mappedBy="shop")
*/
public $goods;
public function __construct() {
}
}
/**
* @Entity
* @Table(name="goods")
*/
class Goods {
/** @Id @GeneratedValue @Column(type="integer") */
public $id;
/** @Column(name="id_shop")*/
public $idShop;
/**
* @ManyToOne(targetEntity="Shop", inversedBy="goods", fetch="EAGER")
* @JoinColumn(name="id_shop", referencedColumnName="id")
**/
public $shop;
/** @Column */
public $name;
}
$shopRepository = $entityManager->getRepository('\Shop');
$shops = $shopRepository->findAll();
echo "\n";
//print_r($shops);
foreach ($shops as $shop) {
//$shop->goods = null;
//print_r($shop);
echo $shop->id."-";
echo count($shop->goods)."\n";
foreach ($shop->goods as $goods) {
echo $goods->name.";";
}
echo "\n";
}
foreach ($logger->queries as $q) {
echo SqlFormatter::format($q['sql'])."
\r\n";
}
?>
PHP: php: get JSON request
php: get JSON request ... Reveal Code
$_POST = json_decode(file_get_contents('php://input'), true);
PHP: Make a thumbnail screenshot of the video
Make a thumbnail screenshot of the video using ffmpeg ... Reveal Code
$source_path = $_SERVER['DOCUMENT_ROOT'] . 'content/videos/my_video.mp4';
$dest_path = $_SERVER['DOCUMENT_ROOT'] . 'content/videos/my_video.jpg';
//"-10" means offset of 10 seconds from start
exec("ffmpeg -itsoffset -10 -i $source_path -s 320x240 $dest_path");
PHP: french months
10.08.2013 07:25 erwan PHP
an array to store french months ... Reveal Code
$mois=array('janvier','février','mars','avril','mai','juin','juillet','août','septembre','octobre','novembre','décembre');
PHP: Test a Password Strength
Test a Password Strength. Will return number (1-10), or a word ("Weak", "Normal", "Good", "Awesome"). ... Reveal Code
function PasswordStrength($password, $return_as_number = true) {
if (strlen($password) == 0) {
return 1;
}
$strength = 0;
/* Get the length of the password */
$length = strlen($password);
/* Check if password is not all lower case */
if (strtolower($password) != $password) {
$strength += 1;
}
/* Check if password is not all upper case */
if (strtoupper($password) == $password) {
$strength += 1;
}
/* Check string length is 8-15 chars */
if ($length >= 8 && $length <= 15) {
$strength += 1;
}
/* Check if lenth is 16 - 35 chars */
if ($length >= 16 && $length <= 35) {
$strength += 2;
}
/* Check if length >35 chars */
if ($length > 35) {
$strength += 3;
}
/* Get the numbers in the password */
preg_match_all('/[0-9]/', $password, $numbers);
$strength += count($numbers[0]);
/* Check for special chars */
preg_match_all('/[|!@#$%&*\/=?,;.:\-_+~^\\\]/', $password, $specialchars);
$strength += sizeof($specialchars[0]);
/* Get the number of unique chars */
$chars = str_split($password);
$num_unique_chars = sizeof(array_unique($chars));
$strength += $num_unique_chars * 2;
/* Strength is a number 1-10 */
$strength = $strength > 99 ? 99 : $strength;
$strength = floor($strength / 10 + 1);
/* Return number OR word */
if ($return_as_number) {
return $strength;
} else {
if (($strength >= 1) && ($strength < 3))
return 'Weak';
if (($strength >= 3) && ($strength < 6))
return 'Normal';
if (($strength >= 6) && ($strength < 8))
return 'Good';
if (($strength >= 8) && ($strength <= 10))
return 'Awesome';
}
}
PHP: wow class api
31.07.2013 11:38 Frey PHP
wow class api ... Reveal Code
switch ($array['class']) {
case 3:
$class = 'Охотник';
break;
case 4:
$class = 'Разбойник';
break;
case 1:
$class = 'Воин';
break;
case 2:
$class = 'Паладин';
break;
case 7:
$class = 'Шаман';
break;
case 8:
$class = 'Маг';
break;
case 5
$class = 'Жрец';
break;
case 6:
$class = 'Рыцарь смерти';
break;
case 11:
$class = 'Друид';
break;
case 9:
$class = 'Чернокнижник';
break;
case 10:
$class = 'Монах';
break;
default:
$class = 'Unknowkn';
break;
}
PHP: wow api race
31.07.2013 11:37 Frey PHP
wow api race ... Reveal Code
switch ($array['race']) {
case 1:
$race = 'Человек';
break;
case 8:
$race = 'Тролль';
break;
case 14:
$race = 'Пандарен';
break;
case 11:
$race = 'Дреней';
break;
case 22:
$race = 'Ворген';
break;
case 10:
$race = 'Эльф крови';
break;
case 4:
$race = 'Ночной эльф';
break;
case 3:
$race = 'Дворф';
break;
case 25:
$race = 'Пандарен';
break;
case 26:
$race = 'Пандарен';
break;
case 6:
$race = 'Таурен';
break;
case 5:
$race = 'Нежить';
break;
case 2:
$race = 'Орк';
break;
case 7:
$race = 'Гном';
break;
case 9:
$race = 'Гоблин';
break;
default:
$race = 'Unknown';
break;
}
PHP: Inverse function for nl2br
The inverse function for the standard nl2br: http://php.net/manual/en/function.nl2br.php ... Reveal Code
function br2nl($str) {
$str = preg_replace("/(\r\n|\n|\r)/", "", $str);
return preg_replace("=
=i", "\n", $str);
}
PHP: Class for encryption / decryption
Class for encryption / decryption. Found here: http://stackoverflow.com/a/2448441/1546928 ... Reveal Code
PHP: Get the user's age
Get the user's age by date of birth ... Reveal Code
function getAge($birth_date) {
return floor((time() - strtotime($birth_date)) / 31556926);
}
PHP: Remove an empty array elements
Remove an empty array elements ... Reveal Code
$myArray = array_diff($myArray, array(''));
Get zodiac sign by birth date ... Reveal Code
function getZodiacSign($birth_date) {
$bd = explode("-", $birth_date);
$daymonth = $bd[1] . "-" . $bd[2];
if ($daymonth >= '01-21' and $daymonth <= '02-20') {
$zodiac = 'Aquarius';
} elseif ($daymonth >= '02-21' and $daymonth <= '03-20') {
$zodiac = 'Pisces';
} elseif ($daymonth >= '03-21' and $daymonth <= '04-20') {
$zodiac = 'Aries';
} elseif ($daymonth >= '04-21' and $daymonth <= '05-20') {
$zodiac = 'Taurus';
} elseif ($daymonth >= '05-21' and $daymonth <= '06-21') {
$zodiac = 'Gemini';
} elseif ($daymonth >= '06-22' and $daymonth <= '07-22') {
$zodiac = 'Cancer';
} elseif ($daymonth >= '07-23' and $daymonth <= '08-23') {
$zodiac = 'Leo';
} elseif ($daymonth >= '08-24' and $daymonth <= '09-23') {
$zodiac = 'Virgo';
} elseif ($daymonth >= '09-24' and $daymonth <= '10-23') {
$zodiac = 'Libra';
} elseif ($daymonth >= '10-24' and $daymonth <= '11-22') {
$zodiac = 'Scorpio';
} elseif ($daymonth >= '11-23' and $daymonth <= '12-21') {
$zodiac = 'Sagittarius';
} else {
$zodiac = 'Capricorn';
}
return $zodiac;
}
//Will return "Aquarius"
echo getZodiacSign('1982-01-27');
Вычисление расстояния между двумя точками, в зависимости от их координат. ... Reveal Code
function getDistanceBetweenPointsNew($lat1, $long1, $lat2, $long2)
{
$theta = $long1 - $long2;
$miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet / 3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
return compact('miles','feet','yards','kilometers','meters');
}
$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
echo $unit.': '.number_format($value,4).'
';
}
//Результат вывода
//miles: 2.6025
//feet: 13,741.4350
//yards: 4,580.4783
//kilometers: 4.1884
//meters: 4,188.3894
Convert the timestamp to human-readable format like XX minutes ago or XX days ago. Was found here: http://stackoverflow.com/questions/2915864/php-how-to-find-the-time-elapsed-since-a-date-time ... Reveal Code
function humanTiming ($time)
{
$time = strtotime($time);
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';
}
}
$time = '2013-05-25 15:45:22';
echo 'Event happened '.humanTiming($time);