Category: PHP and mySQL

How To : Improve Your PHP Programming

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email

How To : Improve Your PHP Programming

 


Hello everyone,

I’ve decided that I would make a thread here describing the different things that I do to improve other people’s PHP scripts.

Hope you enjoy it and learn a thing or two.

1 – Your PHP Tags
I know some of you prefer to use the short tags when writing PHP scripts <? ?> but this is not always the best way of doing it.
The standard tags <?php ?> are much better as they will work on every server that you write your PHP code on. You may move to a server some day that doesn’t allow the short tags or the ASP-style tags and you will have to sit for an hour and update your PHP scripts.

2 – Debugging Your PHP Code
Some of us may run into a problem when programming a PHP script and don’t know what’s wrong with it. The error_reporting() function in PHP helps you out by telling every error you have on your page. To show all of the errors on the page that you’re editing, put this on the second line :

PHP Code:
error_reporting(E_ALL);

3 – Debugging Your PHP Code (again)
When you finish editing your 1200-line PHP script, click onto it in your Internet browser, you see an error that says that is on line 561. Don’t hit the panic-attack button quite yet, because there is an easy way to find out what line 561 is. Follow these easy steps :
- Open up Microsoft Notepad
- Paste your PHP script into it
- Go to ‘Edit’ >> ‘Go To…’ (or Control+G)
- Type in line #561 and hit the enter key
- Your cursor is taken to line #561.
- Look above and below line #561 to see if there is any kind of trouble.
- Fix the error, re-upload the script to your website, and most likely it will work. If there is another error, repeat the above steps.

4 – Using Comments
If you have a 1200-line PHP script, it may be quite hard to figure out what’s going on all through-out it. The solution to figure out what you’re doing is to add PHP-comments.
PHP-comments are different than the <!– HTML Comments –> as they are not outputted to the user’s page (meaning that they are not even going to see it in the source code).
There are three ways to make comments in PHP :

PHP Code:
<?php
// The double-backslash is my personal favorite.  I add another set after my code so that it looks even, though it is not necessary. //
# The hash-style comment is another way of making a comment.
/* And, this is the final way of making PHP-comments.  You can use
multiple
lines
at a time by using this style. */
?>

You can decorate it however you like, you are the only one who may use them.

5 – Indenting Your PHP Codes
I don’t personally like to indent my PHP codes, but it helps when reading it. When I do have to, I use the tab key to accomplish this. Example :

PHP Code:
<?php
// Settings //
$var1 "This";

// Showing Variables //
if($var1 == "This"){
echo
"You said This";
}else{
echo
"You said That";
}
?>

6 – Improving your PHP-File Includes
I’m sure that most of us on here include a PHP file or two for our layouts. Well, what if your layout file was missing ? Wouldn’t that look pretty unprofessional to the people on your website ?
In every PHP-script that I write, I make sure that the file exists before it is even included. Here’s an example :

PHP Code:
<?php
if(!file_exists("layout.inc.php")){exit("Error :  LayOut File Missing");}else{include_once("layout.inc.php");}
?>

I’m sure that a small error message will seem better than half a page that is all messed-up looking.

7 – Your MySQL Queries
Sometimes when you’re writing a PHP script that includes connections to your MySQL database, you may run into a few problems. Most everyone that had MySQL problems ran a command like this one :

PHP Code:
<?php
mysql_query
("INSERT INTO tableName ('id','name') VALUES('1','Mike')");
?>

..and they figure out that it’s not inserting into their database. Here’s the solution to this :

PHP Code:
<?php
mysql_query
("INSERT INTO tableName ('id','name') VALUES('1','Mike')") or exit("MySQL Error :  " mysql_error());
?>

8 – Combining Alike If-Then Statements
You may have a register page, and want to make sure that everything has been filled-in. You may use many if-then statements like so :

PHP Code:
<?php
if(!$_POST[name]){exit("Sorry, but you did not fill-in all of the requested fields.");}
if(!
$_POST[email]){exit("Sorry, but you did not fill-in all of the requested fields.");}
?>

You can combine these two lines into one by joining their if-then statements together :

PHP Code:
<?php
if((!$_POST[name]) || (!$_POST[email])){exit("Sorry, but you did not fill-in all of the requested fields.");}
?>

Simply, || is the same thing as OR and && is the same as AND.

9 – Using echo or print ?
Most of you may say ‘echo is the same thing as print’, in which I agree with you all. The echo command is much faster than the print command, and is one less character to type. The echo command came later than the print command (I believe), so you make the judement on which to use.

10 – Printing out a Huge Chunk of HTML at a Time
Well, I’m sure that many of us found a way to get around this, but I’d like to share with you a few of the ways you can do it.

1 – Break off your PHP-code, print the HTML, and start your PHP-code up again. (I don’t prefer doing this as it looks pretty unprofessional to me).
2 – Adding backslashes to each HTML tag. (It works, but takes forever to do).
3 – Using the echo/print command, but without having to do much work. (I recommend) :

PHP Code:
<?php
// Showing a huge chunk of HTML at a time //
echo<<<END
<font face="Verdana" color="Orange" size="3">Large, Orange Text in Font Size 3</font>
<br><br>
More HTML down here..
<br><br>
<div align="Center">Centered text</div>
END;
?>

Well, I have many other things to tell about sprucing up your PHP-code, but I don’t want to bore you.

I hope I’ve helped.

Best Regards,

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email
 

WP Solve “You do not have sufficient permissions to access this page”

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email

The Horrible Situation where many of you have faced .

Recently I have faced this scenario : Admin logs in fine, however, NO Add New Plugin , and several pages pop the above nightmare error.

I have searched dozens of solutions, and I ended up reading hundreds of lines to figure out the solution and fix for all permissions.

Based on the Codex proposed by WP, it explains Capabilities and User Roles,  I suppose once you are reading this you are either a non developer or a developer wants to save sometime , so lets cut the chase and show Steps :

1: First you might try the simple solution offered on this website , it simply forced upgrades for non completed DB upgrades and did indeed offer a massive help for many users.

However this is not the case for me.

2: Also another useful suggestion which is deactivation all your plugins one by one, because however good a plugin was written it could conflict with some internal code and pop up the above error.

If you are unable to access Admin Control Panel in WP, do not panic, Simply go to your FTP WP-Plugins folder located in WP-Content/Plugins, and rename folders you find there or even download them as a back up and delete them all.

If this solves your error, great, reupload plugins one by one till error appears and you found your messed up plugin.

3: The Database way, if all above failed, your problem is Not a messed upgrade script can solve nor a plugin…

Here is what you should be looking for

A – Login to your phpmyadmin interface and browse the Table : WP_usermeta    ( WP is the table prefix for me, if yours is different go accordingly )

Find the row with your user ID and named wp_capabilities   , its value must be exactly :
a:1:{s:13:”administrator”;b:1;}

As you see above, my user ID is 1, because its the default admin user setup upon installation, if yours is different again note that.

B -  TEST your site now.

If this solves it, great !

C – Still not solved or the info is already correct ? No Problem. …

I have read a lot about users who already did this or already had it in place and still couldnt resolve the problem, so basically you have uploaded latest files, and have admin permissions in place and still the plugin when checks for this

if ( ! current_user_can(‘install_plugins’) )
wp_die(__(‘You do not have sufficient permissions to install plugins on this site.’));
 

The error remains , go again to your phpmyadmin , browse table wp_options and look for the row : wp_user_roles

EDIT that row –

IMPORTANT : COPY and paste data in that field option_value and save that text as a backup

REPLACE THAT TEXT with the following CODE : ( Download the text File and replace it in your DB )

user_roles

Now go to your wordpress admin control panel and Enjoy permission free administration !

 

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email
 

Simple CSV Import Class, to mysql Database Table

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email

<?php

/********************************/
/* Edit the entries below to reflect the appropriate values
/********************************/
$databasehost = “localhost”;
$databasename = “dbname”;
$databasetable = “table”;
$databaseusername =”root”;
$databasepassword = “”;
$fieldseparator = “,”;
$lineseparator = “\n”;
$csvfile = “codes.csv”;
/********************************/
/* Would you like to add an empty field at the beginning of these records?
/* This is useful if you have a table with the first field being an auto_increment integer
/* and the csv file does not have such as empty field before the records.
/* Set 1 for yes and 0 for no. ATTENTION: don’t set to 1 if you are not sure.
/* This can dump data in the wrong fields if this extra field does not exist in the table
/********************************/
$addauto = 0;
/********************************/
/* Would you like to save the mysql queries in a file? If yes set $save to 1.
/* Permission on the file should be set to 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
/********************************/
$save = 1;
$outputfile = “output.txt”;
/********************************/

if(!file_exists($csvfile)) {
echo “File not found. Make sure you specified the correct path.\n”;
exit;
}

$file = fopen($csvfile,”r”);

if(!$file) {
echo “Error opening data file.\n”;
exit;
}

$size = filesize($csvfile);

if(!$size) {
echo “File is empty.\n”;
exit;
}

$csvcontent = fread($file,$size);

fclose($file);

$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());

$lines = 0;
$queries = “”;
$linearray = array();

foreach(split($lineseparator,$csvcontent) as $line) {

$lines++;

$line = trim($line,” \t”);

$line = str_replace(“\r”,”",$line);

/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace(“‘”,”\’”,$line);
/*************************************/

$linearray = explode($fieldseparator,$line);

$linemysql = implode(“‘,’”,$linearray);

if($addauto)
$query = “insert into $databasetable values(”,’$linemysql’);”;
else
$query = “insert into $databasetable values(‘$linemysql’);”;

$queries .= $query . “\n”;

@mysql_query($query);
}

@mysql_close($con);

if($save) {

if(!is_writable($outputfile)) {
echo “File is not writable, check permissions.\n”;
}

else {
$file2 = fopen($outputfile,”w”);

if(!$file2) {
echo “Error writing to the output file.\n”;
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}

}

echo “Found a total of $lines records in this csv file.\n”;
?>

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email
 

php mysql example display table as html

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email

PHP MySQL example: display table as HTML

<html><head><title>MySQL Table Viewer</title></head><body>
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'lptm42b';

$database = 'sphinx';
$table = 'spheres';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>
Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email
 

PHP disable_functions eval base64 horror and others

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email

Most websites and web hosts now have their own custom php.ini so as a hosted user, you would be interested in adding some of security to your website , a typical joomla security tip will look like this

open_basedir = /home/users/you/public_html:/tmp
disable_functions = show_source, system, shell_exec, passthru, exec, phpinfo, popen, proc_open
open_basedir = /home/users/you/public_html

Ofcourse , if you understand what you are doing, add to the disable functions list any commands you wish php to ignore and not parse, and when u doubt urself about a command, try on php.net/yourcommand and read more about it.

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg ThisSubmit to redditShare on MyspaceShare via email