Tuesday 2 July 2019

Laravel cheat sheet



 Laravel Cheat Sheet

Artisan
php artisan --help OR -h
php artisan --quiet OR -q
php artisan --version OR -V
php artisan --no-interaction OR -n
php artisan --ansi
php artisan --no-ansi
php artisan --env
// -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
php artisan --verbose


php artisan changes
php artisan clear-compiled
php artisan downgrade
php artisan dump-autoload
php artisan env
php artisan help
php artisan list
php artisan migrate
php artisan optimize
php artisan routes
php artisan serve
php artisan tinker
php artisan up
php artisan workbench


php artisan asset:publish [--bench[="vendor/package"]] [--path[="..."]] [package]
php artisan auth:reminders
php artisan cache:clear
php artisan command:make name [--command[="..."]] [--path[="..."]] [--namespace[="..."]]
php artisan config:publish
php artisan controller:make [--bench="vendor/package"]
php artisan db:seed [--class[="..."]] [--database[="..."]]
php artisan key:generate
php artisan migrate [--bench="vendor/package"] [--database[="..."]] [--path[="..."]] [--package[="..."]] [--pretend] [--seed]
php artisan migrate:install [--database[="..."]]
php artisan migrate:make name [--bench="vendor/package"] [--create] [--package[="..."]] [--path[="..."]] [--table[="..."]]
php artisan migrate:refresh [--database[="..."]] [--seed]
php artisan migrate:reset [--database[="..."]] [--pretend]
php artisan migrate:rollback [--database[="..."]] [--pretend]
php artisan queue:listen [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--timeout[="..."]] [connection]
php artisan queue:subscribe [--type[="..."]] queue url
php artisan queue:work [--queue[="..."]] [--delay[="..."]] [--memory[="..."]] [--sleep] [connection]
php artisan session:table
php artisan view:publish [--path[="..."]] package


php artisan generate:model 
php artisan generate:controller
php artisan generate:view
php artisan generate:seed
php artisan generate:migration
php artisan generate:resource (Generate a model, Generate index, show, create, and edit views, Generate a controller, Generate a migration with schema, Generate a table seeder, Migrate the database)


Composer
composer create-project laravel/laravel folder_name
composer install
composer update
composer dump-autoload [--optimize]
composer self-update


Routing
Route::get('foo', function(){});
Route::get('foo', 'ControllerName@function');
Route::controller('foo', 'FooController');


Triggering Errors
App::abort(404);
App::missing(function($exception){});
throw new NotFoundHttpException;


Route Parameters
Route::get('foo/{bar}', function($bar){});
Route::get('foo/{bar?}', function($bar = 'bar'){});


HTTP Verbs
Route::any ('foo', function(){});
Route::post('foo', function(){});
Route::put('foo', function(){});
Route::patch('foo', function(){});
Route::delete('foo', function(){});
// RESTful actions
Route::resource('foo', 'FooController');


Secure Routes
Route::get('foo', array('https', function(){}));


Route Constraints
Route::get('foo/{bar}', function($bar){})
->where('bar', '[0-9]+');
Route::get('foo/{bar}/{baz}', function($bar, $baz){})
->where(array('bar' => '[0-9]+', 'baz' => '[A-Za-z]'))


Filters
// Declare an auth filter
Route::filter('auth', function(){});
// Register a class as a filter
Route::filter('foo', 'FooFilter');
// Routes in this group are guarded by the 'auth' filter
Route::get('foo', array('before' => 'auth', function(){}));
Route::group(array('before' => 'auth'), function(){});
// Pattern filter
Route::when('foo/*', 'foo');
// HTTP verb pattern
Route::when('foo/*', 'foo', array('post'));


Named Routes
Route::currentRouteName();
Route::get('foo/bar', array('as' => 'foobar', function(){}));


Route Prefixing
// This route group will carry the prefix 'foo'
Route::group(array('prefix' => 'foo'), function(){})


Sub-Domain Routing
// {sub} will be passed to the closure
Route::group(array('domain' => '{sub}.example.com'), function(){});


URLs
URL::full();
URL::current();
URL::previous();
URL::to('foo/bar', $parameters, $secure);
URL::action('FooController@method', $parameters, $absolute);
URL::route('foo', $parameters, $absolute);
URL::secure('foo/bar', $parameters);
URL::asset('css/foo.css', $secure);
URL::secureAsset('css/foo.css');
URL::isValidUrl('http://example.com');
URL::getRequest();
URL::setRequest($request);
URL::getGenerator();
URL::setGenerator($generator);


Events
Event::fire('foo.bar', array($bar));
Event::listen('foo.bar', function($bar){});
Event::listen('foo.*', function($bar){});
Event::listen('foo.bar', 'FooHandler', 10);
Event::listen('foo.bar', 'BarHandler', 5);
Event::listen('foor.bar', function($event){ return false; });
Event::queue('foo', array($bar));
Event::flusher('foo', function($bar){});
Event::flush('foo');
Event::subscribe(new FooEventHandler);


DB
$results = DB::select('select * from users where id = ?', array('value'));
DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
DB::update('update users set votes = 100 where name = ?', array('John'));
DB::delete('delete from users');
DB::statement('drop table users');
DB::listen(function($sql, $bindings, $time){ code_here() });
DB::transaction(function(){ code_here() });



Eloquent
Model::create(array('key' => 'value'));
Model::destroy(1);
Model::all();
Model::find(1);
// Trigger an exception
Model::findOrFail(1);
Model::where('foo', '=', 'bar')->get();
Model::where('foo', '=', 'bar')->first();
// Exception
Model::where('foo', '=', 'bar')->firstOrFail();
Model::where('foo', '=', 'bar')->count();
Model::where('foo', '=', 'bar')->delete();
Model::whereRaw('foo = bar and cars = 2', array(20))->get();
Model::on('connection-name')->find(1);
Model::with('relation')->get();
Model::all()->take(10);
Model::all()->skip(10);


Soft Delete
Model::withTrashed()->where('cars', 2)->get();
Model::withTrashed()->where('cars', 2)->restore();
Model::where('cars', 2)->forceDelete();
Model::onlyTrashed()->where('cars', 2)->get();


Events
Model::creating(function($model){});
Model::created(function($model){});
Model::updating(function($model){});
Model::updated(function($model){});
Model::saving(function($model){});
Model::saved(function($model){});
Model::deleting(function($model){});
Model::deleted(function($model){});
Model::observe(new FooObserver);


Mail
Mail::send('email.view', $data, function($message){});
Mail::send(array('html.view', 'text.view'), $data, $callback);
Mail::queue('email.view', $data, function($message){});
Mail::queueOn('queue-name', 'email.view', $data, $callback);
Mail::later(5, 'email.view', $data, function($message){});
// Write all email to logs instead of sending
Mail::pretend();


Queues
Queue::push('SendMail', array('message' => $message));
Queue::push('SendEmail@send', array('message' => $message));
Queue::push(function($job) use $id {});
php artisan queue:listen
php artisan queue:listen connection
php artisan queue:listen --timeout=60
php artisan queue:work
Localization
App::setLocale('en');
Lang::get('messages.welcome');
Lang::get('messages.welcome', array('foo' => 'Bar'));
Lang::has('messages.welcome');
Lang::choice('messages.apples', 10);


Files
File::exists('path');
File::get('path');
File::getRemote('path');
File::getRequire('path');
File::requireOnce('path');
File::put('path', 'contents');
File::append('path', 'data');
File::delete('path');
File::move('path', 'target');
File::copy('path', 'target');
File::extension('path');
File::type('path');
File::size('path');
File::lastModified('path');
File::isDirectory('directory');
File::isWritable('path');
File::isFile('file');
// Find path names matching a given pattern.
File::glob($patterns, $flag);
// Get an array of all files in a directory.
File::files('directory');
// Get all of the files from the given directory (recursive).
File::allFiles('directory');
// Get all of the directories within a given directory.
File::directories('directory');
File::makeDirectory('path', $mode = 0777, $recursive = false);
File::copyDirectory('directory', 'destination', $options = null);
File::deleteDirectory('directory', $preserve = false);
File::cleanDirectory('directory');


Input
Input::get('key');
// Default if the key is missing
Input::get('key', 'default');
Input::has('key');
Input::all();
// Only retrieve 'foo' and 'bar' when getting input
Input::only('foo', 'bar');
// Disregard 'foo' when getting input
Input::except('foo');




Session Input (flash)
// Flash input to the session
Input::flash();
Input::flashOnly('foo', 'bar');
Input::flashExcept('foo', 'baz');
Input::old('key','default_value');


Files
// Use a file that's been uploaded
Input::file('filename');
// Determine if a file was uploaded
Input::hasFile('filename');
// Access file properties
Input::file('name')->getRealPath();
Input::file('name')->getClientOriginalName();
Input::file('name')->getSize();
Input::file('name')->getMimeType();
// Move an uploaded file
Input::file('name')->move($destinationPath);
// Move an uploaded file
Input::file('name')->move($destinationPath, $fileName);


Cache
Cache::put('key', 'value', $minutes);
Cache::add('key', 'value', $minutes);
Cache::forever('key', 'value');
Cache::remember('key', $minutes, function(){ return 'value' });
Cache::rememberForever('key', function(){ return 'value' });
Cache::forget('key');
Cache::has('key');
Cache::get('key');
Cache::get('key', 'default');
Cache::get('key', function(){ return 'default'; });
Cache::increment('key');
Cache::increment('key', $amount);
Cache::decrement('key');
Cache::decrement('key', $amount);
Cache::section('group')->put('key', $value);
Cache::section('group')->get('key');
Cache::section('group')->flush();


Cookies
Cookie::get('key');
// Create a cookie that lasts for ever
Cookie::forever('key', 'value');
// Send a cookie with a response
$response = Response::make('Hello World');
$response->withCookie(Cookie::make('name', 'value', $minutes));

Sessions
Session::get('key');
Session::get('key', 'default');
Session::get('key', function(){ return 'default'; });
Session::put('key', 'value');
Session::all();
Session::has('key');
Session::forget('key');
Session::flush();
Session::regenerate();
Session::flash('key', 'value');
Session::reflash();
Session::keep(array('key1', 'key2'));


Requests
Request::path();
Request::is('foo/*');
Request::url();
Request::segment(1);
Request::header('Content-Type');
Request::server('PATH_INFO');
Request::ajax();
Request::secure();


Responses
return Response::make($contents);
return Response::make($contents, 200);
return Response::json(array('key' => 'value'));
return Response::json(array('key' => 'value'))
->setCallback(Input::get('callback'));
return Response::download($filepath);
return Response::download($filepath, $filename, $headers);
// Create a response and modify a header value
$response = Response::make($contents, 200);
$response->header('Content-Type', 'application/json');
return $response;
// Attach a cookie to a response
return Response::make($content)
->withCookie(Cookie::make('key', 'value'));


Redirects
return Redirect::to('foo/bar');
return Redirect::to('foo/bar')->with('key', 'value');
return Redirect::to('foo/bar')->withInput(Input::get());
return Redirect::to('foo/bar')->withInput(Input::except('password'));
return Redirect::to('foo/bar')->withErrors($validator);
return Redirect::back();
return Redirect::route('foobar');
return Redirect::route('foobar', array('value'));
return Redirect::route('foobar', array('key' => 'value'));
return Redirect::action('FooController@index');
return Redirect::action('FooController@baz', array('value'));
return Redirect::action('FooController@baz', array('key' => 'value'));
// If intended redirect is not defined, defaults to foo/bar.
return Redirect::intended('foo/bar');
IoC
App::bind('foo', function($app){ return new Foo; });
App::make('foo');
// If this class exists, it's returned
App::make('FooBar');
App::singleton('foo', function(){ return new Foo; });
App::instance('foo', new Foo);
App::bind('FooRepositoryInterface', 'BarRepository');
App::register('FooServiceProvider');
// Listen for object resolution
App::resolving(function($object){});


Security
Passwords
Hash::make('secretpassword');
Hash::check('secretpassword', $hashedPassword);
Hash::needsRehash($hashedPassword);


Auth
// Check if the user is logged in
Auth::check();
Auth::user();
Auth::attempt(array('email' => $email, 'password' => $password));
// Remember user login
Auth::attempt($credentials, true);
// Log in for a single request
Auth::once($credentials);
Auth::login(User::find(1));
Auth::loginUsingId(1);
Auth::logout();
Auth::validate($credentials);
Auth::basic('username');
Auth::onceBasic();
Password::remind($credentials, function($message, $user){});


Encryption
Crypt::encrypt('secretstring');
Crypt::decrypt($encryptedString);
Crypt::setMode('ctr');
Crypt::setCipher($cipher);


Validation
Validator::make(
array('key' => 'Foo'),
array('key' => 'required|in:Foo')
);
Validator::extend('foo', function($attribute, $value, $params){});
Validator::extend('foo', 'FooValidator@validate');
Validator::resolver(function($translator, $data, $rules, $msgs)
{
return new FooValidator($translator, $data, $rules, $msgs);
});


Validation Rules
accepted
active_url
after:YYYY-MM-DD
before:YYYY-MM-DD
alpha
alpha_dash
alpha_num
between:1,10
confirmed
date
date_format:YYYY-MM-DD
different:fieldname
email
exists:table,column
image
in:foo,bar,baz
not_in:foo,bar,baz
integer
numeric
ip
max:value
min:value
mimes:jpeg,png
regex:[0-9]
required
required_if:field,value
required_with:foo,bar,baz
required_without:foo,bar,baz
same:field
size:value
unique:table,column,except,idColumn
url


Views
View::make('path/to/view');
View::make('foo/bar')->with('key', 'value');
View::make('foo/bar', array('key' => 'value'));
View::exists('foo/bar');
// Share a value across all views
View::share('key', 'value');
// Nesting views
View::make('foo/bar')->nest('name', 'foo/baz', $data);
// Register a view composer
View::composer('viewname', function($view){});
//Register multiple views to a composer
View::composer(array('view1', 'view2'), function($view){});
// Register a composer class
View::composer('viewname', 'FooComposer');
View::creator('viewname', function($view){});

Blade Templates
@extends('layout.name')
@section('name') // Begin a section
@stop // End a section
@show // End a section and then show it
@yield('name') // Show a section name in a template
@include('view.name')
@include('view.name', array('key' => 'value'));
@lang('messages.name')
@choice('messages.name', 1);
@if
@else
@elseif
@endif
@unless
@endunless
@for
@endfor
@foreach
@endforeach
@while
@endwhile
{{ $var }} // Echo content
{{{ $var }}} // Echo escaped content
{{-- Blade Comment --}}


Forms
Form::open(array('url' => 'foo/bar', 'method' => 'PUT'));
Form::open(array('route' => 'foo.bar'));
Form::open(array('route' => array('foo.bar', $parameter)));
Form::open(array('action' => 'FooController@method'));
Form::open(array('action' => array('FooController@method', $parameter)));
Form::open(array('url' => 'foo/bar', 'files' => true));
Form::token();
Form::model($foo, array('route' => array('foo.bar', $foo->bar)));
Form::close;


Form Elements
Form::label('id', 'Description');
Form::label('id', 'Description', array('class' => 'foo'));
Form::text('name');
Form::text('name', $value);
Form::textarea('name');
Form::textarea('name', $value);
Form::textarea('name', $value, array('class' => 'name'));
Form::hidden('foo', $value);
Form::password('password');
Form::email('name', $value, array());
Form::file('name', array());
Form::checkbox('name', 'value');
Form::radio('name', 'value');
Form::select('name', array('key' => 'value'));
Form::select('name', array('key' => 'value'), 'key');
Form::submit('Submit!');
Form::input(‘type’, ‘name’, ‘value’) // type can be number… 
Form Macros
Form::macro('fooField', function()
{ return ''; });
Form::fooField();


HTML Builder
HTML::macro('name', function(){});
HTML::entities($value);
HTML::decode($value);
HTML::script($url, $attributes);
HTML::style($url, $attributes);
HTML::link($url, 'title', $attributes, $secure);
HTML::secureLink($url, 'title', $attributes);
HTML::linkAsset($url, 'title', $attributes, $secure);
HTML::linkSecureAsset($url, 'title', $attributes);
HTML::linkRoute($name, 'title', $parameters, $attributes);
HTML::linkAction($action, 'title', $parameters, $attributes);
HTML::mailto($email, 'title', $attributes);
HTML::email($email);
HTML::ol($list, $attributes);
HTML::ul($list, $attributes);
HTML::listing($type, $list, $attributes);
HTML::listingElement($key, $type, $value);
HTML::nestedListing($key, $type, $value);
HTML::attributes($attributes);
HTML::attributeElement($key, $value);
HTML::obfuscate($value);


Strings
// Transliterate a UTF-8 value to ASCII
Str::ascii($value)
Str::camel($value)
Str::contains($haystack, $needle)
Str::endsWith($haystack, $needles)
// Cap a string with a single instance of a given value.
Str::finish($value, $cap)
Str::is($pattern, $value)
Str::length($value)
Str::limit($value, $limit = 100, $end = '...')
Str::lower($value)
Str::words($value, $words = 100, $end = '...')
Str::plural($value, $count = 2)
// Generate a more truly "random" alpha-numeric string.
Str::random($length = 16)
// Generate a "random" alpha-numeric string.
Str::quickRandom($length = 16)
Str::upper($value)
Str::title($value)
Str::singular($value)
Str::slug($title, $separator = '-')
Str::snake($value, $delimiter = '_')
Str::startsWith($haystack, $needles)
// Convert a value to studly caps case.
Str::studly($value)
Str::macro($name, $macro)


Helpers
Arrays
array_add($array, 'key', 'value');
array_build($array, function(){});
array_divide($array);
array_dot($array);
array_except($array, array('key'));
array_fetch($array, 'key');
array_first($array, function($key, $value){}, $default);
// Strips keys from the array
array_flatten($array);
array_forget($array, 'foo');
// Dot notation
array_forget($array, 'foo.bar');
array_get($array, 'foo', 'default');
array_get($array, 'foo.bar', 'default');
array_only($array, array('key'));
// Return array of key => values
array_pluck($array, 'key');
// Return and remove 'key' from array
array_pull($array, 'key');
array_set($array, 'key', 'value');
// Dot notation
array_set($array, 'key.subkey', 'value');
array_sort($array, function(){});
// First element of an array
head($array);
// Last element of an array
last($array);


Paths
app_path();
public_path();
// App root path
base_path();
storage_path();


Strings
camel_case($value);
class_basename($class);
// Escape a string
e('');
starts_with('Foo bar.', 'Foo');
ends_with('Foo bar.', 'bar.');
snake_case('fooBar');
str_contains('Hello foo bar.', 'foo');
// Result: foo/bar/
str_finish('foo/bar', '/');
str_is('foo*', 'foobar');
str_plural('car');
str_random(25);
str_singular('cars');
// Result: FooBar
studly_case('foo_bar');
trans('foo.bar');
trans_choice('foo.bar', $count);

URLs and Links
action('FooController@method', $parameters);
link_to('foo/bar', $title, $attributes, $secure);
link_to_asset('img/foo.jpg', $title, $attributes, $secure);
link_to_route('route.name', $title, $parameters, $attributes);
link_to_action('FooController@method', $title, $params, $attrs);
// HTML Link
asset('img/photo.jpg', $title, $attributes);
// HTTPS link
secure_asset('img/photo.jpg', $title, $attributes);
secure_url('path', $parameters);
route($route, $parameters, $absolute = true);
url('path', $parameters = array(), $secure = null);


Miscellaneous
csrf_token();
dd($value);
value(function(){ return 'bar'; });
with(new Foo)->chainedMethod();




Sunday 28 April 2019

Read specific row in CSV to using php

<?php

/* This is example for skip particular line from csv */

/*
forexample you have 500 line in your csv but you want read from 125 line then you have
set  $csv->seek(124);

This example used for skip csv file row for read.
This example also used for create new csv after skip csv

*/

$csv_file = 'test.csv';


// try {
//     $csv  = new SplFileObject($csv_file, 'r');
//     $csv->seek(25);
// } catch (RuntimeException $e ) {
//     printf("Error openning csv: %s\n", $e->getMessage());
// }

$fileName ="new_csv.csv";

$dfp = fopen($fileName,'wb');
chmod($fileName,0777);

$csv  = new SplFileObject($csv_file, 'r');
$csv->seek(20);
$lineSkip= 0;
while(!$csv->eof() && ($col = $csv->fgetcsv()) && $col[0] !== null) {
    // $row is a numelrical keyed array  with
    // a string per each field (zero based).
    echo "<pre>";
    print_r($col);
    $lineSkip++;
    fputcsv($dfp,$col);
}
echo $lineSkip;
fclose($dfp);
?>

Wednesday 27 December 2017

link preview like facebook using php

link preview like facebook using php



Hello here example with text area 

<?php

$string =  "adasd asdad asdasd https://www.facebook.com asdasd asdasdsa ";

$preview_data = array();
$preview_data['title'] = "";
$preview_data['desc'] = "";
$preview_data['url'] = "";
$preview_data['image'] = "";

$myurl = "";
if($string!=''){
$string_array = explode(" ",$string);
if(count($string_array) > 0){
foreach($string_array as $string_value){
if (filter_var($string_value, FILTER_VALIDATE_URL)) {
$myurl = $string_value;
break;
} // if of url
if($string_value!=''){
$sub_string_check = explode(".",$string_value);
if(count($sub_string_check) >= 2){
$myurl = "http://" .$string_value;
break;
}
}
} // foreach for loop
 
} // if for array count
}// main if condition


if (filter_var($myurl, FILTER_VALIDATE_URL)) {
$agent = "'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';";
$ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_URL, $myurl);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    
    $data = curl_exec($ch);
    curl_close($ch);
$dom = new DOMDocument();
@$dom->loadHTML($data);
//$page = new self();
    
    // Parse DOM to get Title
    $nodes = $dom->getElementsByTagName('title');
    $title = $nodes->item(0)->nodeValue;
    
    // Parse DOM to get Meta Description
    $metas = $dom->getElementsByTagName('meta');
    $body = "";
    for ($i = 0; $i < $metas->length; $i++) {
        $meta = $metas->item($i);
$name = $meta->getAttribute('property');
$name123 = $meta->getAttribute('name');
        //if ($meta->getAttribute('name') == 'description') {
             $body[$name] = $meta->getAttribute('content');
$body[$name123] = $meta->getAttribute('content');
        //}
    }
    
    // Parse DOM to get Images
    $image_urls = array();
$image_src = array();
    $images = $dom->getElementsByTagName('img');
     
     for ($i = 0; $i < $images->length; $i ++) {
         $image = $images->item($i);
         $src = $image->getAttribute('src');
         
         if(filter_var($src, FILTER_VALIDATE_URL)) {
             $image_src[] = $src;
         }
     }
    
    $output = array(
        'title' => $title,
        'image_src' => $image_src,
        'body' => $body
    );
echo "<pre>";
print_r($output);
$title = "";
$description ="";
$url = "";
$image_url = "";
if(isset($output['title'])){
$title = $output['title'];
}elseif(isset($output['body']['og:title'])){
$title = $output['body']['og:title'];
}elseif(isset($output['body']['twitter:title'])){
$title = $output['body']['twitter:title'];
}
if(isset($output['body']['description'])){
$description = $output['body']['description'];
}elseif(isset($output['body']['og:description'])){
$description = $output['body']['og:description'];
}elseif(isset($output['body']['twitter:description'])){
$description = $output['body']['twitter:description'];
}
if(isset($output['body']['url'])){
$url = $output['url'];
}elseif(isset($output['body']['og:url'])){
$url = $output['body']['og:url'];
}elseif(isset($output['body']['twitter:url'])){
$url = $output['body']['twitter:url'];
}elseif(isset($output['body']['al:web:url'])){
$url = $output['body']['al:web:url'];
}else{
$url =$myurl;
}
if(isset($output['body']['image'])){
$image_url = $output['image'];
}elseif(isset($output['body']['og:image'])){
$image_url = $output['body']['og:image'];
}elseif(isset($output['body']['twitter:image'])){
$image_url = $output['body']['twitter:image'];
}elseif(isset($output['image_src'][0])){
$image_url = $output['image_src'][0];
}
$preview_data['title'] = $title;
$preview_data['desc'] = $description;
$preview_data['url'] = $url;
if($image_url!=""){
$preview_data['image'] = filter_var($image_url, FILTER_VALIDATE_URL)?$image_url:$url.$image_url;
}
 
 
/*if(!filter_var($image_url, FILTER_VALIDATE_URL)) {
             
foreach($output['body'] as $t){
$preview_data['image'] = $url.$t;
}
 
         }*/
}
echo "<pre>";
print_r($preview_data);

?>

Friday 17 November 2017

Converting Timestamp to time ago in PHP e.g 1 day ago, 1 year ago

Converting Timestamp to time ago in PHP e.g 1 day ago, 1 year ago

 

Hello Here Example of set up time as human readable formate in php

<?php
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
echo date('Y-m-d H:i:s');
echo "<br/>";
echo time_elapsed_string('2017-11-17 11:36:00',true);
echo "<br/>";
echo time_elapsed_string('@1367367755'); # timestamp input
echo "<br/>";
echo time_elapsed_string('2013-05-01 00:22:35', true);
echo "<br/>";
?>



Wednesday 1 November 2017

only number or letter input in textbox using jquery example

only number or letter input in textbox using jquery example

you can set using this id and class name 

this example for if you want to input onlu number or letter other you can not enter this 

Please check this example
<script type="application/javascript">
$("input[name=number]").keydown(function (e) {

        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });


// only letter input using jquery

$("input[name=letter]").on("keydown", function(event){
  // Allow controls such as backspace, tab etc.
  var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];

  // Allow letters
  for(var i = 65; i <= 90; i++){
    arr.push(i);
  }

  // Prevent default if not in array
  if(jQuery.inArray(event.which, arr) === -1){
    event.preventDefault();
  }
});

</script>

<input type="text" name="number" placeholder="only number input" />
<input type="text" name="letter" placeholder="only letter input" />

Thursday 26 October 2017

PHP multidimensional array search by value and get array value

PHP multidimensional array search by value and get array value 

Hell here exmple of array search in multidinsional
see the array you can get array key of multidensional and get value using array

check this out put

Array
(
    [0] => Array
        (
            [typeid] => 1
            [typename] => Enveloppe
            [max_kg] => 0.30
            [isactive] => 1
            [isdelete] => 0
        )

    [1] => Array
        (
            [typeid] => 2
            [typename] => Documents
            [max_kg] => 2.00
            [isactive] => 1
            [isdelete] => 0
        )

    [2] => Array
        (
            [typeid] => 3
            [typename] => Colis
            [max_kg] => 300.00
            [isactive] => 1
            [isdelete] => 0
        )

)
 
$new_type_id = array_combine(array_keys($get_row_msttype), array_column($get_row_msttype, 'typename'));
      $search_typeid = array_search('Enveloppe', $new_type_id);
      
      if(is_int($search_typeid)){
       $typeid =  $get_row_msttype[$search_typeid]['typeid']; // you can get value using array value here
      }else{
       $typeid = '';
      }
      
      echo $typeid; 

Tuesday 24 October 2017

Google Translate using javascript english to french without select value from dropdown on page load



Google Translate using javascript english to french without select value from dropdown on page load

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>

<style>
#google_translate_element{width:300px;float:right;text-align:right;display:block}
.goog-te-banner-frame.skiptranslate { display: none !important;}
body { top: 0px !important; }
#goog-gt-tt{display: none !important; top: 0px !important; }
.goog-tooltip skiptranslate{display: none !important; top: 0px !important; }
.activity-root { display: hide !important;}
.status-message { display: hide !important;}
.started-activity-container { display: hide !important;}
#google_translate_element{ display: none !important;}
</style>
<div id="google_translate_element"></div>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

<script type="text/javascript">
  function googleTranslateElementInit() {
    new google.translate.TranslateElement({ 
    
  includedLanguages: 'fr',
      layout: google.translate.TranslateElement.InlineLayout.SIMPLE
    }, 'google_translate_element');

var lang = 'French';
var $frame = $('.goog-te-menu-frame:first');
console.log($frame.contents().find('.goog-te-menu2-item span.text:contains('+lang+')').click());

  }
</script>








Why do we use it?

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Saturday 16 September 2017

Create parking using jquery ui draggable and droppable

Create parking using jquery ui draggable and droppable

Create parking using jquery ui draggable and droppable


<!doctype html>
<html lang="en">
<head>
<title>Society Parking</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="parking.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>

<script type="application/javascript">
$( init );

function init() {



// Ajax Loader
$(document).bind("ajaxStart.mine", function() {

$('.se-pre-con').css("display","block");
});

$(document).bind("ajaxStop.mine", function() {

$('.se-pre-con').css("display","none");
});
// End Ajax Loader

// User draggable event
$(".ui-draggable").draggable({ cursor: "crosshair", revert: "invalid"});



// User droppable event
$("#cardSlots div").droppable({ accept: ".ui-draggable",
           drop: function(event, ui) {
var dropped = ui.draggable;
var droppedOn = $(this);
          

    if($( this ).hasClass('over')==false){
$(".ui-draggable").draggable({ cursor: "crosshair", revert: "invalid"}); // drop element can drag it
$(this).addClass("over"); // drop box add over class

// this code remove prvious element (last drop element data)
if($(ui.draggable).attr('previousid')!=undefined){

var previousid  = "#"+$(ui.draggable).attr('previousid');

$(previousid).removeClass("over");
 
var member = $(ui.draggable).attr('data-userid');
var flat = $(ui.draggable).attr('data-flat');
var hidden_blockid = $(ui.draggable).attr('data-block');
var hidden_parkind =  $(previousid).attr('data-parkid');
var left_p = $(ui.draggable).css('left');
var top_p = $(ui.draggable).css('top');
//alert(top_p);
var flag = "1";




/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,flag:flag},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}
});*/
 
}
// Ends


// this for delete previous element data
var ids =  $(this).attr('id'); // get id
$(ui.draggable).attr('previousid',ids); // set id

     ui.draggable.position( { of: $(this), my: 'left top', at: 'left top' } ); 

  // this code insert current parking element

var member = $(ui.draggable).attr('data-userid');
  var flat = $(ui.draggable).attr('data-flat');
  var hidden_blockid = $(ui.draggable).attr('data-block');
  var hidden_parkind =  $(this).attr('data-parkid');
  var left_p = $(ui.draggable).css('left');
   var top_p = $(ui.draggable).css('top');
var park_drop = ids;
  
/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,park_drop:park_drop},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}

});*/
//ends




}else{

$(".ui-draggable").draggable({ cursor: "crosshair", revert: true});

$("#cardPile").droppable({ accept: ".ui-draggable", drop: function(event, ui) {
console.log("drop");

var dropped = ui.draggable;
var droppedOn = $(this);
//$(dropped).detach().css("position","relative").appendTo(droppedOn);     
$(dropped).removeAttr('style');
$(dropped).css("position","relative");
var imageUrl = $(dropped).attr('data-image');
$(dropped).css('background-image', 'url(' + imageUrl + ')');
$(dropped).css(' background-repeat', 'no-repeat');
$(dropped).css('background-size', '55px 86px');
var left_posion =  $(this).attr('data-left_pos');
   var top_posion =  $(this).attr('data-top_pos');
  
   if(left_posion!=''&&top_posion!=''){
    $(this).css('left', left_posion);
$(this).css('top', top_posion);
  }
 
 
if($(ui.draggable).attr('previousid')!=undefined){

var previousid  = "#"+$(ui.draggable).attr('previousid');

$(previousid).removeClass("over");

var member = $(ui.draggable).attr('data-userid');
var flat = $(ui.draggable).attr('data-flat');
var hidden_blockid = $(ui.draggable).attr('data-block');
var hidden_parkind =  $(previousid).attr('data-parkid');
var left_p = $(ui.draggable).css('left');
var top_p = $(ui.draggable).css('top');
//alert(top_p);
var flag = "1";




/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,flag:flag},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}
});*/

}


},


});

}
           
            
                },
over: function(event, ui) {},

                  out: function(event, ui) {}
                     });

// this code after set data in parking the goto prvious position (set for user display list)
$("#cardPile").droppable({ accept: ".ui-draggable", drop: function(event, ui) {
console.log('drop sucess');

var dropped = ui.draggable;
var droppedOn = $(this);

$(dropped).removeAttr('style');

$(dropped).css("position","relative");

var imageUrl = $(dropped).attr('data-image');
$(dropped).css('background-image', 'url(' + imageUrl + ')');
$(dropped).css(' background-repeat', 'no-repeat');
$(dropped).css('background-size', '55px 86px');

if($(ui.draggable).attr('previousid')!=undefined){

var previousid  = "#"+$(ui.draggable).attr('previousid');

$(previousid).removeClass("over");

var member = $(ui.draggable).attr('data-userid');
var flat = $(ui.draggable).attr('data-flat');
var hidden_blockid = $(ui.draggable).attr('data-block');
var hidden_parkind =  $(previousid).attr('data-parkid');
var left_p = $(ui.draggable).css('left');
var top_p = $(ui.draggable).css('top');
//alert(top_p);
var flag = "1";




/*$.ajax({
url:"",
type:"POST",
data:{member:member,flat:flat,hidden_blockid:hidden_blockid,hidden_parkind:hidden_parkind,left_p:left_p,top_p,top_p,flag:flag},
success: function(res){
var t = $.parseJSON(res);
//alert(t['message']);

}
});*/

}

$(ui.draggable).removeAttr('previousid');



}


});

// set background image to all userlist box
$(".profileimg").each(function(index, element) {
var imageUrl =   $(this).attr('data-image');
$(this).css('background-image', 'url(' + imageUrl + ')');
$(this).css(' background-repeat', 'no-repeat');
$(this).css('background-size', '55px 86px');

var left_posion =  $(this).attr('data-left_pos');
var top_posion =  $(this).attr('data-top_pos');

if(left_posion!=''&&top_posion!=''){
$(this).css('left', left_posion);
$(this).css('top', top_posion);
}
            });



}
</script>
<div id="loader" class="se-pre-con"></div>
<div id="wrapper">


       


  <div id="cardPile">
        <div  data-left_pos="" data-top_pos="" data-userid="11" data-flat="1" data-block="1" id="card11" data-image="thumb_59b7e0eeb0b6125-dsc-4806-copy-1490189640.jpg" class="ui-draggable profileimg"> </div>
        <div previousid=droppable24 data-left_pos="192px" data-top_pos="236px" data-userid="17" data-flat="1" data-block="1" id="card17" data-image="thumb_59b7e135e97524331AD0C00000578-4784672-image-m-2_1502551607375.jpg" class="ui-draggable profileimg"> </div>
        <div previousid=droppable23 data-left_pos="56px" data-top_pos="236px" data-userid="18" data-flat="1" data-block="1" id="card18" data-image="thumb_59b7e0175dc18Salman-Khan_55.jpg" class="ui-draggable profileimg"> </div>
      </div>
  <div id="cardSlots" style="width:910px;">
        <div  class="ui-droppable cardSlots " id="droppable6" data-parkid="6"   >a1011</div>
        <div  class="ui-droppable cardSlots " id="droppable7" data-parkid="7"   >a101</div>
        <div  class="ui-droppable cardSlots " id="droppable8" data-parkid="8"   >708</div>
        <div  class="ui-droppable cardSlots " id="droppable10" data-parkid="10"   >701</div>
        <div  class="ui-droppable cardSlots " id="droppable11" data-parkid="11"   >702</div>
        <div  class="ui-droppable cardSlots " id="droppable12" data-parkid="12"   >703</div>
        <div  class="ui-droppable cardSlots " id="droppable13" data-parkid="13"   >704</div>
        <div  class="ui-droppable cardSlots " id="droppable14" data-parkid="14"   >705</div>
        <div  class="ui-droppable cardSlots " id="droppable15" data-parkid="15"   >706</div>
        <div  class="ui-droppable cardSlots " id="droppable16" data-parkid="16"   >7014</div>
        <div  class="ui-droppable cardSlots " id="droppable17" data-parkid="17"   >707</div>
        <div  class="ui-droppable cardSlots " id="droppable18" data-parkid="18"   >709</div>
        <div  class="ui-droppable cardSlots " id="droppable19" data-parkid="19"   >7011</div>
        <div  class="ui-droppable cardSlots " id="droppable20" data-parkid="20"   >7012</div>
        <div  class="ui-droppable cardSlots " id="droppable21" data-parkid="21"   >501</div>
        <div  class="ui-droppable cardSlots " id="droppable22" data-parkid="22"   >503</div>
        <div  class="ui-droppable cardSlots over" id="droppable23" data-parkid="23"   >504</div>
        <div  class="ui-droppable cardSlots over" id="droppable24" data-parkid="24"   >505</div>
        <div  class="ui-droppable cardSlots " id="droppable25" data-parkid="25"   >506</div>
        <div  class="ui-droppable cardSlots " id="droppable26" data-parkid="26"   >507</div>
        <div  class="ui-droppable cardSlots " id="droppable27" data-parkid="27"   >508</div>
        <div  class="ui-droppable cardSlots " id="droppable28" data-parkid="28"   >509</div>
        <div  class="ui-droppable cardSlots " id="droppable29" data-parkid="29"   >5010</div>
        <div  class="ui-droppable cardSlots " id="droppable30" data-parkid="30"   >101</div>
        <div  class="ui-droppable cardSlots " id="droppable31" data-parkid="31"   >102</div>
        <div  class="ui-droppable cardSlots " id="droppable32" data-parkid="32"   >103</div>
        <div  class="ui-droppable cardSlots " id="droppable33" data-parkid="33"   >104</div>
        <div  class="ui-droppable cardSlots " id="droppable34" data-parkid="34"   >105</div>
        <div  class="ui-droppable cardSlots " id="droppable35" data-parkid="35"   >107</div>
        <div  class="ui-droppable cardSlots " id="droppable36" data-parkid="36"   >108</div>
        <div  class="ui-droppable cardSlots " id="droppable37" data-parkid="37"   >109</div>
        <div  class="ui-droppable cardSlots " id="droppable38" data-parkid="38"   >110</div>
        <div  class="ui-droppable cardSlots " id="droppable39" data-parkid="39"   >111</div>
        <div  class="ui-droppable cardSlots " id="droppable40" data-parkid="40"   >113</div>
        <div  class="ui-droppable cardSlots " id="droppable41" data-parkid="41"   >114</div>
        <div  class="ui-droppable cardSlots " id="droppable42" data-parkid="42"   >301</div>
        <div  class="ui-droppable cardSlots " id="droppable43" data-parkid="43"   >222</div>
      
  </div>
  <!--<div id="drop" class="fbox">
  
</div>-->
</div>

Monday 21 August 2017

Get wordpress post using webservice

Get wordpress post using webservice


Get wordpress post using webservice, wordpress, wordpress websevice, get post using webservice, 



<?php

require_once '../wp-load.php';
require_once '../wp-config.php';
header('Content-type: application/json');

$response = array();
$count = 0;

$args = array(
        'post_type' => 'owl-carousel',
'posts_per_page' => -1,
        'orderby' => get_option('owl_carousel_orderby', 'post_date'),
        'order' => 'asc',
        'tax_query' => array(
            array(
                'taxonomy' => 'Carousel',
                'field' => 'slug',
                'terms' => 'home'
            )
        ),
        'nopaging' => true
    );

$my_query = null;
$my_query = new WP_Query($args);

if( $my_query->have_posts() )
{
$response['message'] = 'Banner list';
$response['status'] = 1;

while ($my_query->have_posts()) : $my_query->the_post();
   
$response['data'][$count]['id'] = get_the_ID();
$response['data'][$count]['title'] = html_entity_decode(get_the_title());
$response['data'][$count]['imageurl'] = wp_get_attachment_url( get_post_thumbnail_id($my_query->ID));
$count++;

endwhile;
}
else
{
$response['message'] = 'No banner exists.';
$response['status'] = 2;
}

echo json_encode($response);

?>

Insert webservice with post type with metabox value in wordpress

Insert webservice with post type with metabox value in wordpress

Insert webservice with post type with metabox value in wordpress, wordpress, wordpress webserivce, insert webserice in wordpress, 

<?php

require_once '../wp-load.php';
require_once '../wp-config.php';
header('Content-type: application/json');

$response = array();


$alu_name=    sanitize_meta('name_alu_c1',$_POST['metal_name'],'user');
$alu_email=    sanitize_email($_POST['metal_email']);
$alu_mobile=    sanitize_meta('phone_alu_c1',$_POST['metal_mobile'],'user');
$alu_city=    sanitize_meta('city_alu_c1',$_POST['metal_city'],'user');
$alu_message=    sanitize_meta('message_alu_c1',$_POST['metal_message'],'user');





$my_cptpost_args = array(
          
            'post_title' => $alu_name,
            'post_status'   => 'publish',
            'post_type' => "enter-your-post-type-name",
);

$admin_email = "admin@gmail.com";
$headers[] = 'From: <test@gmail.com>';
$second_email = "test@gmail.com";

$cpt_id = wp_insert_post($my_cptpost_args, $wp_error );
if($cpt_id){

$response['message'] = 'Thank you! We will get back to you soon.';
$response['status'] = 1;
add_post_meta($cpt_id, 'name_alu_c1', $alu_name, true);//here insert two custom field data.
add_post_meta($cpt_id, 'email_address_alu_c1', $alu_email, true);//here insert two custom field data.
add_post_meta($cpt_id, 'phone_alu_c1', $alu_mobile, true);//here insert two custom field data.
add_post_meta($cpt_id, 'city_alu_c1', $alu_city, true); //here insert two custom field data..
add_post_meta($cpt_id, 'message_alu_c1', $alu_message, true); //here insert two custom field data..

$email_temp = "Name : ".$alu_name."<br/>";
$email_temp .= "Email : ".$alu_email."<br/>";
$email_temp .= "Phone : ".$alu_mobile."<br/>";
$email_temp .= "City : ".$alu_city."<br/>";
$email_temp .= "Message : ".$alu_message."<br/>";

$inqury = " Inquiry for ".$alu_name;

$test = wp_mail( $alu_email, "Contact Us", "Thank you! We will get back to you soon.",$headers);
$test = wp_mail($admin_email, $inqury, $email_temp );
if($second_email !=''){
$test = wp_mail($second_email, $inqury, $email_temp );
}


}else{

$response['message'] = 'Some Error';
$response['status'] = 2;

}


echo json_encode($response);

?>