Showing posts with label PHP Tips. Show all posts
Showing posts with label PHP Tips. Show all posts

8 Useful WordPress SQL statement 2014


In the past decade, MySQL database has become popular, and WordPress blog using a MySQL database, although the use of plug-ins can solve some problems, but to achieve some special tasks, execute SQL statements in phpMyAdmin is the most concise way, here is a useful summary of eight WordPress system SQL statements used to solve some practical problems encountered.

1. create a backup of the database

  Backup of the database is the first thing to do, just by following a simple method you can back up the database:

  After login phpMyAdmin. Choose your WordPress database, and then click on the "Export" button, select a compression method (you can use gzip) and click the "Go" button, when the browser when prompted to download, click "Yes", download the file to the database locally.
 
2. bulk delete articles Amendment

  WordPress2.6 later version adds a Post revisions feature, though some use, but the article is amended to increase the size of your database, we can choose to bulk delete.

  After logging in phpMyAdmin execute the following SQL statement to bulk delete.

DELETE FROM wp_posts WHERE post_type = "revision";

3. batch delete spam comments

  A true story is that one of my friends set up a blog on the Internet, there are times he spent a few days on vacation, no Internet, and when he came back, log in to your blog, saw more than 5000 comments Wait audit, of course, most of them are spam comments to manually delete these comments to spend a lot of time, so we can use the following approach.

  Execute the following SQL statement after login phpMyAdmin.

DELETE from wp_comments WHERE comment_approved = '0';

  Be careful, though this solution is useful for processing millions of ordinary garbage, but will remove comments without approval, so it is best to install or use Akismet to fight comment spam.
 
4. modify article properties

  After you install WordPress, admin account is created, a lot of people are wrong to use this account to write a blog, until they realize that this is not a personal account.

  The solution, each article to modify the properties need a lot of time, the following SQL statement can help you quickly complete this function.

  First you have to find your correct user name, use the following SQL statements can be found in your user ID number.

SELECT ID, display_name FROM wp_users;

  Assuming that this ID is NEW_AUTHOR_ID, and administrator admin ID for
OLD_AUTHOR_ID, then run the following SQL statement.

UPDATE wp_posts SET post_author = NEW_AUTHOR_ID WHERE post_author = OLD_AUTHOR_ID;

5.Manual Reset Password

  A lot of people in order to protect their own blog not being hacked, using a very complex password, although this is a good thing, but often forgotten administrator password things will happen.

  Of course, you can send to your WordPress link to reset your password via e-mail, but if you can not access your e-mail address, then had to use the following SQL statement to reset your password.

UPDATE wp_users SET user_pass = MD5 ('PASSWORD') WHERE wp_users.user_login = 'admin' LIMIT 1;

  MD5 hash function is a built-in MySQL for converting password hashes.

6.change WordPress domain

  Sometimes you may want to change your blog's domain name, but WordPress will put your name stored in the database, so you have to use the following SQL statement to modify.

UPDATE wp_options SET option_value = replace (option_value, 'http://www.oldsite.com', 'http://www.newsite.com') WHERE option_name = 'home' OR option_name = 'siteurl';

  Then, you have to use the following SQL GUID of the article will also be modified.

UPDATE wp_posts SET guid = replace (guid, 'http: //www.oldsite.com','http: //www.newsite.com');

  Finally, use the following statement will replace the article all the old domain to the new domain name.

UPDATE wp_posts SET post_content = replace (post_content, 'http://www.oldsite.com', 'http://www.newsite.com');

7. showing the number of SQL queries

  You have something to blog in performance when the number of queries the database learned is very important, in order to reduce database query, we need to know on one page in the end how many queries.

  This time, do not need to log in phpMyAdmin, you only need to modify the footer.php file, at the end of the file add the following lines of code.

<? PHP if (is_user_logged_in ()) {?>  
    <? PHP echo get_num_queries ();?> queries in <PHP timer_stop (1);??> seconds.  
<PHP?}?>


8.restore your WordPress database

  When your database for some reason (hacking or upgrade error) is damaged or lost, if you have a backup, then you can restore your WordPress database.

  Sign in phpMyAdmin, select your WordPress database, click "Import" button, click "Browse" button, then "Run" button to import the database from your hard drive to select the backup file, point.

  If all goes well, your WordPress functions will return to normal.

Wordpress Database Optimization Tips 2014 August

Wordpress database optimization tips 2014 august

WordPress system uses a long time, the database will be a lot of redundant data regularly Wordpress database optimization and cleanup, Wordpress can guarantee fast work.

  First, disable some useless plugins, WordPress system table data tables outside are removed, leaving only wp_posts, wp_comments, wp_terms, wp_term_relationships, wp_term_taxonomy and other system data tables.

  Secondly, open phpMyadmin, redundant data via SQL statement delete operation. Remember to backup before deleting it.

  Delete the script is:

  DELETE FROM wp_posts WHERE post_type = 'revision';

  DELETE FROM wp_postmeta WHERE meta_key = '_edit_lock';

  DELETE FROM wp_postmeta WHERE meta_key = '_edit_last';

  Finally, in phpMyAdmin, select all tables, click "optimize table."

  After this some optimize operations, it can be WordPress database delete redundant data to optimize the performance of the database.

Cookies Explanation for Beginners

cookies

cookies

Starting with Netscape 3.0 in 1996, browsers began to offer support for cookie.The following is a quote from the Netscape cookie specification:
A server, when returning an HTTP object to a client, may also send a piece of state information which the client will store. Included in that state object is a description of the range of URLs for which that state is valid. Any future HTTP requests made by the client which fall in that range will include a transmittal of the current value of the state object from the client back to the server.The state object is called a cookie, for no compelling reason.
Cookies provide an invaluable tool for maintaining state between requests. More than just a way of conveying credentials and authorizations, cookies can be effectively used to pass large and arbitrary state information between requests—even after the browser has been shut down and restarted.
Cookies are the de facto standard for transparently passing information with HTTP requests.These are the major benefits of cookies over Basic Authentication:
  • Versatility—Cookies provide an excellent means for passing around arbitrary information between requests. Basic Authentication is, as its name says, basic.
  • Persistence—Cookies can be set to remain resident in a user’s browser between sessions. Many sites take advantage of this to enable transparent, or automatic, login based on the cookied information. Clearly this setup has security ramifications, but many sites make the security sacrifice to take advantage of the enhanced usability.
    Of course users can set their cookie preferences to refuse cookies from your site. It’s up to you how much effort you want to apply to people who use extremely paranoid cookie policies.
  • Aesthetic—Basic Authentication is the method that causes a browser to pop up that little username/password window.That window is unbranded and unstyled, and this is unacceptable in many designs.When you use a homegrown method, you have greater flexibility.
The major drawback with using cookie-based authentication is that it does not allow you to easily protect non-PHP pages with them.To allow Apache to read and understand the information in cookies, you need to have an Apache module that can parse and read the cookies. If a Basic Authentication implementation in PHP employees any complex logic at all, you are stuck in a similar situation. So cookies aren’t so limiting after all.

Authentication Handlers Written in PHP

In PHP 5 there is an experimental SAPI called apache_hooks that allows you to author entire Apache modules in PHP. This means that you can implement an Apache-level authentication handler that can apply your authentication logic to all requests, not just PHP pages.
When this is stable, it provides an easy way to seamlessly implement arbitrarily complex authentication logic consistently across all objects on a site.

Easyway to resetting wordpress password using FTP

resetting wordpress password

Resetting wordpress password using FTP

There is lot of methods for resetting wordpress password. Normally you can reset password by clicking lost password link, which uses email to reset your password.
But if email is not working and other methods also not working or any 404 errors occur, you can reset your password via FTP.
Note: Use the methods at your own risk. I’m not responsible if any data loss.

Method 1: Edit functions.php

  • Login to your site’s FTP and navigate to the directory “/wp-content/themes/your active theme/”. Then download the file called functions.php
  • Edit the file, and find first <?php: and add the below code next to it.
    wp_set_password('password',1);
    Put your desired new password for the main admin user. “1″ denotes the user ID in the wp_users table.
  • once you’ve done upload the edited file back to the same directory of your site. Select overwrite if asks. Please make sure you have a backup.
  • Now you are able to login with the new password. Once you’ve logged change new password using admin pannel and delete the code on functions.php. Otherwise it will reset the password on every pageload.

Method 2: Emergency reset script

If the above method is not working you can use emergency password reset script.It is a PHP script.
Warnings:
  • You should know the admin user name
  • It will reset password and will send an email to admin’s email id. Even though you didn’t receive email, the password will be changed.
  • You don’t need to be logged in. If you could this method is not needed.
  • Put the script on the root directory of your website.
  • Make sure to delete the script once the password has been changed. (Important)
  • steps
    • Download emergency password reset script from here and place to your wordpress installation directory. File name should be emergency.php
    • Open ‘http://yourwebsitename.com/emergency.php
    • Follow the instructions. Enter admin username and new password. click update options. A message will be displayed to note the password change. An email will be send to the admin’s email.
    • Don’t forget to delete the emergency.php from your server. Because, anyone can use it to change the password.
    I hope one of these method will work for you. If doesn’t please feel free to comment below.

Get URL and change the according image in PHP


change image according to url

Trick to change image according to URL in PHP

Hi people! This trick is pretty simple and very useful at sometimes.
Sometimes you might want to change image according to URL in any PHP page here is the tutorial.

STEP1

In first step you need to get the current url. See the code below
This code is a php function which allows you to find out the current page URL.
You can get the Current page URL like this
This will print the current page URL. But for this tutorial we need to store it in a variable.
We’ve stored the current page URL in the variable ‘$cur’.

Step 2

Now we need to split the URL according to ‘/’ and have to select the last part.
Note: if your URL is something like this ‘http://www.example.com/pages/about’ you’ve to use the above code as it is, but if your URL is Like this ‘http://www.example.com/pages/about/’ you’ve to change the ‘-1′ to ‘-2′.
The above code will store last part of the URL in the variable $url for example ‘about’.

Step 3

Now all you need to do is save an image in this name. eg. ‘about.jpg’
Then go to your page and put the following code where you want your image to be placed.
Hurrah!! if you go to that page you can see your image. Now include all the above codes into each page where you want to show the images and place the image with the same name of URL’s last part.

PDF generater in PHP tutorial

php pdf

PHP PDF Generate tutorial

Here is the tutorial for php pdf creation.
For this you need to download a file called fpdf.php

Basic Code to generate pdf in php

Take a look at the code, First you need to include the fpdf.php file using require() function.
after requiring the library file, we instantiate an object of the FPDF class and call it $pdf.
Then we add a page with the AddPage method, set our output font, define the cell (location) for our string of output, and then—using the Output method—display the PDF in the browser.
Output for the above code will be
php pdf

PHP PDF generate using cell

In the above code we’ve used cell method.
For the first text “PHP – The Good Parts!” we’ve given x=10 and y=10 and 0,0,’L’ denotes column, row and text alignment respectively.
So the output will be
php pdf

NOTE:

You may want to disable your browser’s caching capabilities while you are developing and testing the layout of your FPDF PDFs because some browsers will not reload the page with changes if the changes are so small that they don’t register as such with the cache control.

Attachments

1) FPDF.php

Top 20 PHP Tips and Tricks for beginners

PHP tips

PHP tips to improve PHP skills

Hi people, in this post i’m gonna deliver you some interesting quick tips to explore and improve PHP skills. Try to follow these tips when you code.
  1. Use <?php ... ?> tags for PHP. All other formats are depreciated including short tags.
  2. It is very useful to use Unset or null your variables to free memory, especially for large arrays.
  3. It is better to wrap you strings in single quotes (”) instead of double quotes (“”). Beacuse PHP looks for variables into double quotes.So unless you’re gonna use a variable inside, don’t use doubles quotes for variables.
  4. echo is faster than print. So avoid using ‘print’ often.
  5. else if” statements are faster than select statements aka case/switch.
  6. Use sprintf instead of using variables contained in double quotes, it is about 10x faster.
  7. Turn on mod_deflate in Apache v2 to reduce the use of bandwidth. For Apache v1 try mod_gzip.
  8. Avoid using string concatenation. Preferred method is echo’s multiple parameters (or stacked).
  9. Avoid using pre-calculated functions in loops. for eg. for($i=0; $i< count($array);$i++) This will call count function each time. So store it in a variable like this $count = count($array); before the loop starts.
  10. Avoid using magic methods like __isset(), __unset(), __sleep().
  11. Avoid require_once() and use require() where possible.
  12. Better to Use full paths in includes and requires.
  13. require() and include() are same in all the ways. One different is require will halt if the file is missing. Performance wise there is a very little difference between them.
  14. Since PHP5, the script execution start time can be found by $_SERVER[’REQUEST_TIME’], so avoid using time() or microtime().
  15. PCRE regex is quicker than EREG, but always look out if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.
  16. Try xml2array when parsing XML in PHP, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.
  17. Error suppression with ” @ ” is very slow.
  18. str_replace is faster than preg_replace. str_replace is best overall, however strtr is sometimes quicker with large strings. Using array() inside str_replace is usually quicker than multiple str_replace.
  19. $row[’id’] is 7x faster than $row[id], because if there is no quotes PHP has to guess which index you meant, assuming you didn’t mean a constant.
  20. It is always better to close your database connection after the use.

PHP form handling for beginners

PHP form handling

PHP form handling Tutorial

PHP form handling is the thing which irritates you if you’re a beginner.
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page will automatically be available to your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:
When a user fills out the form above and click on the submit button, the form data is sent to a PHP file,
calledwelcome.php“:
“welcome.php” looks like this:
Output could be something like this
Welcome John!
You are 28 years old.

The PHP $_GET and $_POST functions will be explained in the next chapters.

Form Validation

User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
The built-in $_GET function is used to collect values in a form with method=”get”.

The $_GET Function

The built-in $_GET function is used to collect values from a form sent with method=”get”.
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send (max. 100 characters).
Example
When the user clicks the “Submit” button, the URL sent to the server could look something like this:
http://www.voidtricks.com/welcome.php?fname=Peter&age=37
The “welcome.php” file can now use the $_GET function to collect form data (the names of the form fields will automatically be the keys in the $_GET array):

When to use method=”get”?

When using method=”get” in HTML forms, all variable names and values are displayed in the URL.
Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
Note: The get method is not suitable for large variable values; the value cannot exceed 100 characters.
The built-in $_POST function is used to collect values in a form with method=”post”

The $_POST Function

The built-in $_POST function is used to collect values from a form sent with method=”post”.
Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
Note: However, there is an 8 Mb max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
Example
When the user clicks the “Submit” button, the URL will look like this:
http://www.voidtricks.com/welcome.php
The “welcome.php” file can now use the $_POST function to collect form data (the names of the form fields will automatically be the keys in the $_POST array):

When to use method=”post”?

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.

The PHP $_REQUEST Function

The PHP built-in $_REQUEST function contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST function can be used to collect form data sent with both the GET and POST methods.
Example

www.comhttp.blogspot.in. Powered by Blogger.