how can i get the current_link id? - laravel-5

I am using laravel 5.2.I want to get the id of current_link.Please help me to find the id of current_link.
public function checkUrl(){
$current_link = $_SERVER['REQUEST_URI'];
$current_link=ltrim($current_link, '/');
$current_link=ltrim($current_link, 'cable');
$current_link=ltrim($current_link, '/');
$plink = DB::table('roles')->where('id',$current_link->id)->get();
// print_r($plink);
// die();
$dlink= DB::table('my_roles')->where('role_id',$current_link->role_id)->get();
if($plink!=$dlink){
Session::flash('flash_notification', array('level' => 'success', 'message' => 'Error!! You dont have the permission to access this page'));
return Redirect::action('Admin\DashboardController#index');
}
}

Related

Users Controller does not exist

I'm building a CMS in Laravel 5.8 with an in-built Authentication system. My app was working fine but suddenly it starts giving me an error as ReflectionException : Class App\Http\Controllers\Users does not exist on command php artisan route:list -v. However, if i define a new resource route, then that new route page works fine. It means, route file is getting saved but gives error while listing the routes.
I have not created any file named as Users but my user controller file name is UserController
Below is the structure of my application:
cms -> project folder
app
Http
Controllers
Auth
RegisterController.php
LoginController.php and other Auth files
backend
UserController.php and my other controller files
Below is my route file
Auth::routes();
Route::group(['as'=>'cms.' ,'prefix'=>'cms'],function(){
Route::get('/', 'backend\Dashboard#index')->name('dashboard');
Route::resource('/user-management', 'backend\UserController');
});
Below is my UserController file residing in backend folder
<?php
namespace App\Http\Controllers\backend;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Auth;
use App\Models\backend\Admin;
use App\Models\backend\Menu;
use App\Models\backend\Submenu;
use Config;
use illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function AuthRouteAPI(Request $request)
{
return $request->user();
}
public function index()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
$cms_users = Admin::withTrashed()->get();
return view('backend.pages.users.index', ['arrUserMenu'=>$arrUserMenu, 'cms_users'=>$cms_users]);
}
public function create()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.create', ['arrUserMenu'=>$arrUserMenu]);
}
public function store(Request $request)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|unique:cms_users,email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrname' => 'required|min:'.Config::get('cms_const.USER_ID_MIN_LEN').'|max:'.Config::get('cms_const.USER_ID_MAX_LEN').'|regex:/(^[A-Za-z0-9._]+$)+/|unique:cms_users,username',
'usrpwd' => 'required|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.unique' => 'Email already exist',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrname.required' => 'Please enter the user name',
'usrname.min' => 'User name should not be less then '.Config::get('cms_const.USER_ID_MIN_LEN').' characters',
'usrname.max' => 'User name should not be more then '.Config::get('cms_const.USER_ID_MAX_LEN').' characters',
'usrname.regex' => 'Only Alphabets, Numbers, Dot and Underscore allowed in user name',
'usrname.unique' => 'User name already exist',
'usrpwd.required' => 'Please enter the password',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
Admin::create([
'name' => $request->name,
'username' => $request->usrname,
'password' => bcrypt($request->usrpwd),
'email' => $request->usrmail,
]);
return redirect()->route('cms.user-management.index')->with('success','New user account created successfully.');
}
public function edit($id)
{
if(!$id)
{
return redirect()->route('cms.user-management.index');
die;
}
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.edit', ['arrUserMenu'=>$arrUserMenu, 'arrRecord'=>$arrRecord]);
}
public function update(Request $request, $id)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrpwd' => 'nullable|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
$arrRecord->name = $request->input('name');
$arrRecord->email = $request->input('usrmail');
if($request->input('usrpwd'))
{
$arrRecord->password = bcrypt($request->input('usrpwd'));
}
$arrRecord->save();
return redirect()->route('cms.user-management.index')->with('success','User account details updated successfully.');
}
public function destroy($id)
{
try
{
$user = Admin::findOrFail($id);
$user->delete();
return response()->json(['success'=>'Record successfully deleted', 'status'=>'Suspended']);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
return response()->json(['error'=>'Record you are trying to delete does not exist']);
}
}
}
I have tried the below commands and they all run successfully but none resolved the error
php artisan clear-compiled
composer dump-autoload
php artisan optimize
php artisan route:cache
Don't know from where this Users controller class in being referenced.
Can anyone help me in this regard as I'm badly stuck in my development.
Much Regards,
Javed
#ClémentBaconnier the error is resolved now. I made the changes in api.php to Route::middleware('auth:api')->get('/user', 'backend\Users#AuthRouteAPI'); and now all my routes are listed. Thanks u soooo much for ur advice.

How fix Facebook login error in codeigniter

Facebook SDK returned an error:
Cross-site request forgery validation failed. The "state" param from the URL and session do not match.
I use fblogin() and fbcallback() in same controller. But face this error. Also do all steps in developer.facebook.com. Session is also started. But error says, do not match.
public function fblogin(){
$this->load->library('session');
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID', // Replace {app-id} with your app id
'app_secret' => '{APP_SECRET}',
'default_graph_version' => 'v2.5',//v2.5
]);
$helper = $fb->getRedirectLoginHelper();
// if (isset($_GET['state'])) {
// $helper->getPersistentDataHandler()->set('state', $_GET['state']);
// }
// $sURL = $helper->getLoginUrl(FACEBOOK_AUTH_CALLBACK, FACEBOOK_PERMISSIONS);
$permissions = ['email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('https://www.collegeprintsusa.com/maintenance/signin/fbcallback', $permissions);
// echo 'Log in with Facebook!';
header("location: ".$loginUrl);
}
public function fbcallback() {
$this->load->view('../libraries/facebook-php-sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.5',//v2.5
]);
// $serializedFacebookApp = serialize($fb);
// $unserializedFacebookApp = unserialize($serializedFacebookApp);
// echo $unserializedFacebookApp->getAccessToken();
$helper = $fb->getRedirectLoginHelper(); //'https://www.collegeprintsusa.com/maintenance/signin/fblogin'
// $_SESSION['FBRLH_state'] = $_REQUEST['state'];
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$fbClient = $fb->getClient();
$accessToken = $helper->getAccessToken($fbClient);
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: collegeprintsusa.com');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email', $accessToken);
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
// echo $fbid.','.$fbfullname; die();
# save the user nformation in session variable
$get_user_email = $this->user_model->get_single_user(['email' => $fbemail]);
if($get_user_email){
$res_user_fbid_update = $this->user_model->update_users(['id' => $get_user_email['id']],['facebook_id' => $fbid]);
if($res_user_fbid_update){
$this->session->set_userdata(['username' => $get_user_email['usename'],
'name' => $get_user_email['name'],
'last' => $get_user_email['last_name'],
'email' => $get_user_email['email'],
'type' => $get_user_email['user_type'],
'uid' => $get_user_email['id'],
'phone' => $get_user_email['phone'],
'address' => $get_user_email['address'],
'profile_image' => $get_user_email['profile_image'],
'disable' => $get_user_email['sms_update']]);
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}else{
$res_user_reg = $this->user_model->add_users([
'name' => $fbfullname,
'email' => $fbemail,
'phone' => 0,
'user_type' => 'customer',
'username' => $fbemail,
'password' => SALT . sha1($fbemail),
'token' => SALT . sha1($fbemail),
'facebook_id' => $fbid
]);
if($res_user_reg){
$this->output->set_output(json_encode(['result' => 1]));
return FALSE;
}else{
$this->output->set_output(json_encode(['result' => 2]));
return FALSE;
}
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: index.php");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://phpstack-21306-56790-161818.cloudwaysapps.com', $permissions);
echo 'Log in with Facebook!';
}
}
Here I would like to suggest a better solution to log in with Facebook. Please use JavaScript instead of PHP, because PHP will redirect on facebook page & JavaScript will not redirect, It will open facebook login popup on own website, and it`s very quick & easy process according to performance.
Please follow below code to login with facebook using JavaScript.
$(document).ready(function($) {
window.fbAsyncInit = function() {
FB.init({
appId : '186770818730407', // Set YOUR APP ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fbLogin()
{
FB.login(function(response) {
if (response.authResponse) {
getFBUserInfo();
}else {
showToaster('error','User cancelled login or did not fully authorize.');
return false;
}
},{scope: 'email,user_photos,user_videos'});
}
function getFBUserInfo() {
FB.api('/me',{fields: "id,picture,email,first_name,gender,middle_name,name"}, function(response) {
$.ajax({
url : "http://example.com/welcome/facebook_login",
type : "POST",
data : {response:response},
dataType : "JSON",
beforeSend:function(){
ajaxindicatorstart();
},
success: function(resp){
ajaxindicatorstop();
if(resp.type == "success"){
fbLogout();
showToaster('success',resp.msg);
setTimeout(function(){
window.location.href = base_url() + 'account-setting';
},1000);
}
else{
showToaster('error',resp.msg);
}
},
error:function(error)
{
ajaxindicatorstop();
}
});
});
}
function fbLogout()
{
FB.logout(function(){ console.log('facebook logout') });
}
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
});
Hope You will like it.
Thanks

Get last insert_id in the URL in codeigniter

i have one requirement from in my application..so when ever user insert details in the requirement.and then submit..the mail will go to the particular vendor with one link..when vendor click on the link i redirect the page to login page..
So what i want to do is i want to send email link with last inserted id..
Here is my controller:
public function requirement()
{
$data["msg"]="";
$this->load->model('RequirementModel');
$data['user']=$this->RequirementModel->getusers();
$data['rolename']=$this->RequirementModel->getrolename();
if($this->input->post())
{
$this->RequirementModel->add_requirement($this->input->post());
$all_users = $this->input->post('user_id');
foreach($all_users as $key)
{
$get_email = $this->RequirementModel->get_user_email_by_id($key);
$req_id = $this->input->post('req_id');
$role_name = $this->input->post('role_name');
$vacancies = $this->input->post('vacancies');
$experience = $this->input->post('experience');
$jd = $this->input->post('jd');
$hiring_contact_name = $this->input->post('hiring_contact_name');
$hiring_contact_number = $this->input->post('hiring_contact_number');
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://md-in-42.webhostbox.net',
'smtp_port' => 465,
'smtp_user' => 'test3#clozloop.com',
'smtp_pass' => 'test3'
);
$this->load->library('email',$config);
$this->email->set_mailtype("html");
$this->email->from('test3#clozloop.com', 'bharathi');
$this->email->to($get_email);
$this->email->subject('this is our requirements pls go through it');
$link = 'Click on this link - <a href="http://localhost/job_portal/index.php/Login/signin>Click Here</a>';
$this->email->message($link);
print_r($get_email);
if($this->email->send())
{
echo "email sent";
}
else
{
echo "email failed";
}
}
}
$this->load->view('Requirements/requirements',$data);
}
Can anyone help me..
Thanks in advance..
What you need is the database helper function insert_id(), it returns the id of the last insert: https://www.codeigniter.com/userguide3/database/helpers.html?highlight=insert_id
Have your add_requirement function of the RequirementModel model return the insert_id like so:
return $this->db->insert_id();
Then just save that value when you call the function:
$insert_id = $this->RequirementModel->add_requirement($this->input->post());

How I do do get session in model? CakePHP 3.x

Cakephp 3.x
I want to do my captcha custom validation. But I can not access a session.
$validator->notEmpty('securityCode', __('not empty message'))
->add('securityCode','custom',
['rule' => function ($value, $context) use ($extra) {
if($this->request->Session()->read('captcha') != $value) {
return false;
}
return true;
}, 'message' => 'error security code']);
return $validator;
or can I my custom validation function give custom parameter?
public function validationLogin(Validator $validator, $customParameter)
{ //bla bla }
I use: http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules
You can pass Session data as parameter of validation function like this
// In Controller
$sessionData = $this->request->Session()->read('captcha');
$validator = $this->{YourModel}->validationLogin(new Validator(), $sessionData);
$errors = $validator->errors($this->request->data());
if (!empty($errors)) {
// Captcha validation failed
}
// In Model
public function validationLogin(Validator $validator, $sessionData)
{
$validator
->notEmpty('securityCode', __('not empty message'))
->add('securityCode', 'custom', [
'rule' => function ($value, $context) use ($sessionData) {
if ($sessionData != $value){
return false;
}
return true;
},
'message' => 'error securty code'
]);
return $validator;
}
Edit: you can access session from model, but it is not a good practise and you better avoid it. Instead rather pass it from controller as in example above
// In model
use Cake\Network\Session;
$session = new Session();
$sessionData = $session->read('captcha');
For CakePHP 3: at the top of your Model class add
use Cake\Network\Session;
and at the point where you want to have to access the session add
$this->session = new Session();
$messages = $this->session->read('captcha'); // Example for the default flash messages
To set a flash message in the model use
$this->session = new Session();
$messages = $this->session->read('Flash.flash');
$messages[] = ['message' => 'YOUR FLASH MESSAGE', 'key' => 'flash', 'element' => 'Flash/default', 'params' => []];
$this->session->write('Flash.flash', $messages);

HybridAuth send tweet with image

I'm using the HybridAuth library.
I'd like to be able to post message to my authenticated users twitter profile with images.
The setUserStatus method works well to automatically send a tweet.
I wrote the following method :
function setUserStatus( $status, $image )
{
//$parameters = array( 'status' => $status, 'media[]' => "#{$image}" );
$parameters = array( 'status' => $status, 'media[]' => file_get_contents($image) );
$response = $this->api->post( 'statuses/update_with_media.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
The message I get from twitter is :
Ooophs, we got an error: Update user status failed! Twitter returned an error. 403 Forbidden: The request is understood, but it has been refused.
How Can I get more precise info about error ?
Does anybody allready success in sending a picture attached to a tweet ?
Thanks !
Hugo
Thanks #Heena for making myself wake up on this question, I MADE IT ;)
function setUserStatus( $status )
{
if(is_array($status))
{
$message = $status["message"];
$image_path = $status["image_path"];
}
else
{
$message = $status;
$image_path = null;
}
$media_id = null;
# https://dev.twitter.com/rest/reference/get/help/configuration
$twitter_photo_size_limit = 3145728;
if($image_path!==null)
{
if(file_exists($image_path))
{
if(filesize($image_path) < $twitter_photo_size_limit)
{
# Backup base_url
$original_base_url = $this->api->api_base_url;
# Need to change base_url for uploading media
$this->api->api_base_url = "https://upload.twitter.com/1.1/";
# Call Twitter API media/upload.json
$parameters = array('media' => base64_encode(file_get_contents($image_path)) );
$response = $this->api->post( 'media/upload.json', $parameters );
error_log("Twitter upload response : ".print_r($response, true));
# Restore base_url
$this->api->api_base_url = $original_base_url;
# Retrieve media_id from response
if(isset($response->media_id))
{
$media_id = $response->media_id;
error_log("Twitter media_id : ".$media_id);
}
}
else
{
error_log("Twitter does not accept files larger than ".$twitter_photo_size_limit.". Check ".$image_path);
}
}
else
{
error_log("Can't send file ".$image_path." to Twitter cause does not exist ... ");
}
}
if($media_id!==null)
{
$parameters = array( 'status' => $message, 'media_ids' => $media_id );
}
else
{
$parameters = array( 'status' => $message);
}
$response = $this->api->post( 'statuses/update.json', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 ){
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
To make it work you have to do like this :
$config = "/path_to_hybridauth_config.php";
$hybridauth = new Hybrid_Auth( $config );
$adapter = $hybridauth->authenticate( "Twitter" );
$twitter_status = array(
"message" => "Hi there! this is just a random update to test some stuff",
"image_path" => "/path_to_your_image.jpg"
);
$res = $adapter->setUserStatus( $twitter_status );
Enjoy !
I did not understand it for hybridauth then I used this library
https://github.com/J7mbo/twitter-api-php/archive/master.zip
Then I was successful using code below: (appears elsewhere in stack)
<?php
require_once('TwitterAPIExchange.php');
$settings= array(
'oauth_access_token' => '';
'oauth_access_secret' => '';
'consumer_key' => '';
'consumer_secret' => '';
// paste your keys above properly
)
$url_media = "https://api.twitter.com/1.1/statuses/update_with_media.json";
$requestMethod = "POST";
$tweetmsg = $_POST['post_description']; //POST data from upload form
$twimg = $_FILES['pictureFile']['tmp_name']; // POST data of file upload
$postfields = array(
'status' => $tweetmsg,
'media[]' => '#' . $twimg
);
try {
$twitter = new TwitterAPIExchange($settings);
$twitter->buildOauth($url_media, $requestMethod)
->setPostfields($postfields)
->performRequest();
echo "You just tweeted with an image";
} catch (Exception $ex) {
echo $ex->getMessage();
}
?>

Resources