Basics – CodeForest https://www.codeforest.net Fri, 29 Aug 2025 10:28:50 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.3 https://www.codeforest.net/wp-content/uploads/2017/06/cropped-Asset-3-32x32.png Basics – CodeForest https://www.codeforest.net 32 32 Prevent pinning pictures from your site to Pinterest https://www.codeforest.net/prevent-pinning-pictures-from-your-site-to-pinterest?utm_source=rss&utm_medium=rss&utm_campaign=prevent-pinning-pictures-from-your-site-to-pinterest Thu, 05 Apr 2012 07:51:37 +0000 https://www.codeforest.net/?p=1266 Pinterest is the fastest growing sharing platform today, but has its own problems. It is the heaven of copyright violations and similar.

For example, if you are a photographer and have a bunch of your photos available online on your site, people will surely pin some of them. Then, other people will see those images on Pinetrest, download them and use somewhere, thus violating your copyright. Some people will even name Pinterest as the source of the image!

People at Pinterest are aware of it and released a small trick to disallow pictures from your site to be pinned.

Actually, it’s a meta tag that prevents the pinning to Pinterest.

Just place somewhere between and in your sites header:

[code lang=”html”]
<meta name="pinterest" content="nopin" />
[/code]

Now, if anyone tries to pin an image to Pinterest, they will receive an alert :

This site doesn’t allow pinning to Pinterest. Contact website owner for any questions.

Handy.

Block Pinterest for WordPress

Oh, yes. There are some plugins already available to automate this work for WordPress users:

Block Pinterest WordPress plugin and Pinterest Block plugin.

The first one only adds the meta tag, while the latter has some handy options to filter the block on pages, home page or even per post.

pinterest block

Of course, users can manually download the image and pin it, but then, owner of the image can file Copyright Infringement Notification directly on Pinterest.

But, if you block the pinning of your images, you are losing exposure for them, too. It is up to you to decide.

Do you have the need to block the pinning of your site’s images to Pinterest?

]]>
Programming for kids: PHP string manipulation and arrays https://www.codeforest.net/programming-for-kids-php-string-manipulation-and-arrays?utm_source=rss&utm_medium=rss&utm_campaign=programming-for-kids-php-string-manipulation-and-arrays Mon, 21 Nov 2011 22:49:22 +0000 https://www.codeforest.net/?p=1140 As I said earlier in my Programming for kids post, I started to teach my kids some basic programming stuff.

We were playing around with some word games and came up with a simple encrypting trick which I learned when I was a kid.

Basically, you type a word GERMANIKUS and substitute every character in that word with number, starting from 0.

So, G=0, E=1, R=2, M=3, A=4, N=5, I=6, K=7, U=8, S=9. After that, you write your message and substitute every character found in a word GERMANIKUS with a number and all other characters are just plain text.

For example, the word Codeforest would be COD1F1219T. Nice and interesting.

Now, my kids wanted to program a simple script that would take a message as a parameter and encrypt it using the above method. We chose PHP and started with writing down how the program should look and work. My kids were too eager to see the results, we first tried to work this out. This is the first version:

[code lang=”php”]




Programming for kids – string replacing



[/code]

Demo

Very simple and effective. I explained everything to my kids and they were eager to continue.

Next step was to build a form so you can enter the message to be encrypted.

[code lang=”php”]

Insert your message:


‘;
echo nl2br(strtoupper($encodedMessage));
}
?>
[/code]

Demo

Very nice, now we have a basic encrypting mechanism. But what if we want to make this even harder to break? My older kid had an idea: we will allow user to enter a key which will be a number. If a user enters number 3, that would move number 0 (zero) to the third letter of germanikus word.

Great, let’s do it:

[code lang=”php”]
$word) {
$r[$count] = $secretWord[$key] . ‘ => ‘ . $word;
$count++;
}
echo implode(‘, ‘, $r) . ‘
‘;
$message = strip_tags($_POST[‘message’]);
//encode
$encodedMessage = str_replace($secretWordArray, $codeArray, strtoupper($message));
//decode
$decodedMessage = str_replace($codeArray, $secretWordArray, $encodedMessage);
echo ‘Encrypted message:
‘;
echo nl2br(strtoupper($encodedMessage));
echo ‘
‘;
echo ‘Decrypted message:
‘;
echo nl2br(strtoupper($decodedMessage));
}
?>
[/code]

Demo

When you try this demo, you will see that if you enter 3 as a key, the fourth letter will be 0. That is ok, as we want to start counting from zero.

That’s it, my kids were delighted with this and have learned a lot about string manipulation and a little bit about arrays in PHP.

Please share your thoughts in comments below.

]]>
How to display latest Google+ updates with PHP and Unofficial Google+ API https://www.codeforest.net/how-to-display-latest-google-updates-with-php-unofficial-google-plus-api?utm_source=rss&utm_medium=rss&utm_campaign=how-to-display-latest-google-updates-with-php-unofficial-google-plus-api Thu, 04 Aug 2011 20:27:09 +0000 https://www.codeforest.net/?p=955 As we are all waiting for official Google Plus API, I browsed the internet looking for some unofficial ways for implementing Google Plus into web applications.

I found some very interesting stuff, but the most advanced is Jason Striegel’s Unofficial Google API.

For the moment it consists the following:

GoogleUtil – functions for parsing the almost-JSON that Google Plus produces
PlusPerson – a person entity in Google plus that can be stored to a local mysql DB
PlusRelationship – a relationship between people in Google plus. This does not contain any circle context
PlusPost – a post to a user’s activity stream
PostAttachment – encapsulates a media attachment to a post

I will surely write a tutorial using this great code, but as I am enjoying a summer vacation, I wanted to write a simple tip on getting the latest updates from Google Plus. So I will use Plus Feed, an unofficial Google+ User Feeds.

Usage is pretty straightforward:

[code lang=”php”]

// Google Plus user id
$user_id = "107308413755179474011";
// we are using CURL to access the API
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://plusfeed.appspot.com/" . urlencode($user_id));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec ($curl);
curl_close ($curl);

header(‘Content-Type: application/xml; charset=UTF-8’);
// just echoing plain XML result (which is Atom feed)
echo $result;

[/code]

That’s it, you just enter desired Google Plus user id and get (unfortunately only public) updates for that user id. Now, you can use SimpleXMLElement to parse the results as I did on my Useful Twitter snippets tutorial.

More on this subject in one of the later tutorials, so stay tuned.

]]>
jQuery Mobile Tutorial: Basics https://www.codeforest.net/jquery-mobile-tutorial-basics?utm_source=rss&utm_medium=rss&utm_campaign=jquery-mobile-tutorial-basics https://www.codeforest.net/jquery-mobile-tutorial-basics#comments Wed, 02 Feb 2011 22:06:42 +0000 https://www.codeforest.net/?p=742 As smart mobile phones are all over the place, the need for mobile web pages rises. Building a mobile web page is different in many ways then building a “normal” web page.

To help us, smart people have developed a unified user interface system across all popular mobile device platforms, built on the rock-solid jQuery and jQuery UI foundation. Yes, it’s jQuery Mobile.

So, let me show how easy it is to use it. When you start developing with jQuery Mobile, first thing is to build a boilerplate template and see if everything is working as expected.

So open up your favourite editor and enter this code in:

[code lang=”html”]



jQuery Mobile Tutorial on Codeforest.net


The title

The content

The Footer



[/code]

Now save this page as index.php and open it up in the browser. OMG, it works. As you can see, we called jQuery and jQuery Mobile from Google and loaded jQuery Mobile CSS.

If you look closely, you will some strange attributes like data-role. It is exactly these attributes that are telling jQuery Mobile what this element is, how to look like and how to behave.

So, let us do something fancy now. There are two type of linking inside jQuery Mobile, External and Internal. Let me show you the magic:

External linking

By default, when you click on a link that points to an external page (ex. products.html), the framework will parse the link’s href to formulate an Ajax request (Hijax) and displays the loading spinner.

If the Ajax request is successful, the new page content is added to the DOM, all mobile widgets are auto-initialized, then the new page is animated into view with a page transition.

If the Ajax request fails, the framework will display a small error message overlay that disappears after a brief time so this doesn’t break the navigation flow.

Open a new file and paste this in:

[code lang=”html”]



jQuery Mobile Tutorial on Codeforest.net

Some Title

Page Footer




[/code]

Save this file and load it in the browser. If you click on the link, you will see Loading and the new page is loaded. Also, there is a Back button rendered on top in header.

If something is wrong (like you misspelled index.php and wrote ondex.php), you will get an error message. Nice.

Internal linking

A single HTML document can contain multiple pages that are loaded together by stacking multiple divs with a data-role of “page”. Each page block needs a unique ID (id=”first”) that will be used to link internally between pages (href=”#first”). When a link is clicked, the framework will look for an internal page with the ID and transition it into view.

[code lang=”html”]

First

The content

View internal page called second

Page Footer

Second

I’m the second content

Back to first

Page Footer


[/code]

Above is only code inside the body tags.

It’s important to note if you are linking from a mobile page that was loaded via Ajax to a page with multiple internal pages, you need to add a rel=”external” to the link. This tells the framework to do a full page reload to clear out the Ajax hash in the URL. This is critical because Ajax pages use the hash (#) to track the Ajax history, while multiple internal pages use the hash to indicate internal pages so there will be a conflicts.

Themes

You can easily use themes anything in jQuery Mobile with data-theme attribute. Try something like this:

[code lang=”html”]



jQuery Mobile Tutorial on Codeforest.net


The title

The content

The Footer



[/code]

Try it in your browser and you should have a nice bluish theme. You can try other letters like e or a.

That’s it for the basics. Next time we will start building our sample web page in jQuery Mobile from scratch. I hope you like this amazing piece of software and realize how easy it is to get started.

]]>
https://www.codeforest.net/jquery-mobile-tutorial-basics/feed 25
PHP Exceptions https://www.codeforest.net/php-exceptions?utm_source=rss&utm_medium=rss&utm_campaign=php-exceptions https://www.codeforest.net/php-exceptions#comments Thu, 27 Jan 2011 22:53:21 +0000 https://www.codeforest.net/?p=724 PHP 5 has an exception model similar to that of other programming languages (like Java). An exception can be thrown, and caught within PHP.

Code can be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch block.

Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block, or when a catch matching the thrown exception’s class is not present) will continue after that last catch block defined in sequence.

Enough said, let me show you a basic example:

[code lang=”php”]
class Generic
{

private $someVar;

public function __construct($someVar)
{
$this->someVar = $someVar;
}

public function testValue($someOtherVar)
{
if($someOtherVar > 3) {
throw new Exception(‘Method parameter can not be larger then 3!’);
} else {
echo $this->someVar + $someOtherVar;
}
}
}

$gen = new Generic(3);
$gen->testValue(4);
[/code]

This is some really generic code to show you how exceptions are handled. If you try this you will get a response like this:

Fatal error: Uncaught exception ‘Exception’ with message ‘Parameter can not be larger then 3!’ in C:\wamp\www\privat\codeforest\exceptions\index.php:15 Stack trace: #0 C:\wamp\www\privat\codeforest\exceptions\index.php(23): Generic->testValue(4) #1 {main} thrown in C:\wamp\www\privat\codeforest\exceptions\index.php on line 15

That is because I didn’t put try and catch blocks to handle the exception. So, to do it properly, our code should look like this:

[code lang=”php”]
try
{
$gen = new Generic(3);
$gen->testValue(4);
} catch (Exception $e) {
// code to handle the Exception
echo ‘Catch exception here
‘;
echo ‘Message: ‘ . $e->getMessage() . ‘
‘;
echo ‘Some more info goes here!’;
}
[/code]

Now, the exception is caught and our exception message is displayed on the screen.

It’s possible to get detailed information about the error that occurred. It’s precisely for this reason that the Exception class provides developers with some other methods, which can offer additional details about the failure and its environment.

This is how to implement this other methods in our little example:

[code lang=”php”]
try
{
$gen = new Generic(3);
$gen->testValue(4);
} catch (Exception $e) {
// code to handle the Exception
echo ‘Error :’ . $e->getMessage() . ‘
‘;
echo ‘Code :’ . $e->getCode() . ‘
‘;
echo ‘File :’ . $e->getFile() . ‘
‘;
echo ‘Line :’ . $e->getLine() . ‘
‘;
exit();
}
[/code]

Returning to the example above, it’s nearly the same as the previous one. However, the catch block uses the additional methods of the exception object, helpful for obtaining more specific details on the error that occurred. With reference to this, the set of echo statements displays the error message passed in when the exception was originally thrown, as well as the error code (if any), the file containing the error, and finally the line at which the failure happened.

Now, the benefits of exceptions should be pretty clear. Notice how easy it is to set up an error management mechanism that can be developed through specific code, while maintaining program flow completely free from dealing with potential failures. In addition a greater level of detail on the error that occurred can be easily obtained by calling up some of the complementary built-in methods.

Consider this example:

[code lang=”php”]
class Generic
{

private $someVar, $result;
const NUM_ERROR = 1;
const ANY_ERROR = 2;

public function __construct($someVar)
{
$this->someVar = $someVar;
}

public function testValue($someOtherVar)
{
if($someOtherVar > 3) {
throw new Exception(‘Parameter can not be larger then 3!’, self::NUM_ERROR);
} else {
$this->result = $this->someVar + $someOtherVar;
echo $this->result . ‘
‘;
}
}

public function otherMethod()
{
if($this->result > 4) {
throw new Exception(‘The result is greater then 4.’, self::ANY_ERROR);
}
}
}

// let’s do it
try
{
$gen = new Generic(3);
$gen->testValue(2);
$gen->otherMethod();
} catch (Exception $e) {
if($e->getCode() == 1) {
die ($e->getMessage());
} else {
echo ‘Error :’ . $e->getMessage() . ‘
‘;
echo ‘File :’ . $e->getFile() . ‘
‘;
echo ‘Line :’ . $e->getLine() . ‘
‘;
exit();
}
}
[/code]

Now, with the introduction of a few modifications to the original sample class, I’ve set up a more efficient error handler, which can react differently, based on the second error parameter passed to client code. Certainly, it’s possible to use all the methods of the Exception class shown above, and develop an error handing mechanism capable of giving detailed information on the failure and its context.

But, there is one more thing you can do. Create your own Exception handler. Creating a custom exception handler is quite simple. We simply create a special class with functions that can be called when an exception occurs in PHP. The class must be an extension of the exception class.

The custom exception class inherits the properties from PHP’s exception class and you can add custom methods to it.

Consider this example:

[code lang=”php”]
class Generic
{

private $someVar, $result;
const NUM_ERROR = 1;
const ANY_ERROR = 2;

public function __construct($someVar)
{
$this->someVar = $someVar;
}

public function testValue($someOtherVar)
{
if($someOtherVar > 3) {
throw new CustomException(‘Parameter can not be larger then 3!’, self::NUM_ERROR);
} else {
$this->result = $this->someVar + $someOtherVar;
echo $this->result . ‘
‘;
}
}

public function otherMethod()
{
if($this->result > 4) {
throw new CustomException(‘The result is greater then 4.’, self::ANY_ERROR);
}
}
}

class CustomException extends Exception
{

public function logError()
{
// Send notification through the server log
if($this->getCode() == Generic::NUM_ERROR){
error_log($this->getMessage(), 0);
}
// Notify administrator by email
else if($this->getCode() == Generic::ANY_ERROR){
error_log($this->getMessage(), 1, ‘sysadmin@domain.com’);
}
}
}

// let’s do it
try
{
$gen = new Generic(3);
$gen->testValue(2);
$gen->otherMethod();
} catch (CustomException $e) {
$e->logError();
}
[/code]

Here we are using our own Exception handler class CustomException to handle the Exception logic.

Definitely, the above script is now much simpler to code and read, due to the fact that all the exceptions are handled by the logError() method. Although the customized exception class is basic in its conception, it’s a useful example aimed at showing in a friendly way how to use Inheritance for deriving child exception handling classes.

PHP has a nifty function called set_exception_handler which sets a user-defined function to handle all uncaught exceptions:

[code lang=”php”]
function myException($exception)
{
echo “Exception: ” , $exception->getMessage();
}

set_exception_handler(‘myException’);

throw new Exception(‘Uncaught Exception occurred’);
[/code]

The PHP Exceptions class can be a very useful and significant tool to aid in the reporting and handling of errors. There is more things to do here, like writing a custom Exception handler for different environments (like development and production) which will output exception messages to screen or log them in some log file.

]]>
https://www.codeforest.net/php-exceptions/feed 2
Building an AJAX currency converter with PHP, jQuery and Google https://www.codeforest.net/building-an-ajax-currency-converter-with-php-jquery-and-google?utm_source=rss&utm_medium=rss&utm_campaign=building-an-ajax-currency-converter-with-php-jquery-and-google Wed, 01 Dec 2010 11:54:20 +0000 https://www.codeforest.net/?p=683 As you may already know, Google has a calculator feature built in their search engine, which can be used to convert measures, currencies, get stock quotes, weather data and many other features. You can see this features explained here.

Why wouldn’t we use it for something useful and build a simple AJAX currency converter using Google currency converter feature? We need some time, jQuery, Google, great music and of course, this tutorial.

So, let’s start. Create new file, call it index.php and make some basic markup for our converter:

<label for="amount">Amount:</label>
<input class="amount" type="text" name="amount" id="amount" value="100" />

<label for="from">From:</label>
<select name="from" id="from">
<option selected="selected" value="EUR">Euro - EUR</option>
<option value="USD">United States Dollars - USD</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="INR">India Rupees - INR</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="DZD">Algeria Dinars - DZD</option>
<option value="ARS">Argentina Pesos - ARS</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="BHD">Bahrain Dinars - BHD</option>
<option value="BRL">Brazil Reais - BRL</option>
<option value="BGN">Bulgaria Leva - BGN</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="CLP">Chile Pesos - CLP</option>
<option value="CNY">China Yuan Renminbi - CNY</option>
<option value="CNY">RMB (China Yuan Renminbi) - CNY</option>
<option value="COP">Colombia Pesos - COP</option>
<option value="CRC">Costa Rica Colones - CRC</option>
<option value="HRK">Croatia Kuna - HRK</option>
<option value="CZK">Czech Republic Koruny - CZK</option>
<option value="DKK">Denmark Kroner - DKK</option>
<option value="DOP">Dominican Republic Pesos - DOP</option>
<option value="EGP">Egypt Pounds - EGP</option>
<option value="EEK">Estonia Krooni - EEK</option>
<option value="EUR">Euro - EUR</option>
<option value="FJD">Fiji Dollars - FJD</option>
<option value="HKD">Hong Kong Dollars - HKD</option>
<option value="HUF">Hungary Forint - HUF</option>
<option value="ISK">Iceland Kronur - ISK</option>
<option value="INR">India Rupees - INR</option>
<option value="IDR">Indonesia Rupiahs - IDR</option>
<option value="ILS">Israel New Shekels - ILS</option>
<option value="JMD">Jamaica Dollars - JMD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="JOD">Jordan Dinars - JOD</option>
<option value="KES">Kenya Shillings - KES</option>
<option value="KRW">Korea (South) Won - KRW</option>
<option value="KWD">Kuwait Dinars - KWD</option>
<option value="LBP">Lebanon Pounds - LBP</option>
<option value="MYR">Malaysia Ringgits - MYR</option>
<option value="MUR">Mauritius Rupees - MUR</option>
<option value="MXN">Mexico Pesos - MXN</option>
<option value="MAD">Morocco Dirhams - MAD</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="NOK">Norway Kroner - NOK</option>
<option value="OMR">Oman Rials - OMR</option>
<option value="PKR">Pakistan Rupees - PKR</option>
<option value="PEN">Peru Nuevos Soles - PEN</option>
<option value="PHP">Philippines Pesos - PHP</option>
<option value="PLN">Poland Zlotych - PLN</option>
<option value="QAR">Qatar Riyals - QAR</option>
<option value="RON">Romania New Lei - RON</option>
<option value="RUB">Russia Rubles - RUB</option>
<option value="SAR">Saudi Arabia Riyals - SAR</option>
<option value="SGD">Singapore Dollars - SGD</option>
<option value="SKK">Slovakia Koruny - SKK</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="KRW">South Korea Won - KRW</option>
<option value="LKR">Sri Lanka Rupees - LKR</option>
<option value="SEK">Sweden Kronor - SEK</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="TWD">Taiwan New Dollars - TWD</option>
<option value="THB">Thailand Baht - THB</option>
<option value="TTD">Trinidad and Tobago Dollars - TTD</option>
<option value="TND">Tunisia Dinars - TND</option>
<option value="TRY">Turkey Lira - TRY</option>
<option value="AED">United Arab Emirates Dirhams - AED</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="USD">United States Dollars - USD</option>
<option value="VEB">Venezuela Bolivares - VEB</option>
<option value="VND">Vietnam Dong - VND</option>
<option value="ZMK">Zambia Kwacha - ZMK</option>
</select>

<label for="to">To:</label>
<select name="to" id="to">
<option value="USD">United States Dollars - USD</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="INR">India Rupees - INR</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="DZD">Algeria Dinars - DZD</option>
<option value="ARS">Argentina Pesos - ARS</option>
<option value="AUD">Australia Dollars - AUD</option>
<option value="BHD">Bahrain Dinars - BHD</option>
<option value="BRL">Brazil Reais - BRL</option>
<option value="BGN">Bulgaria Leva - BGN</option>
<option value="CAD">Canada Dollars - CAD</option>
<option value="CLP">Chile Pesos - CLP</option>
<option value="CNY">China Yuan Renminbi - CNY</option>
<option value="CNY">RMB (China Yuan Renminbi) - CNY</option>
<option value="COP">Colombia Pesos - COP</option>
<option value="CRC">Costa Rica Colones - CRC</option>
<option value="HRK">Croatian Kuna - HRK</option>
<option value="CZK">Czech Republic Koruny - CZK</option>
<option value="DKK">Denmark Kroner - DKK</option>
<option value="DOP">Dominican Republic Pesos - DOP</option>
<option value="EGP">Egypt Pounds - EGP</option>
<option value="EEK">Estonia Krooni - EEK</option>
<option value="EUR">Euro - EUR</option>
<option value="FJD">Fiji Dollars - FJD</option>
<option value="HKD">Hong Kong Dollars - HKD</option>
<option value="HUF">Hungary Forint - HUF</option>
<option value="ISK">Iceland Kronur - ISK</option>
<option value="INR">India Rupees - INR</option>
<option value="IDR">Indonesia Rupiahs - IDR</option>
<option value="ILS">Israel New Shekels - ILS</option>
<option value="JMD">Jamaica Dollars - JMD</option>
<option value="JPY">Japan Yen - JPY</option>
<option value="JOD">Jordan Dinars - JOD</option>
<option value="KES">Kenya Shillings - KES</option>
<option value="KRW">Korea (South) Won - KRW</option>
<option value="KWD">Kuwait Dinars - KWD</option>
<option value="LBP">Lebanon Pounds - LBP</option>
<option value="MYR">Malaysia Ringgits - MYR</option>
<option value="MUR">Mauritius Rupees - MUR</option>
<option value="MXN">Mexico Pesos - MXN</option>
<option value="MAD">Morocco Dirhams - MAD</option>
<option value="NZD">New Zealand Dollars - NZD</option>
<option value="NOK">Norway Kroner - NOK</option>
<option value="OMR">Oman Rials - OMR</option>
<option value="PKR">Pakistan Rupees - PKR</option>
<option value="PEN">Peru Nuevos Soles - PEN</option>
<option value="PHP">Philippines Pesos - PHP</option>
<option value="PLN">Poland Zlotych - PLN</option>
<option value="QAR">Qatar Riyals - QAR</option>
<option value="RON">Romania New Lei - RON</option>
<option value="RUB">Russia Rubles - RUB</option>
<option value="SAR">Saudi Arabia Riyals - SAR</option>
<option value="SGD">Singapore Dollars - SGD</option>
<option value="SKK">Slovakia Koruny - SKK</option>
<option value="ZAR">South Africa Rand - ZAR</option>
<option value="KRW">South Korea Won - KRW</option>
<option value="LKR">Sri Lanka Rupees - LKR</option>
<option value="SEK">Sweden Kronor - SEK</option>
<option value="CHF">Switzerland Francs - CHF</option>
<option value="TWD">Taiwan New Dollars - TWD</option>
<option value="THB">Thailand Baht - THB</option>
<option value="TTD">Trinidad and Tobago Dollars - TTD</option>
<option value="TND">Tunisia Dinars - TND</option>
<option value="TRY">Turkey Lira - TRY</option>
<option value="AED">United Arab Emirates Dirhams - AED</option>
<option value="GBP">United Kingdom Pounds - GBP</option>
<option value="USD">United States Dollars - USD</option>
<option value="VEB">Venezuela Bolivares - VEB</option>
<option value="VND">Vietnam Dong - VND</option>
<option value="ZMK">Zambia Kwacha - ZMK</option>
</select>

<input type="button" name="submit" id="submit" value="Convert" />
<div id="results"></div>

Basically, we have two drop downs with currencies, amount field and a button. Below is a div with id results which will hold our result data.

Now let’s add some jQuery to handle AJAX call and filling result data into our markup:

$(document).ready(function() {

$('#submit').click(function(){

//Get the values
var amount = $('#amount').val();
var from = $('#from').val();
var to = $('#to').val();

var params = "amount=" + amount + "&amp;from=" + from + "&amp;to=" + to;

$.ajax({
    type: "POST",
    url: "convert.php",
    data: params,
    success: function(data){
        $('#results').html(data);
    }
    });
});
});

We are making an ajax call to convert.php and on success filling the data into results div.

And here is convert.php :

// sanitizing input using built in filter_input available from PHP 5.2
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_INT);
$from = filter_input(INPUT_POST, 'from', FILTER_SANITIZE_SPECIAL_CHARS);
$to = filter_input(INPUT_POST, 'to', FILTER_SANITIZE_SPECIAL_CHARS);

// building a parameter string for the query
$encoded_string = urlencode($amount) . urlencode($from) . '%3D%3F' . urlencode($to);

$url = 'http://www.google.com/ig/calculator?hl=en&amp;q=' . $encoded_string;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);

$results = curl_exec($ch);

// this is json_decode function if you are having PHP < 5.2.0 // taken from php.net $comment = false; $out = '$x='; for ($i=0; $i<strlen($results); $i++) { if (!$comment) { if ($results[$i] == '{') $out .= ' array('; else if ($results[$i] == '}') $out .= ')'; else if ($results[$i] == ':') $out .= '=>';
else $out .= $results[$i];
}
else $out .= $results[$i];
if ($results[$i] == '"') $comment = !$comment;
}
// building an $x variable which contains decoded array
echo eval($out . ';');

echo $x['lhs'] . ' = ' . $x['rhs'];

This code is pretty simple and commented, but let me explain some stuff I added.

$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_INT);
$from = filter_input(INPUT_POST, 'from', FILTER_SANITIZE_SPECIAL_CHARS);
$to = filter_input(INPUT_POST, 'to', FILTER_SANITIZE_SPECIAL_CHARS);

Above code is really interesting. It can be used from PHP 5.2.0 and above. The filter_input() function gets external variables (like form input) and filters them.

This function is used to validate variables form insecure sources such as user input.

You can filter several sources:

  1. INPUT_GET
  2. INPUT_POST
  3. INPUT_COOKIE
  4. INPUT_ENV
  5. INPUT_SERVER

It returns the filtered data on success, FALSE on failure or NULL if the variable parameter is not set.

You can expand this to convert a currency and save it to database, so you never ever have to worry about prices on your webshop.

]]>
CakePHP from Scratch: Theming in real life example – Part Two https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-two?utm_source=rss&utm_medium=rss&utm_campaign=cakephp-from-scratch-theming-in-real-life-example-part-two https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-two#comments Sun, 24 Oct 2010 19:57:05 +0000 https://www.codeforest.net/?p=569 Long time no CakePHP on Codeforest. Let me correct that and finally finish the theming tutorial.

If you missed the first one, go to CakePHP theming in real life example – part one and read it carefully. Then return for the second part.

Last time I showed you how easy it is to add theme support to CakePHP and how to adjust xHTML/CSS template to make it work through CakePHP engine.

Today, we will adjust the template a bit by removing some unneeded elements and then adjust the CakePHP views so our application will look and work better.


If you didn’t follow the first part, download the files here.

First, we will remove some elements, so open /app/views/themed/default/layouts/default.ctp and change it to this:

[code lang=”php”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title_for_layout; ?></title>
<?php echo $this->Html->css(‘default’); ?>
</head>

<body>
<!–Header Background Part Starts –>
<div id="header-bg">
<!–Header Contant Part Starts –>
<div id="header">
<?php
echo $html->link($html->image("logo.gif"), array(‘controller’=>’jobs’, ‘action’ => ‘index’), array(‘escape’ => false));
?>
<!– –>
<!–Login Background Starts –>
<div id="login-bg">
<!–Login Area Starts –>
<div id="login-area">
<form action="" method="post" name="Login" id="Login">
<label>Members Login:</label>
<input type="text" name="username" id="username" />
<input type="password" name="pass" id="pass" />
<input type="image" src="images/login-btn.gif" class="login-btn" alt="Login" title="Login" />
<br class="spacer" />
</form>
</div>
<!–Login Area Ends –>
</div>
<!–Login Background Ends –>
<br class="spacer" />
</div>
<!–Header Contant Part Ends –>
</div>
<!–Header Background Part Ends –>
<?php echo $this->element(‘menu’, array(‘cache’ => true)); ?>
<!–Our Company Bacground Part Starts –>
<div id="ourCompany-bg">
<!–Our Company Part Starts –>
<div id="ourCompany-part">
<h2 class="ourCompany-hdr"><?php echo $title_for_layout; ?></h2>
<?php echo $content_for_layout; ?>
<br class="spacer" />
</div>
<!–Our Company Part Ends –>
</div>
<!–Our Company Bacground Part Ends –>
<!–Footer Part Starts –>
<div id="footer-bg">
<!–Footer Menu Part Starts –>
<div id="footer-menu">
<ul class="footMenu">
<li class="noDivider"><a href="#" title="Home">Home</a></li>
<li><a href="#" title="About">About</a></li>
<li><a href="#" title="Services">Services</a></li>
<li><a href="#" title="Support">Support</a></li>
<li><a href="#" title="Chat">Chat</a></li>
<li><a href="#" title="History">History</a></li>
<li><a href="#" title="Contact">Contact</a></li>
</ul>
<br class="spacer" />
<p class="copyright">Copyright?&amp;copy; Package 2007 All Rights Reserved</p>
<p class="copyright topPad">Powered by TemplateKingdom.com</p>
</div>
<!–Footer Menu Part Ends –>
</div>
<!–Footer Part Ends –>
</body>
</html>
[/code]

This way, I removed the Future plans div which we don’t need (at the moment).

Now open your default.css file which is located in /app/views/themed/default/webroot/css/ and find these lines:

[code lang=”css”]
div#ourCompany-bg div#ourCompany-part{
width:922px; margin:0 auto; padding:26px 0 28px 0;
background:url(../img/our-company-bg-pic.jpg) 606px 0 no-repeat;
}
[/code]

and comment the background line like this:

[code lang=”css”]
div#ourCompany-bg div#ourCompany-part{
width:922px; margin:0 auto; padding:26px 0 28px 0;
/*background:url(../img/our-company-bg-pic.jpg) 606px 0 no-repeat;*/
}
[/code]

What we just did? We got rid of the package image on the right of our content div, so we can stretch the content further.

Now, let us adjust the index view for Jobs. Open /app/views/themed/default/jobs/index.ctp, and change it to this:

[code lang=”php”]
<h2 class="ourCompany-hdr">Jobs</h2>
<div class="jobs index">
<?php
if(!empty($jobs)) {
$i = 0;
echo ‘<ul class="jobs_list">’;
foreach ($jobs as $job):
$class = null;
if ($i++ % 2 != 0) {
$class = ‘ class="odd"’;
}
echo ‘<li’.$class.’>’;
echo ‘<h3>’.$this->Html->link($job[‘Job’][‘title’], array(‘action’ => ‘view’, $job[‘Job’][‘id’])).'</h3>’;
echo ‘<div class="details">’;
echo ‘<span class="category">’.$job[‘Job’][‘job_type’].'</span>’;
echo ‘ – ‘ . $job[‘Job’][‘company’];
echo ‘<span class="date">’ . date(‘M d’, strtotime($job[‘Job’][‘created’])) . ‘</span>’;
echo ‘<div>’;
echo ‘</li>’;
endforeach;
echo ‘<ul>’;
} else {
echo ‘No Jobs found …’;
}
?>
[/code]

We are removing links to actions and pagination links (we will style and add these back in next tutorial) and adding some new HTML markup for showing jobs.

Let us add some CSS styles for this markup in /app/views/themed/default/webroot/css/default.css

[code lang=”css”]
ul.jobs_list { width: 565px; }
ul.jobs_list li { margin:10px 0; padding:20px; position:relative; text-shadow:0 0 1px rgba(0, 0, 0, 0.3); -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px;}
ul.jobs_list li:hover, ul.jobs_list li.odd:hover{ background:#ded698; }
ul.jobs_list li.odd{ background:#e4db98; border:1px solid #c7c77c; -moz-box-shadow:0 0 6px rgba(51,51,51,0.1); -webkit-box-shadow:0 0 6px rgba(51,51,51,0.1); box-shadow:0 0 6px rgba(51,51,51,0.1); }
ul.jobs_list li h3 { font-size:21px; margin: 0 0 5px 0; text-shadow:0 0 1px rgba(51, 51, 51, 0.1); }
ul.jobs_list li h3 a { color: #082733; font-family: "Arial Narrow", Arial, Helvetica, sans-serif; }
ul.jobs_list li h3 a:hover { color: #000; text-decoration: underline; }
ul.jobs_list li .details { font-size: 13px; }
ul.jobs_list li .details .category { font-size: 16px; font-weight: normal; color: #70322C; text-transform: uppercase; font-family: "Arial Narrow", Arial, Helvetica, sans-serif; }
ul.jobs_list li .details .date { position:absolute; top:38px; right:20px; }
[/code]

Looking good. Add some jobs by going to http://localhost/jobs/jobs/add (if your cakePHP app is in /wamp/www/jobs) and view the Home page.

Now, we have to change the look of our Job details page. You can see it by clicking on Job’s title. So let’s change the markup. Open /app/views/themed/default/jobs/view.ctp and change it to this:

[code lang=”php”]
<h3 class="jobs_view_h3"><?php echo $job[‘Job’][‘title’]; ?></h3>
<div class="jobs view">
<?php
echo ‘<div class="info">’;
echo ‘<span class="category">’.$job[‘Job’][‘company’].'</span>’;
echo ‘ – ‘ . $job[‘Job’][‘job_type’];
echo ‘<span class="date">’ . date(‘M d’, strtotime($job[‘Job’][‘created’])) . ‘</span>’;
echo ‘</div>’;
echo ‘<div class="job_details">’;
echo ‘<p>’ . nl2br($job[‘Job’][‘body’]) . ‘</p>’;
echo ‘</div>’;

?>
[/code]

And add this to /app/views/themed/webrot/css/default.ctp file:

[code lang=”css”]
.job_details { margin:10px 0; padding:20px; position:relative; text-shadow:0 0 1px rgba(0, 0, 0, 0.3); -moz-border-radius:4px; -webkit-border-radius:4px; border-radius:4px; width: 600px; background:#e4db98; border:1px solid #c7c77c; -moz-box-shadow:0 0 6px rgba(51,51,51,0.1); -webkit-box-shadow:0 0 6px rgba(51,51,51,0.1); box-shadow:0 0 6px rgba(51,51,51,0.1); }
.job_details p { font-size: 15px; line-height: 21px;}

.info { width: 640px; font-size: 13px;}
.info .category { font-size: 16px; font-weight: normal; color: #70322C; text-transform: uppercase; font-family: "Arial Narrow", Arial, Helvetica, sans-serif; }
.info .date { float:right; }

.jobs_view_h3 { font-size:21px; margin: 0 0 5px 0; text-shadow:0 0 1px rgba(51, 51, 51, 0.1); }
[/code]

Now, click on the title of some Job on the front page and you will see the change in your view.

That’s it for now, stay tuned as we continue next time.

Make sure your read our previous tutorials in CakePHP series:

]]>
https://www.codeforest.net/cakephp-from-scratch-theming-in-real-life-example-part-two/feed 6
Making a shoutbox with PHP, MySql and jQuery – Revisited https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery-revisited?utm_source=rss&utm_medium=rss&utm_campaign=making-a-shoutbox-with-php-mysql-and-jquery-revisited https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery-revisited#comments Wed, 13 Oct 2010 19:46:21 +0000 https://www.codeforest.net/?p=517 Recommendation to all my readers who have trouble with their hosting not installing PDO: change your hosting.

This is just an update on a previous tutorial which can be found here.

In that particular tutorial I am using PDO class to manipulate the MySql database. Everything else stays the same, except the code in shout.php file.

For all readers that can not use PDO, change the code in shout.php to this:


/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'root';

/*** mysql password ***/
$password = '';

$dbname = 'demo';

mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);

if($_POST['name']) {
	$name = mysql_real_escape_string($_POST['name']);
	$message = mysql_real_escape_string($_POST['message']);

	$sql = "INSERT INTO shoutbox (date_time, name, message)
	VALUES (NOW(), '".$name."', '".$message."')";

		/*** run the sql statement ***/
		if (mysql_query($sql)) {
			populate_shoutbox();
		}
	}

	if($_POST['refresh']) {
		populate_shoutbox();
	}

	function populate_shoutbox() {
		$sql = "select * from shoutbox order by date_time desc limit 10";
		$rez = mysql_query($sql);
		echo '
		<ul>
		<li style="list-style-type: none;">
		<ul>';</ul>
		</li>
		</ul>
		<ul>
		<li style="list-style-type: none;">
		<ul>while ($row = mysql_fetch_array($rez, MYSQL_ASSOC)) {</ul>
			</li>
			</ul>
			<ul>
			<li style="list-style-type: none;">
			<ul>echo '
			<li>';
			echo '<span class="date">'.date("d.m.Y H:i", strtotime($row['date_time'])).'</span>';
			echo '<span class="name">'.$row['name'].'</span>';
			echo '<span class="message">'.$row['message'].'</span>';
			echo '</li>
			</ul>
			</li>
			</ul>
			';
		}
		echo '

		';
	}

Now your shoutbox is working like a charm using mysql functions.

]]>
https://www.codeforest.net/making-a-shoutbox-with-php-mysql-and-jquery-revisited/feed 4
How to crop an image using jQuery and PHP https://www.codeforest.net/how-to-crop-an-image-using-jquery-and-php?utm_source=rss&utm_medium=rss&utm_campaign=how-to-crop-an-image-using-jquery-and-php https://www.codeforest.net/how-to-crop-an-image-using-jquery-and-php#comments Tue, 12 Oct 2010 21:29:01 +0000 https://www.codeforest.net/?p=510 So, your client uploaded the image into your newly, freshly developed CMS and then called you to yell about distorted image, or image that just does not look good?

That is a well known scenario. Let me explain a bit what we will achieve today. When your client uploads an image, he is taken to an Image edit area where he sees uploaded image and a smaller preview window. He just needs to drag on the larger image to select crop area and press submit.

After that you crop the image using PHP GD functionality and save the new image somewhere on disk.

Cropping refers to the removal of the outer parts of an image to improve framing, accentuate subject matter or change aspect ratio.

I will concentrate mainly on Image editor part, assuming that the client has uploaded the image. So here is our markup:

[code lang=”html”]
<p>Drag on the larger image to select crop area.</p>
<p>
<img id="photo" src="photo.jpg" alt="" title="" style="margin: 0 0 0 10px;" />
</p>
[/code]

So, we have an image tag with id and some inline styling. We will help ourselves with jQuery plugin which will achieve actual client side functionality without coding it from scratch. So, please go to ImgAreaSelect jQuery plugin page and download the plugin.

Extract css and scripts folder in your working folder and put this in your HTML’s head section:

[code lang=”html”]
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
[/code]

Now, you are ready to rock and roll. As I said earlier, we will show a preview to the user, so let us create it using jQuery:

[code lang=”javascript”]
$(document).ready(function () {
$(‘<div><img src="photo.jpg" style="position: relative;" /><div>’) .css({
float: ‘left’,
position: ‘relative’,
overflow: ‘hidden’,
width: ‘100px’,
height: ‘100px’
}) .insertAfter($(‘#photo’));
});
[/code]

What this code does is add a div with size 100x100px and puts our image in it. Let us create some cropping functionality, so change the above code like this:

[code lang=”javascript”]
$(document).ready(function () {
$(‘<div><img src="photo.jpg" style="position: relative;" /><div>’) .css({
float: ‘left’,
position: ‘relative’,
overflow: ‘hidden’,
width: ‘100px’,
height: ‘100px’
}) .insertAfter($(‘#photo’));

$(‘#photo’).imgAreaSelect({
aspectRatio: ‘1:1’,
handles: true,
onSelectChange: preview
});
});
[/code]

We added a call to our plugin, set some parameters and a callback function which will preview our image in a smaller div. This function looks like this:

[code lang=”javascript”]
function preview(img, selection) {
var scaleX = 100 / (selection.width || 1);
var scaleY = 100 / (selection.height || 1);
$(‘#photo + div > img’).css({
width: Math.round(scaleX * 600) + ‘px’,
height: Math.round(scaleY * 400) + ‘px’,
marginLeft: ‘-‘ + Math.round(scaleX * selection.x1) + ‘px’,
marginTop: ‘-‘ + Math.round(scaleY * selection.y1) + ‘px’
});
}
[/code]

Let me explain a bit. Our plugin will send two parameters to out callback function, and image and selection. Selection is an object which contains width, height and borders of our selection.

Then we set scaling variables and by changing CSS properties of our preview div, we are showing the preview image to our user. Go ahead and try this. Awesome, isn’t it?

But, what now? This is useless. As much as it looks great, it does nothing. To provide cropping parameters to PHP file, we must use a form in which the parameters will be stored and then passed to PHP.

So let us add a form below our image, so our markup looks like this:

[code lang=”html”]
<p>
<img id="photo" src="photo.jpg" alt="" title="" style="margin: 0 0 0 10px;" />
</p>

<form action="crop.php" method="post">
<input type="hidden" name="x1" value="" />
<input type="hidden" name="y1" value="" />
<input type="hidden" name="x2" value="" />
<input type="hidden" name="y2" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" />
<input type="submit" value="Crop" />
</form>
[/code]

Now let us adjust our JavaScript so it writes values to our form fields. Complete code looks like this:

[code lang=”javascript”]
function preview(img, selection) {
var scaleX = 100 / (selection.width || 1);
var scaleY = 100 / (selection.height || 1);
$(‘#photo + div > img’).css({
width: Math.round(scaleX * 600) + ‘px’,
height: Math.round(scaleY * 400) + ‘px’,
marginLeft: ‘-‘ + Math.round(scaleX * selection.x1) + ‘px’,
marginTop: ‘-‘ + Math.round(scaleY * selection.y1) + ‘px’
});
}

$(document).ready(function () {
$(‘<div><img src="photo.jpg" style="position: relative;" /><div>’) .css({
float: ‘left’,
position: ‘relative’,
overflow: ‘hidden’,
width: ‘100px’,
height: ‘100px’
}) .insertAfter($(‘#photo’));

$(‘#photo’).imgAreaSelect({
aspectRatio: ‘1:1’,
handles: true,
onSelectChange: preview,
onSelectEnd: function ( image, selection ) {
$(‘input[name=x1]’).val(selection.x1);
$(‘input[name=y1]’).val(selection.y1);
$(‘input[name=x2]’).val(selection.x2);
$(‘input[name=y2]’).val(selection.y2);
$(‘input[name=w]’).val(selection.width);
$(‘input[name=h]’).val(selection.height);
}
});
});
[/code]

Now whenever you complete selection (release a mouse button), callback function writes 4 coordinate values into our form fields. After we click Crop button, this parameters are sent to PHP file crop.php, which will crop the image and save it to disk. This is the code in crop.php:

[code lang=”php”]
// Original image
$filename = ‘photo.jpg’;
//die(print_r($_POST));
$new_filename = ‘photo1.jpg’;

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image, taken from the form
$x1 = $_POST[‘x1’];
$y1 = $_POST[‘y1’];
$x2 = $_POST[‘x2’];
$y2 = $_POST[‘y2’];
$w = $_POST[‘w’];
$h = $_POST[‘h’];

//die(print_r($_POST));

// This will be the final size of the image
$crop_width = 100;
$crop_height = 100;

// Create our small image
$new = imagecreatetruecolor($crop_width, $crop_height);
// Create original image
$current_image = imagecreatefromjpeg($filename);
// resamling (actual cropping)
imagecopyresampled($new, $current_image, 0, 0, $x1, $y1, $crop_width, $crop_height, $w, $h);
// creating our new image
imagejpeg($new, $new_filename, 95);
[/code]

And that’s it. You can see the demo below. Demo only shows client side functionality for security reasons.


If you have any questions, please ask below in comments. I would love to help you.

]]>
https://www.codeforest.net/how-to-crop-an-image-using-jquery-and-php/feed 9