Categories
Apache mod-rewrite and htaccess related Articles PHP

How to increase php upload_max_filesize with htaccess?

In PHP the default value of upload_max_filesize is 2MB and the default value for post_max_size is 8MB on the server but you can increase or decrease this size limit by modifying your php.ini or . htaccess file using post_max_size and upload_max_filesize .
You can manually adjust the post data size and file size using these directives in your php.ini. See a list of supported directives you can use in php.ini .
Also see How to increase upload_max_filesize in PHP an article on tecmint.com.

  • post_max_size directive represents the maximum data size your form can submit to server using the POST method.

    The following line in php.ini will set the maximum post size to 500mb which means that your form can submit data upto 500mb in one request.
    post_max_size = "500M"

  • upload_max_filesize represents the maximum filesize your form can submit to server. For example if this is set as the following in your php.ini :

    upload_max_filesize = "250M"

    Then you can upload a file that is upto 250MB in size to server . This won’t allow you to upload files that are greater then 250MB as it’s the maximum size limit set in the directive.

You can easily increase the file upload limit on php by modifying your ini file but not all hosting service providers allow you to do that. If you can not modify your php.ini then the another easy option is to edit it via the htaccess file.

Increase php maximum upload filesize by htaccess

Since htaccess is available on all types of hosting providers, you can easily edit your htaccess file to update the PHP filesize limit.
Add the following two lines to your htaccess . You can change the size according to your needs

php_value post_max_size 100M
php_value upload_max_filesize 100M

This will set the maximum size to 100MB for both . You can change the size as per your requirements.

I hope this article was helpful. Thanks for reading it!

Categories
PHP

Managing MySQL database with PHP using single Object-oriented interface

This article explains how you can access and manipulate MySQL database using MySQLi Object-oriented interface in PHP.
This article covers the following MySQL statements with code examples. The code examples are pasted in the textarea so you can easily copy then edit as per your requirements.

  • CREATE TABLE
  • RENAME TABLE
  • INSERT INTO
  • SELECT

We will use PHP and Mysqli object oriented extension in this tutorial to perform different types of tasks to retrieve , create and
update records on a MySQL database.

Note :-
The codes used here are just for educational purposes and to teach you how to implement a db connection for read and right access. You can copy and paste these codes on your server for testing and learning.

Setting up a secure connection to MySQL database

To connect to MySQL database with our code examples, you must have the following things ready :

  • Your MySQL host name
  • Your MySQL username
  • Your MySQL database password
  • Database name

You will get these informations on your hosting Cpanel. Create a new database and copy the db informations from there.

For testing and learning purposes, create a new directory in your document root and name it as db_project .
Remember that the db_project directory is for learning purposes only and it must be reachable by visiting yoursite.com/db_project/foobar .

Now inside that directory , create a new file named
connection.php with the contents shown below.

connection.php

<?php
//Setting up a secure connection to database
$db_host="localhost";
$db_user="foobar";
$db_pass="123456";
$db_name="my_db";

$conn = new mysqli($db_host,$db_user,$db_pass,$db_name);

// Check the connection
if ($conn -> connect_errno) {
  echo "Could not connect to MySQL: " . $mysqli -> connect_error;
  exit();
}
else {echo "Connected to MySQL database!";}
?>

The connection.php sets up a secure connection with your MySQL database so that you can access the database . You can use this single file to execute multiple Mysqli queries on different pages by including this file.

Add your server informations in this file and test it on your server. If everything is ok you will get a text output “Connected” on your page.

Okay cool, now that you have successfully established the connection with your MySQL server , it’s time to create a table. See the next step below to create a table .

Creating a table on MySQL database

A table on MySQL database can hold multiple columns and rows. In this article , we are going to create a table named MyUsers with 5 unique columns :

  1. ID
  2. username
  3. password
  4. email
  5. reg_date

We will use this table to store user informations.
Create a new file named create_table.php in your db_project directory with the following contents :

create_table.php

<?php

//include the connection file
include "connection.php";


// sql code to create table
//Creating table MyGursts with 5 fields
//----------------------
// ID
//Username
//Password
//Email
//reg_date

$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
//if the query is successful
if ($conn->query($sql) === TRUE) {
  echo "Table MyGuests created successfully";
}
//If something goes wrong

 else {
  echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

The code above creates 5 column in the “MyUsers” table.
The ID column is AUTO_INCREMENT which means that the rows of this column will get incremented by +1 each time a new record is added.
username , password and email has varchar data types with the maximum allowed text and finally the reg_date column is a current time which means the row value of this column will get updated automatically with server date time.

Edit this file if you need to change anything or add more columns and run it on your server . This will create a new table in your MySQL database.

Renaming MySQL table

If you created a new table on MySQL and you want
to change the table name , you can use MySQL RENAME
statement to change the table name.

The code below changes table name from MyUsers to MyNewUsers .

You will only need to use this code if you are not happy with the existing table name and you
want to change it something else.
For learning and testing purpose , create a new file named rename_table.php and put the following contents in that file :



<?php

//include the connection file
include "connection.php";


// sql code to rename table
$sql = "RENAME TABLE MyUsers TO MyNewUsers";
//if the query is successful
if ($conn->query($sql) === TRUE) {
  echo "Table MyUsers renamed successfully";
}
//If something goes wrong

 else {
  echo "Error renaming table: " . $conn->error;
}

$conn->close();
?>

The syntex to change or rename database table is simple and easier to understand.
RENAME TABLE OldName TO NewName
Where OldName is name of your existing table and NewName is the name you want to replace your old table name with.

Adding records to MySQL database with PHP

To add a record to MYSQL db we use the INSERT INTO statement. With this statement we can add a record (row) to db.

add-record.php

<?php
// Include the connection file
include "connection.php";

//Add records to database now
//Adding new records to 3 columns
$user_name="Neha";
$pass="123456";
$email="[email protected]";

$sql = "INSERT INTO MyUsers (username, password, email)
VALUES ('$user_name', '$pass', '$email')";
//If the query is successful
if ($conn->query($sql) === TRUE) {
  echo "New record added successfully";
//If something goes wrong
} else {
  echo "Error: " . $sql . "
" . $conn->error; } $conn->close(); ?>

Select data from MySQL database

To select data from the “MyUsers” table we will use the following code.

Create a new file named select.php in your MySQL test directory and put the following file contents in that file.

select.php

<?php
// Include the db connection file
include "connection.php";

//Select specific columns from MyUsers table
$sql = "SELECT id, username, password, email, reg_date FROM MyUsers";
$result = $conn->query($sql);
// If result rows are more then 0
if ($result->num_rows > 0) {
  // output data of each row in html table

   echo "<table>";
   echo "<tr>";
   echo "<th>ID</th><th>Username</th>
   <th>Password</th>
<th>Email</th>
<th>Registered on</th>
    </tr>";
  while($row = $result->fetch_assoc()) {


    echo "<tr>";
echo '<td>'.$row["id"];
echo '<td>'.$row["username"];
echo '<td>'.$row["password"];
echo '<td>'.$row["email"];
echo '<td>'.$row["reg_date"];
echo "</tr>";

  }
echo "";
} 
// Else print an error
else {
  echo "No results found";
}
$conn->close();
?>

The code above will select all the specific columns from the database.
We have requested to select all the columns from the table. If you just need to get a single column ,ie : username you can then modify the select statement like so :

$sql = "SELECT username FROM MyUsers";

This will now return all the rows for a specific column.

Display database records on a webpage

There are many ways to display MySQL records on a webpage. You can either show the data in tabular format using html table or use any block level elements to show the record. The following is a basic example of showing MySQL records on an HTML webpage. It shows the retrieved data in HTML table element.

<!DOCTYPE html>
<html>
<head>
<title>My db records</title>
</head>
<body>
<!--php code that retrieves records from database-->
<?php
// Include the db connection file
include "connection.php";

//Select specific columns from MyUsers table
$sql = "SELECT id, username, password, email, reg_date FROM MyUsers";
$result = $conn->query($sql);
// If result rows are more then 0
if ($result->num_rows > 0) {
  // output data of each row in html table

   echo "<table>";
   echo "<tr>";
   echo "<th>ID</th><th>Username</th>
   <th>Password</th>
<th>Email</th>
<th>Registered on</th>
    </tr>";
  while($row = $result->fetch_assoc()) {


    echo "<tr>";
echo '<td>'.$row["id"];
echo '<td>'.$row["username"];
echo '<td>'.$row["password"];
echo '<td>'.$row["email"];
echo '<td>'.$row["reg_date"];
echo "</tr>";

  }
echo "";
} 
// Else print an error
else {
  echo "No results found";
}
$conn->close();
?>
</body>
</html>

Categories
PHP Twitter API

How to unfollow twitter users using Twitter php API

Unfollow twitter users using Twitter PHP API

In this short tutorial I will show you how we can unfollow Twitter users using Twitter PHP API .
We are using the latest Twitter php auth in this tutorial.

What you need to get started?

To unfollow Twitter users from a website , you must have the following things ready :

  • A PHP web server (PHP 5.4 or above) .
  • Custom domain with SSL
  • Live Twitter API app
  • Twitter PHP oauth code

The first thing you need to get started with Twitter unfollow is the Twitter login. You need to log Twitter users to your website.
You can read here how to implement Twitter login for PHP and post tweet direct from a website.

See Sign in with Twitter Demo

Follow these simple steps to implement Twitter login on your php website:

  • Create an application on developer.twitter.com/en/apps
  • Copy the API key and API secret for your Twitter developer app because you will need it for your Twitter login code.
  • Download the Twitter auth PHP source code from this link and upload/unzip it on your web directory.
  • Modify the index.php file.

The only one file you need to modify in order to be able to log Twitter users to your website is index.php .

Find this file in your twitter login project directory and update API key, API secret and Callback URL fields with your app.

Here is the block of code from the index.php that needs to be updated :

define('CONSUMER_KEY', 'add_your_key_here');
define('CONSUMER_SECRET', 'add_your_app_secret_here');
define('OAUTH_CALLBACK', 'https://example.com/demo/twitter/login/callback.php');

Update these three lines and your site will be ready to log Twitter users.

Unfollow twitter users from website using API

Now that you have successfully implemented Twitter Login for your website. The next step is to create a code that can unfollow twitter users from a logged in twitter account.

You can use POST friendships/destroy method provided by Twitter API to unfollow twitter users using their screen_name or user_id .

For example (using screen name) :

$connection->post('friendships/destroy',array('screen_name' =>'twitter'));

Or using “user id of the user to unfollow”

$connection->post('friendships/destroy',array('user_id' =>'123456'));

To unfollow Twitter users using the twitter source code provided by us, create a new file named unfollow.php in the same directory as your index.php and put the following code :

session_start();

require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY','your key');
define('CONSUMER_SECRET', 'your_app_secret');
define('OAUTH_CALLBACK', 'https://example.com/demo/twitter/login/callback.php');
if (!isset($_SESSION['access_token'])) {
header("Location:index.php");}
else
{

$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get("account/verify_credentials", ['include_email' => 'true']);
// $user1 = $connection->get("https://api.twitter.com/1.1/account/verify_credentials.json", ['include_email' => true]);

//$connection->post('statuses/update', array('status' =>$tweet));
$connection->post('friendships/destroy',array('screen_name' =>'twitter'));

echo "User unfollowed";

}

This code will unfollow an specified account Twitter from the following list of your twitter account. You must be logged in to Twitter from your developer app otherwise the code will redirect you back to index.php for sign in with Twitter .

I hope this article was helpful. Thanks for reading!

Related : Sign in with Twitter for PHP with demo +code

Categories
Twitter Twitter API

Post tweet using Twitter PHP API | Live demo with zip code archive

Post Tweet using Twitter API

Do you want to post tweets from your website to your Twitter account?
If yes, then read on!
This post is for you.

In this post I will show you how to post a tweet using Twitter API for PHP. We will use a live demo here to explain the process in detail.
If you want to see the live demo first , then Visit this URL and log in with your Twitter account to see how it works.

What you need to get started?

Before we get started, here are a few requirements that you must meet in order to implement Tweeting from your php website

  • A live web server with PHP 5.4 or above
  • Domain with https certificate
  • Twitter API app.
  • Twitter Auth for PHP

1) Your webserver must have installed PHP version 5.4 or above.

2) Your domain must be SSL enabled.
All API calls from your website to twitter server must be using a secure URL scheme.
If you don’t have an SSL certificate , you can buy one or get a free SSL certificate for your domain from Cloudflare .

3) Create an application on developer.twitter.com for your project.
You will need this application to log twitter users to your website.

To be able to create your first app the twitter developer platform, first you will need to apply for a developer account. Create your developer account on Twitter and send it for review. Once its reviewed you can then create your first app.
3) Download twitter oauth on your server. You need twitter oauth to integrate twitter on your PHP website. You can download the popular twitter Auth library from Here .

What’s next?

We will first implement the Twitter login so that we can log Twitter users to our website.

Download the zip source code from This link and upload it to your web directory.
You can use any Online ftp ediors to upload and unzip the zip archive on your server.

After unzipping the source code file, you need to modify only one single file index.php .
Open the file in your editor and change App key , App secret and callback URL with your values.

You will find API key andsecret on the dashboard of your Twitterper application.
The callback URL is the URL of your site where Twitter users will come after successful authorization on Twitter. You need to add this URL to the settings of your app . If you don’t know the exact location of this URL, just find where the callback.php is located in your Twitter login code.

To verify everything is working perfectly fine, just vist the index.php project file in your browser. This will now ask you to login with your Twitter.

Congratulations : you have successfully implemented Log in with Twitter for your php website. Now we have finished our first step. The next step is to Post a tweet from website .

Post tweet using Twitter PHP API

To post a tweet using Twitter API , we use POST statuses/update method provided by Twitter.
To be able to send tweet using Twitter PHP API, you just need to create a new file in the same directory where your Twitter login source code is located.

Create a new file named post_tweet.php and put the following php code in that file :

session_start();

require 'autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
define('CONSUMER_KEY', 'Your_consumer_key');
define('CONSUMER_SECRET', 'your_consumer_secret');
define('OAUTH_CALLBACK', 'https://example.com/demo/twitter/login/callback.php');
if (!isset($_SESSION['access_token'])) {
header("Location:index.php");}
else
{

$tweet=$_POST["mytweet"];
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$user = $connection->get("account/verify_credentials", ['include_email' => 'true']);
// $user1 = $connection->get("https://api.twitter.com/1.1/account/verify_credentials.json", ['include_email' => true]);

$connection->post('statuses/update', array('status' =>'Hello world!'));

}

We use statuses/update’, array(‘status’ =>’Hello world!’) method to post tweet from website to Twitter account.

With the php code above, anyone who is logged in to Twitter with your application will be able to post a tweet direct from your website to their Twitter account.
The php code above in the post_tweet.php post a short text tweet “Hello world!” to Twitter.

I hope this article was helpful! Thank you so much reading!

Related : Twitter Login for PHP websites with demo and source code .

Categories
PHP Twitter Twitter API

How to implement Twitter login for PHP websites (2021)

Sign in with twitter for PHP websites

Login with Twitter for php

With Twitter APIs you can log twitter users to your website. This helps reduce the signup process and enables twitter functionalities such as “post tweets” , “follow users” directly from your own web server. You can put a “login with twitter” button on your website to securely log twitter users to your website.

In this post, we will learn how to use twitter login for a PHP websites.

With the source code provided on this post you will be able to use a “sign in with twitter” button on your website that will allow your twitter users to log in to your site using their twitter credentials.

See the live demo


You can use your real twitter account for the login. Don’t worry your account is safe and your account credentials are saved only in the sessions between this site and your browser. You can revoke access to this application any time from your twitter account settings.


Sign in with Twitter

Download the source code :

You can download the “Sign in with twitter for PHP” source code as zip file from here and upload it to your webserver using any web based ftp client.
The only one file that you need to modify is the index.php .

Open it in your editor and change the Consumer key, Consumer sercret and callback URL with your own values .

Find the following three lines in the index.php file and replace the values

define('CONSUMER_KEY', 'yourKeyHere');
define('CONSUMER_SECRET', 'yourSecretHere');
define('OAUTH_CALLBACK', 'https://example.com/demo/twitter/login/callback.php');

Update these three lines and you will be ready to use Twitter login on your php website.

What you need to get started with Twitter PHP APIs

  • PHP (5.4 or above)
  • Custom domain with SSL cert.
  • Twitter API App
  • Twitter oauth source code

Things to setup before you start

PHP server :Your php version must be 5.4 or greater to use twitter login.

Custom domain with SSL cert :In order to make secure API calls from your website to twitter, you need an SSL certificate for your domain. Make sure your URLs use https perfix.

Twitter API app : you need a twitter developer API Api to get Consumer token and secret. See instructions bellow on how to create one.

Twitter oauth source code : Download the zip source code file file . Upload and unzip it to your web directory.

Create a twitter developer API app

API app will provide you “consumer token” and “consumer secret” that will be used to verify your app on the twitter oauth code.

In order to be able to create an application on the twitter developer platform, first of all you need to submit an developer application and once its approved you can then create your first App.

To create your first app , go to https://developer.twitter.com/en/apps and click on the crete a new app button.

Creating an app on the developer platform is easy and it only takes a few seconds to make the app Live.

Fill up all the required app details

Twitter Dev app

  • App name : The name of your Application ie: “Demo app”.
  • App description : The short description of your Application in 10 to 200 characters. Write a short description about your application.
  • Website URL : Add the URL of your website ie https://exmple.com/ . You can add the URL on which you are hosting the twitter oauth code. Add https://yoursitename.com/twitter/login if you are using the oauth source code provided on this post.
  • Click on the “enable sign in with twitter checkbox. If you do not check mark this then your application will not be able to authorize twitter login requests.
  • Callback URL : callback URL is the URL where twitter users will get redirected to after completing the twitter login or after pressing the “Authorize app” button.If you are using the source code provided by us then add http://yoursitename.com/twitter/login/callback.php to this field.

Twitter developer app for PHP login
The last three fiels except the “Tell us how your app will be used” are optional fields you can leave them blank.
You need to write a short description about how you will use the application. Example : Write “I want use this for a simple login” . This field is required and only visible to twitter employees.

Finally click on the create button. This will create your app and you can now copy the “customer token and secret ” from the settings. You need these app token and secret to update the config.php file of the source code.

Download the Twitter oauth source code

Now that you have app token and secret your next step is to download the source code zip file from the link mentioned above. Upload and unzip it to your document root folder. The zip file will create a new folder named “twitter/login” on your root directory. All the source files are located inside the twitter directory.

The only one file that you will need to modifyis index.php. You can find the index.php file in Twitter/login folder of your twitter source code.
Go to /twitter/login on the ftp editor and open index.php for writing.

Index.php contains your consumer token/secret and callback URL
[code]
define(‘CONSUMER_KEY’,’Add_your_key_here’);
define(‘CONSUMER_SECRET’,’add_secret_here’);
define(‘OAUTH_CALLBACK’, ‘https://example.com/twitter/login/callback.php’);
[/code]
Replace define values with your own values .
You can find your application consumer key and secret on Keys and token menu of your Twitter API app.
Twitter API app key and token dashboard


That’s it.
Now you can go to “yoursite.com/twitter/” to check your sign in with twitter demo.

Twitter user properties

User properties are used to display user informations on a web page. To display profile informations of logged in twitter users you can use the following properties provided by Twitter API.
[code]
echo “User name “.$user->name;
[/code]
The php code above will print twitter name of the user who is logged in to your page using Twitter API.

A list of twitter user properties:

  • name – the full name of the user
  • screen_name – screen name of the twitter user ie. “foobar” without the leading “@”.
  • profile_image_url_https – URL of the twitter user profile pic with secure https scheme.
  • statuses_count – the number of tweets posted by the user.
  • followers_count : follwers count of the user.
  • friends_count – following count of the user.

To see a complete list of Twitter user properties, you can print the $user variable (after authorising the user) .
code>print_r($user);