Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Sunday, November 24, 2019

php 7.3 compact() undefined variable

If you have used compact and upgraded php to 7.3 you maybe noticed warnings when variable is not defined.
PHP 7.3 made compact function strict and it will throw warnings.

Quick dirty solution:
Replace
compact
with

@compact

Normal solution:

Replace compact with array. It will take time, so if you are in production use quick dirty solution to supress notice, and when you have time make changes.
Here gist https://gist.github.com/AucT/55340f911259fd7a6e9a76b766985c6c  you can use it on any php online website and decompact your function calls.

Sunday, August 11, 2019

Prevent / Defend Against XSS Attack in PHP

Include funtion e. This will escape malicious js stuff.

function e($value)
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
}

Call function e to the input you need to display. For example

<input type="text" value="<?=e($_GET['q']??'')?>">

Sunday, July 22, 2018

Post to facebook page from php

Facebook has very weird documentation. If you have facebook page and want to post on page with php script here what you need:

1. Facebook page
2. Your user never ending access token. Here normal guide how to get it https://medium.com/@Jenananthan/how-to-create-non-expiry-facebook-page-token-6505c642d0b1
3. Get your pageId. Go to your page Information (or About)->In the very bottom your pageId. At the moment of the article it is here https://www.facebook.com/pg/<pageUrl>/about/. Where <pageUrl> is your facebook page slug.
4. Get facebook php sdk  https://github.com/facebook/php-graph-sdk with composer

composer require facebook/graph-sdk
Note: this command is good at the moment of this article. But you better go to github and copy, because they can change it.


Now here the script


$appId = ''; //your App Id
$appSecret = ''; //your app secret
$pageId = '0000000000'; //id of the page you want to publish on
$userAccessToken = ''; //Your never expire user access token

$fb = new \Facebook\Facebook([
    'app_id' => $appId,
    'app_secret' => $appSecret,
    'default_graph_version' => 'v3.0',
]);
$linkData = [
    'link' => 'http://google.com', //TODO  change
    'message' => "My message", //TODO  change
];


$longLivedToken = $fb->getOAuth2Client()->getLongLivedAccessToken($userAccessToken);
$fb->setDefaultAccessToken($longLivedToken);
$response = $fb->sendRequest('GET', $pageId, ['fields' => 'access_token'])
    ->getDecodedBody();

$foreverPageAccessToken = $response['access_token'];
$fb->setDefaultAccessToken($foreverPageAccessToken);
$response = $fb->post("/$pageId/feed", $linkData);
Note: If you're using github then values for first 4 variables should be outside of git. For example in env file or php file which is in gitignore.

Sunday, July 15, 2018

php get substring after character or word


Here we will get substring after word '/'
$item = 'posts/p10504';

substr(strrchr($item, '/'),1);
substr($item , strpos($item , '/') + 1);

//both lines has value of p10504

Saturday, April 8, 2017

how to create helpers file laravel5

Simple tip for simple stuff.

create folder Helpers in app directory
create file StringHelper.php in app\Helpers

<?php
namespace App\Helpers;
class StringHelper
{
public static function getCleanString($string)
{
//remove unnecessary chars
$string = str_replace(['-', ' '], '', $string);
return str_slug($string);
}
}

add any simple function in this class as static.
when you need a different helper, create new class for example YoutubeHelper.php and add there stuff you need.

usage

\App\Helpers\StringHelper::getCleanString($name)

Tuesday, March 14, 2017

PHP format tree comments, categories, nested sets

Simple function for formatting tree. One cons - you need to pass all items (all comments of the post) to format them.

<?php

function formatTree($tree, $parent)
{
    $tree2 = array();
    foreach ($tree as $item) {
        if ($item['parent_id'] == $parent) {
            $tree2[$item['id']] = $item;
            $tree2[$item['id']]['child'] = formatTree($tree, $item['id']);
        }
    }

    return $tree2;
}


//for demo
$beforeTree = [
    ['id' => 1, 'parent_id' => 0],
    ['id' => 2, 'parent_id' => 1],
    ['id' => 3, 'parent_id' => 2],
    ['id' => 4, 'parent_id' => 0],
    ['id' => 5, 'parent_id' => 4],
    ['id' => 6, 'parent_id' => 4],
];
$afterTree = formatTree($beforeTree, 0);

var_dump($afterTree);

Saturday, December 31, 2016

Laravel insert ignore check if inserted (affected rows for insert ignore)

Halo guys!
if you break your head for finding solution to check if row is inserted here is the way

$query = "INSERT INTO table (id) VALUES (?)";
    try {
        DB::insert($query, array($value));
        return 1;
    } catch (\Exception $e) {
        return 0;
    }

The solution is simle - not use insert ignore. So we are catching exception instead of fatal erroring and know if it did or not.
You can even do query builder insert instead of raw query.

Thursday, March 10, 2016

export database without phpmyadmin

Hi! sometimes you need to get database, but you haven't phpmyadmin/sqladminer nor or you just want to do it faster.
So you can do it loggining via ssh and use some mysql command or create script with

<?php
exec('mysqldump --user=MYUSERNAME --password=MYPASSWORD --host=localhost MYDATABASENAME > backup.sql');
exit('done');

and run it

Thursday, March 3, 2016

Extending multiple controllers in Code Igniter

Hi! If you are forced to use old framework like codeigniter, and want to have multiple base controllers and then extend them here a trick you can do:

1) check the value of
$config['subclass_prefix'] = 'MY_';
in application\config\config.php
By default it is MY_ ; but nvm check to make sure.
2) create php file called MY_Controller.php (or your %prefix%Controller.php inside application\core folder
3) In this file (MY_Controller.php) you can create any amount of base controllers that extends CI_Controller, and then in simple controllers extend these base controllers
<?phpif (!defined('BASEPATH')) {    exit('No direct script access allowed');}

class Admin_Controller extends CI_Controller{    }
class Public_Controller extends CI_Controller{
}