PHP Get Current URL

Sometimes it is not as straightforward as one may think to get the current url to use it inside your application. Here is a snippet that I use to fetch the current URL and use it in a script. The current url (whether http or https) is now a local variable that you can do with as you please.

[php]$url = (!empty($_SERVER['HTTPS'])) ? “https://”.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : “http://”.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];[/php]

Note: You should groom this value before using in anything sensitive, like a sql query.

Share

PHP mysql Getting rid of magic quotes problem once and for all

Here is a simple solution that i have found recently. In you project at very start of your code may be in your conf file some where:

This should solve all your magic quotes problems inshAllah.

If you post data has some variables like name[], phone[], etc. i.e. if you $_REQUEST is multidimensional use the following function:

 

 

Share

php mysql indented subcategory recursive loop

Here is my simple recursive function to create a category subcategory tree of unlimited subcategories.

 

 <select name="parent_cat">
      	<option value="0">Root</option>
      	<?
          function get_all_sub_cats($parent_cat_id, $level_string)
          {
              $return_str='';
              if(!$level_string)
              {
                  $level_string='';
              }
              $db=new DB();
              $db->open();
              $db->query("select * from categories where parent_id='{$parent_cat_id}'");
              $db->rsset();
              if($db->rs)
              {
                  while($db->rs)
                  {
                      $return_str.="<option value=\"{$db->rs['id']}\" style=\"padding-left:10px\">{$level_string}{$db->rs['name']}</option>";
                      $return_str.=get_all_sub_cats($db->rs['id'], $level_string.'+');
                      $db->rsset();
                  }
              }
              else
              {
                  return false;
              }
              return $return_str;
          }
      	    print get_all_sub_cats('0', '');
      	?>
      </select>

This is to fit my needs. You can get the logic and build your own accordingly.

Share

ob_start – save php output to a string variable – The PHP output buffering

I want to share this great php utility: the output buffering, it is sometimes very usefull. So what it does ?
The PHP output buffering will save all the server outputs ( html and php prints) to a string variable.

So to start buffering, use ob_start(); this will keep saved any output.
Then you use $variable = ob_get_clean(); to stop buffering, and copy the buffer content to the variable.

Here are few samples of the use of ob_start() and ob_get_clean()

<?php ob_start(); //Turn on output buffering ?>
Hello world, <a href=”http://www.blogger.com/myotherpage.php”>link</a>
<div class=”style”>Content</div>
<?php $var = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer
ob_end_flush();
?>

Now the content of the variable $var should be:

Hello word, <a href=”http://www.blogger.com/myotherpage.php”>link</a>
<div>Content</div>

Another example (with php outputs buffered)

<?php ob_start(); ?>
Hello world, <?php echo ”My Website”; ?>
Thank you.
<?php $var = ob_get_clean();
ob_end_flush();
 ?>

And this will be the content of $var:

Hello world, My Website
Thank you.

Share

cs-cart help – enable ratings and reviews on all products at once

Use following code with you db info to enable ratings and reviews at once on all products saves a lot of time and energy. Originally this is taken from cs-cart forum but i have done little modification to work perfectly. Tested on version 2.x.

 

<?php

// login to the cscart database
$username=”";
$password=”";
$cscartDB=”";
mysql_connect(‘localhost’, $username, $password);
@mysql_select_db($cscartDB) or die(“Unable to select $cscartDB database”);

// get all the active product_id’s from the cscart_products table
//$query = “SELECT product_id FROM cscart_products WHERE status=’A'”;

$query = “SELECT product_id FROM cscart_products”;
$productsResult = mysql_query($query);
$numRows = mysql_numrows($productsResult);
echo “Processing $numRows product id’s…\n”;

while ($row = mysql_fetch_assoc($productsResult)) {
$cscart_product_id = $row['product_id'];

// see if there is a row already for this cscart_product_id
$query=”select object_id from cscart_discussion where object_id=$cscart_product_id AND object_type = ‘P’”;
$result=mysql_query($query);

// if not, add a row to cscart_discussion
if (mysql_num_rows($result) == 0) {
echo “Inserting record into cscart_discussion for $cscart_product_id\n”;
$query=”INSERT INTO cscart_discussion (object_id, object_type, type) VALUES ($cscart_product_id, ‘P’, ‘B’)”;
$result=mysql_query($query);

if (!$result)
echo “Query failed: ($query): ” . mysql_error(). “\n”;
}

//update already existing products statuses

$query=”update cscart_discussion  set type=’B’ where object_type=’P'”;
$result=mysql_query($query);

 

if (!$result)
echo “Query failed: ($query): ” . mysql_error(). “\n”;
}
?>

Share

cs-cart code help- Changing products data for blocks

\core\templater_plugins\function.block.php

function smarty_function_block_output($_block_data, &$smarty)

This function creates the block. and assign the values to the block items.

 

core\fn.catalog.php

function fn_get_products($params, $items_per_page = 0, $lang_code = CART_LANGUAGE)

This function supplies products data to the function above

 

Share

cs-cart 1.3.5 product features export problem to version cs-cart 2.x.x

As product features can’t be exported readily from cs-cart version 1.3.5 to cs-cart version 2.x.x here is the solution:

 

Unfortunately, there is no possibility to use the CSV file of format 1.3.5 in the 2.1.x CS-Cart installation. But there is the possibility to create new CSV file with the necessary format.

In this case you can try the following solution.
1) Open the “exim.products.php” file, located in the “include/admin/exim” directory of your 1.3.5 CS-Cart installation.
2) In this file, replace the following part of code:

if (!empty($features)) {
	foreach ($features as $f) {
		if (!empty($f['value'])) {
			$result[] = fn_exim_post_item_id($f['feature_id']) . "$f[description]$pair_delimiter $f[value]";
		}
	}
}

with this one:

if (!empty($features)) {
	foreach ($features as $f) {
		if (!empty($f['value'])) {
			//[bo"lean]
			$result[] = fn_exim_post_item_id($f['feature_id']) . $parent . "{$f['description']}{$pair_delimiter} {$f['feature_type']}[" . (!empty($f['value']) ? $f['value'] : $f['value_int']) . ']';
			//[/bo"lean]
		}
	}
}

and save the file.

Then you should try to create the CSV file once again in your 1.3.5 CS-Cart installation, using the “Export” functionality.

Then please try to import this file in your 2.1.x CS-Cart installation.

 

Share

PHP MYSQL UTF-8

[ad]

Connection:

SET NAMES 'utf8';

PHP mysql connection (not totally confirmed, but see tests below) defaults to a latin1 connection, so, your first query after connection should be:

mysql_query("SET NAMES 'utf8'");

In php versions 5.2 and later, use

mysql_set_charset('utf8',$conn);

[ad]

Share

10+ extremely useful PHP classes

[ad]

PHP PSD Reader

A few weeks ago, I wrote an article about this PHP which allow you to display any Adobe PSD file on screen. Very usefull to create preview of PSDs designed for clients, for example.
Download

Browser detect

One of the most common (and boring) problem for front-end developers is definitely cross-browser compatibility. This PHP class will detect almost all browsers and simplify your cross-browser work.
Download

Akismet

Remember those days without spam? If your website gets spammed in any ways, Akismet can probably help you. When a new comment, trackback, or pingback comes to your site it is submitted to the Akismet web service which runs hundreds of tests on the comment and returns a thumbs up or thumbs down.
Download

ADOdb

The large majority of websites and web apps are using databases to store all kinds of data. ADOdb is a database abstraction library for PHP, supporting MySQL, PostgreSQL, Interbase, Firebird, Oracle, MS SQL and more. ADOdb is quite easy to learn and have lots of nice features as such as extensive portability support, speed and BSD licencing.
Download

HTML Purifier

As it name tells, HTML Purifier is a PHP class created to help you writing a better code. HTML Purifier can remove malicious code and make sure your code is standard-compliant. A great tool for all developers.
Download

Google charts API

Charts are very useful and highly asked by clients, but they can be a lot of work. I remember some years ago when a friend of mine had to create charts using Photoshop every week for one of his clients. Well, this time is gone for good.
With the Google charts API, a simple chart can be created and displayed on screen using as little as 4 lines of code.
Download

pChart

pChart is another chart class, and it is as good as Google charts API. Data can be easily retrieved from SQL queries, CSV files, or manually provided.
Download

PHP Excel

Excel documents are highly popular in the corporate world. Considering that fact, there’s a strong chance that one of your clients asks for you to create excel files in PHP someday.
Happilly, the PHP Excel engine allow you to easily create and manipulate lots of different files, as such as Excel 2007, Open XML, or PDF.
Download

Country from IP

Some websites are able to detect your location and automatically display information related with your language. How do they do that? Quite simple, they use your IP adress to find your location. The Country from IP class is easy to use and will allow you to get the country a specific IP is from.
Download

Cache Manager

If you’re working on a high traffic site, there’s not doubt you’ll need to cache files in order to improve performance. This will be very easy an simple to do, using this very handy class. A defifinitive must-have, in my opinion.
Download

WPGet

As I know many of you have a WordPress blog, I just can’t finish this article without a great tool for our favorite blogging engine.
WPGet is a PHP class which allow you to easily get infos from a WordPress 2.X database. In other words, it allows you to get posts, comments, etc from a WordPress blog, on a non-WordPress site. Great, isn’t it?
Download

[ad]

Share

How to display PHP errors in My Script Code When display_errors is Disabled

[ad]

If you are like many webmaster who are always making your website more secure, then you will benefit from this small simple tutorial guide on how to show your php errors. This helps when your web hosting isp or provider has turned off the display erorrs feature in the php.ini file.

Sometimes, your head turns trying to figure out what the problem is with your script. many times when the display_errors if off, you won’t have a clue as to what the problem is unless you display the php errors.

this is how the php.ini file would look like:

Quote:

; - display_errors = Off           [Security]
;     With this directive set to off, errors that occur during the execution of
;     scripts will no longer be displayed as a part of the script output, and thus,
;     will no longer be exposed to remote users.  With some errors, the error message
;     content may expose information about your script, web server, or database
;     server that may be exploitable for hacking.  Production sites should have this
;     directive set to off.
; Print out errors (as a part of the output).  For production web sites,
; you're strongly encouraged to turn this feature off, and use error logging
; instead (see below).  Keeping display_errors enabled on a production web site
; may reveal security information to end users, such as file paths on your Web
; server, your database schema or other information.
display_errors = On

As you have read from the php.ini file above, having the display_errors on could have a security issue. so many web hosting companies turn it off, this is to protect your website from harm.

One way to display erorrs while the display_errors is off in the php.ini file, is to create write these functions at the beginning of your script files (.php files)

copy and paste this code

Code:

ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);

As for me, i had to learn the hard way. i was installing a gallery into my site and could not figure out what the problem was. this is what the gallery site had to say:

When diagnosing a problem, you want to be sure that you notice all hints that there might be. That’s why you need to ensure that PHP is configured to display and log errors in such cases.

* Starting with Gallery 2.2, it suffices to put Gallery into its debug mode.
* In Gallery 2.0 and Gallery 2.1 (including 2.1.2), the debug mode doesn’t enable displaying PHP errors yet. You’ll need to enable it yourself.
* In rare cases, you also have to ensure that PHP errors are not just displayed, but also logged.

Also see: * How can I view the error log of the webserver?

By browsing to your Gallery’s phpinfo page at http://www.example.com/gallery/lib/support/index.php -> PHPinfo, you can find all the configuration details of PHP we’re interested in. And these are:

* display_errors (we want it to be On or 1)
* display_startup_errors (we want it to be On or 1)
* log_errors (we want it to be On or 1)
* error_log (it should be anything but undefined)
* error_reporting (it should be 2047 or larger)

You can ask your webhost to help you to put PHP into a configuration that is useful for debugging. Or you can open Gallery’s main.php file in a text editor and replace:

[ad]

Share