User Tools

Site Tools





curl -sS | php
php composer.phar install

list images in folders as JSON

header('Content-type: application/json');
$rootfolder = "photos/*";
$albums = [];
foreach (glob($rootfolder) as $folder) {
  $album = [];
  $album["folder"] = basename($folder);
  $album["title"] = basename($folder);
  $items = [];
  foreach (glob($folder."/*.jpg") as $filename) {
    list($width, $height, $type, $attr) = getimagesize($filename);
    $item = [];
    $item["filename"] = basename($filename);
    $item["src"] = $filename;
    $item["w"] = $width;
    $item["h"] = $height;
    $items[] = $item;
  $album["photos"] = $items;
  $albums[] = $album;
echo json_encode($albums);

json header

header('Content-type: application/json');

array_map & str_getcsv

//"07","Week 3","54.jpg"
$a = array_map('str_getcsv', file('info.txt'));


foreach (glob("fotos/$folder/*.jpg") as $filename) {
  list($width, $height, $type, $attr) = getimagesize($filename);
  $items[] = "{ src: '$filename', w:$width, h:$height }";

youmagine missing API call: get image preview for document

header("Access-Control-Allow-Origin: *");
header("Content-type: text/plain");
if (empty($_GET['id'])) die("id is undefined");
if (!is_numeric($_GET['id'])) die("id should be a valid number");
$id = $_GET["id"];
$json = json_decode(file_get_contents("$id.json"));
$documentable_id = $json->documentable_id;
$url = getDesignURLById($documentable_id);
$html = file_get_contents($url);
preg_match("/<article data-id=\"".$id."\" .+?id=\"(\d+)\"/", $html, $matches);
echo $matches[1];
function getDesignURLById($designId) {
  $url = "$designId";
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, TRUE); // We'll parse redirect url from header.
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); // We want to just get redirect url but not to fo$
  $response = curl_exec($ch);
  preg_match_all('/^Location:(.*)$/mi', $response, $matches);
  return !empty($matches[1]) ? trim($matches[1][0]) : 'No redirect found';

PHP.INI on OpenPanel


Use PHPMailer for sending email with attachment

require 'PHPMailerAutoload.php';
$bodytext = "Testing...";
$email = new PHPMailer();
$email->From      = '';
$email->FromName  = 'YOU';
$email->Subject   = 'Message Subject';
$email->Body      = $bodytext;
$file_to_attach = 'test.png';
$email->AddAttachment( $file_to_attach , 'test.png' );
return $email->Send();

Save Base64 encoded raw data from post as image

header("Access-Control-Allow-Origin: *");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'test.png';
$success = file_put_contents($file, $data);

Install GD

apt-get install php5-gd

online code testen

socket server with php

upload script

based on: permissions: 755

if ($_FILES["file"]["error"] > 0)
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"] . "<br>";
  move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
  echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

Solve the following problem om CentOS

'PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/' - /usr/lib64/php/modules/ cannot open shared object file: No such file or directory in Unknown on line 0'

edit /etc/php.d/mcrypt.ini and change



last item from array

$item = end($array);

strip illegal characters from string

$location = preg_replace('/[^(\x20-\x7F)]*/','', $location);

append or create if not exists

file_put_contents($path, $data, FILE_APPEND);

get random string

function getRandomKey($count) { 
  $chars = "abcdefghijklmopqrstuvwxyz1234567890";
  for ($a=0; $a<$count; $a++) $str.=$chars[rand(0,strlen($chars)-1)];
  return $str;
echo getRandomKey(6);

or shorter and with no duplicate characters per string:

echo substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 6);

or if you only need a hex string:

echo substr(md5(rand()), 0, 6);

get url info ie. in 404.php

$result = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $input);

auto include

function __autoload($class_name) {
    include $class_name . '.php';

extract, stripslashes & sqlite escape

if (get_magic_quotes_gpc() ) {
  $_GET = array_map('stripslashes', $_GET);
$_GET = array_map('sqlite_escape_string', $_GET);

json header

header("Content-type: application/json");


function file_get_contents_utf8($fn) {
    $content = file_get_contents($fn);
    return mb_convert_encoding($content, 'UTF-8', mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));

encoding of non utf-8 content to json

Convert PHP Object to array

$eventArray = (array)$event;


als je last van rare tekens hebt (zoals ë wordt ë) dan staat misschien de encoding van je pagina verkeerd.

header("Content-Type: text/plain; charset=utf-8"); //iso-8859-1

Bij het inserten van UTF-8 tekst in een MySQL datebase dien je eerst een utf8decode te gebruiken zoals het er nu naar uitziet.
<code php>
$event→description = utf8

Als de tijd niet goed staat in PHP staat misschien je timezone verkeerd

setlocale(LC_ALL, "nl_NL");

ssl disabled?

if ssl seems to be disabled in php just enable it like this in your php.ini:


short open tags

connect to mysql through console/command line PHP but without Apache

if you get this error:

PHP Warning:  mysql_connect(): [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) 

try to connect to instead of localhost


twitter uitlezen met PHP? zie Twitter

php versie opvragen

php -v

if else endif

<?php if( condition ): ?>
<?php else: ?>
<?php endif; ?>


Ik moet me nog steeds eens verdiepen in PEAR:

while / list / each

while (list($k, $v) = each($_GET)) {
  echo $k . '=' . $v . ', ';

mysql transactions in php

foreach($userIds as $id) {
  $this->db->update("INSERT INTO ......");

Internal Server Error 500 door PHP in Apache

Als Apache error 500 geeft kan dat liggen aan een fout in de syntax van een PHP script. Door het aanzetten van displayerrors in php.ini of door het gebruiken van de iniset functie in php kun je de exacte foutmelding achterhalen.

ini_set('display_errors', 'On');

Als dat niet helpt kun je ook je php.ini aanpassen. In mijn geval stond die hier (het pad kun je opvragen mbv phpinfo():

of hier (op OpenPanel):

php error log


import_request_variables icm sqlite vs extract

Problemen met quotes in sqlite zelfs na SQLite3::escapeString of sqliteescapestring?

import_request_variables("g","_"); //kijkt niet naar $_GET dus negeert magic quotes.

ik gebruik nu ipv daarvan extract (ik weet niet of dat veilig genoeg is maar het werkt wel):

if (get_magic_quotes_gpc() ) {
  $_GET = array_map('stripslashes', $_GET);
$_GET = array_map('sqlite_escape_string', $_GET);

Content-type voor json

header("Content-type: application/json");


require 'scraperwiki/simple_html_dom.php';
$html_content = scraperwiki::scrape("");
$html = str_get_html($html_content);
foreach ($html->find("div.category") as $categories) {
    foreach ($categories->find("div.repo") as $addons) {
        //if ($ttl++>20) exit();
        $link = $addons->find("a.github_link");
        $link = $link[0]->href;
        $name = explode("/",$link);
        $name = $name[count($name)-1];
        $author = explode("/",$link);
        $author = $author[3];
        $category = $categories->find("h2 a");
        $category = $category[0]->plaintext;
        //print $category . " - " . $name . " - " . $author . " - " . $link . "\n";
        $records[] = array("link"=>$link, "name"=>$name, "author"=>$author, "category"=>$category);
print "saving...\n";
$unique_keys = array("link");
$table_name = "repos";
scraperwiki::save_sqlite($unique_keys, $records, $table_name);
print "done\n";

mini api

header("Content-type: text/plain");
if (isset($pinguin)) {
  $html = file_get_contents("");
  $parts = explode("Nu op</strong> <I>", $html);
  $parts = explode("</I>",$parts[1]);
  $artist = $parts[0];
  $parts = explode("</h2>", substr($parts[1],3));
  $title = $parts[0];
if (isset($time)) {
  die(date('Y-m-d h:i:s'));
php.txt · Last modified: 2015/07/14 12:45 by rick