RSSAll Entries Tagged With: "PHP"

Set Credentials using security.yml in Symfony 1.4

Symfony provides some cool configuration features that would allow you to minimize your coding part .  In this tutorial i would explain how to configure security.yml to set credentials for a different users.

Create a class file named account.class.php under apps/frontend/lib folder with content .The class below checks weather the user is admin and sets his credential as ‘admin’ . Update the class file as your requirement .

[php]

class account
{
public static function getLoginAdmin($username, $password)
{
// code to check for username and password in a particular table : ORM is doctrine
$usr = Doctrine::getTable(‘TableName’)
->createQuery(‘a’)
->where(‘a.adminuser = ?’,$username)
->andWhere(‘a.password = ?’,$password)
->execute();

$login_user = count($usr);

if($login_user > 0)
{
sfContext::getInstance()->getUser()->setAuthenticated(true);
sfContext::getInstance()->getUser()->addCredential(‘admin’);

return true;
}
else
{
return false;
}
}
public static function LogoutSession()
{
sfContext::getInstance()->getUser()->setAuthenticated(false);
sfContext::getInstance()->getUser()->clearCredentials();

sfContext::getInstance()->getUser()->getAttributeHolder()->removeNamespace(‘admin’);

return true;
}
}

[/php]

And in login action file after receiving username and password call the library function as shown below

[php]

$login_flag = account::getLoginAdmin($this->username,$this->password);

[/php]

and if $login_flag returns true you have successfully logged in else enter username or password is invalid .

You have done with the class file and action page . Now you need to configure security.yml .

Create a folder named config inside a module ( say for eg : under admin module ) with security.yml in it and paste the following code .

[html]

index:
is_secure: true
credentials: admin

[/html]

Now admin module can be accessed only by one with ‘admin’ credential .

You can flush the credential as

[php]

$logout = account::LogoutSession();

[/php]

You are done !

Thumbnail creation using uploadify.php

Hello friends i came across a good jquery flash file up-loader here . Do use it its simple and powerful .

The next main thing was generation of thumbnail using the same flash uploader after some homework found a solution for it . Do some simple updations in your existing code .

1. Create a folder named “thumbnails” under the upload folder .

2. Replace the code in uploadify.php [you can find it under scripts folder] with the following code .

[php]

if (!empty($_FILES))
{
$tempFile = $_FILES[‘Filedata’][‘tmp_name’];
$targetPath = $_SERVER[‘DOCUMENT_ROOT’] . $_REQUEST[‘folder’] . ‘/’;
$targetFile =  str_replace(‘//’,’/’,$targetPath) . $_FILES[‘Filedata’][‘name’];
move_uploaded_file($tempFile,$targetFile);
echo "1";
}
$imgsize = getimagesize($targetFile);
switch(strtolower(substr($targetFile, -3)))
{
case "jpg":
$image = imagecreatefromjpeg($targetFile);
break;
case "png":
$image = imagecreatefrompng($targetFile);
break;
case "gif":
$image = imagecreatefromgif($targetFile);
break;
default:
exit;
break;
}

$width = 80; //New width of image
$height = $imgsize[1]/$imgsize[0]*$width; //This maintains proportions

$src_w = $imgsize[0];
$src_h = $imgsize[1];

$picture = imagecreatetruecolor($width, $height);
imagealphablending($picture, false);
imagesavealpha($picture, true);
$bool = imagecopyresampled($picture, $image, 0, 0, 0, 0, $width, $height, $src_w, $src_h);

if($bool)
{
switch(strtolower(substr($targetFile, -3)))
{
case "jpg":
header("Content-Type: image/jpeg");
$bool2 = imagejpeg($picture,$targetPath."thumbnails/".$_FILES[‘Filedata’][‘name’],80);
break;
case "png":
header("Content-Type: image/png");
imagepng($picture,$targetPath."thumbnails/".$_FILES[‘Filedata’][‘name’]);
break;
case "gif":
header("Content-Type: image/gif");
imagegif($picture,$targetPath."thumbnails/".$_FILES[‘Filedata’][‘name’]);
break;
}
}

imagedestroy($picture);
imagedestroy($image);

echo ‘1’;

[/php]

You are done ! Hope it helped you .

Update Timeline using Jquery as in Twitter | Live Twitter Search using PHP

Hello friends back to blogging after sometime .  Recently i got a mail from one of my friend asking about how can we update a timeline using an animation effect as in twitter timeline .

Here i am giving you a code in jquery that would help you to implement the same .

The package contains 3 main files . 1.index.php 2.search.php and a 3.twitterapi.php

code within index.php

[html]

<!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=ISO-8859-1" />
<title>Twitter Search Flow</title>
<style type="text/css">
.woork{
color:#444;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
width:600px;
margin: 0 auto;
}
.twitter_container{
color:#444;
font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
width:450px;
margin: 0 auto;
background:#DEDEDE;
padding:8px;
}
.twitter_container a{
color:#0066CC;
}
.twitter_status{
height:60px;
padding:6PX;
border-bottom:solid 1px #DEDEDE;
background:#FFF;
}
.twitter_image{
float:left;
margin-right:14px;
border:solid 2px #DEDEDE;
width:50px;
height:50px;
}
.twitter_small{
font-size:11px;
padding-top:4px;
color:#999;
display:block;
}
#twitter-results{padding-top:8px;}
</style>
<script type="text/javascript" src="jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var twitterq = ”;

function displayTweet(){
var i= 0;
var limit = $("#twitter-results > div").size();
var myInterval = window.setInterval(function () {
var element =  $("#twitter-results div:last-child");
$("#twitter-results").prepend(element);
element.fadeIn("slow");
i++;
if(i==limit){
window.setTimeout(function () {
clearInterval(myInterval);
});
}

},2000);
}

$("form#twittersearch").submit(function() {
twitterq = $(‘#twitterq’).attr(‘value’);

$.ajax({
type: "POST",
url: "search.php",
cache: false,
data: "twitterq="+ twitterq,
success: function(html){
$("#twitter-results").html(html);
displayTweet();
}
});
return false;
});

});

</script>
</head>

<body>
<div>
<strong>Try to search something on twitter:</strong><br />
<br/>
<form id="twittersearch" method="post" action="">
<input name="twitterq" type="text" id="twitterq" />
<button type="submit">Search</button></form>
<div id="twitter-results"></div>
</div>
</body>
</html>

[/html]

code within search.php

[php]

include(‘twitterapi.php’);

if($_POST[‘twitterq’]){
$twitter_query= $_POST[‘twitterq’];
$search = new TwitterSearch($twitter_query);
$results = $search->results();

foreach($results as $result){
echo ‘<div style="display:none;">’;
echo ‘<img src="’.$result->profile_image_url.’">’;
$text_n=toLink($result->text);
echo $text_n;
echo ‘<span>’;
echo ‘<strong>From:</strong> <a
href="http://www.twitter.com/’.$result->from_user.’">’.$result->from_user.'</a>:
‘;
echo ‘<strong>at:</strong> ‘.$result->created_at;
echo ‘<input type="hidden" value="’.$result->id.’"></input>’;
echo ‘</span>’;
echo ‘</div>’;
}
}

[/php]

Download the source package for jquery.js and twitterapi.php .

Rewrite .php extension with .html using .htaccess | URL rewriting using .htaccess.

I had to implement URL rewriting in my last project . After some browsing found that it can be implemented using .htaccess file .

Ok fine . we can start from the basics of creating a .htaccess file .

In windows one cannot create .htaccess file directly . You can either create a “htaccess” file on windows upload it and rename it to “.htaccess” or create a notepad file and save it as “.htaccess” file .

Begin Rewriting

Whenever you use mod_rewrite (the part of Apache that does all this magic), you need to do

[html]
Options +FollowSymlinks
RewriteEngine on
[/html]

before any ReWrite rules. note: +FollowSymLinks must be enabled for any rules to work, this is a security requirement of the rewrite engine. Normally it’s enabled in the root and you shouldn’t have to add it, but it doesn’t hurt to do so, and I’ll insert it into all the examples on this page, just in case*.

The next line simply switches on the rewrite engine for that folder. if this directive is in you main .htaccess file, then the ReWrite engine is theoretically enabled for your entire site, but it’s wise to always add that line before you write any redirections, anywhere.

Simple Rewriting

You can rewrite all .php files with .html tag . Use following code to implement the same .

[html]
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.html $1\.php
[/html]

Now try .html with .php extension . ie , help.html would call help.php

Reading remote files using PHP | Manage remote files | Read data from URL using PHP

Recently I had to do a project in which the task to read files from a remote server. On browsing on net I found different resources , I am putting it together for your reference.

Getting the title of a Remote Page

Use the following code to scrap page title .

[php]
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
/* This only works if the title and its tags are on one line */
if (eregi ("(.*)", $line, $out)) {
$title = $out[1];
break;
}
}
echo "Page Title : ".$title;
fclose($file);
?>
[/php]

Reading the contents of a file into Array

File function returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Each line in the resulting array will include the line ending, so you still need to use rtrim() if you do not want the line ending present.

[php]

<?php
// Get a file into an array.  In this example we’ll go through HTTP to get
// the HTML source of a URL.
$lines = file(‘http://www.example.com/’);

// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo “Line #<b>{$line_num}</b> : ” . htmlspecialchars($line) . “<br />\n”;
}
?>

[/php]

Reading the contents of a file into a string
Functions file_get_contents() returns the file in a string. This is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

[php]

<?php
$content_string = file_get_contents(‘www.example.com/products.html’);
?>

[/php]

Storing data on a remote server

You can also write to files on an FTP server (provided that you have connected as a user with the correct access rights). You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail. You need to specify the username and password within the URL, such as ‘ftp://user:password@ftp.example.com/path/to/file’.

[php]

<?php
$file = fopen (“ftp://ftp.example.com/incoming/outputfile”, “w”);
if (!$file) {
echo “<p>Unable to open remote file for writing.\n”;
exit;
}
/* Write the data here. */
fwrite ($file, $_SERVER[‘HTTP_USER_AGENT’] . “\n”);
fclose ($file);
?>

[/php]

Implement captcha in PHP

As you know spamming can be a huge problem. You can prevent spamming in different ways. Either log the spammer ip and block it from further updates or you may use a captcha in your form. In this tutorial i would explain how to implement recaptcha using php. “reCAPTCHA is a free CAPTCHA service that helps to digitize books, newspapers and old time radio shows. Check out our paper in Science about it”.

1. GoTo recaptcha.net

Click on “use reCAPTCHA on your site” and follow the registration steps. Once you are done, click on “My Account” in the left menu. a button appears.

Add a New Site

Click on it and add your website. When you finish, you will be redirected to a page contains your “Public Key” and your “Private Key”. Keep in your mind that your Private Key is must be kept as secret, so don’t share it with everyone. Also you need to have a key for every website. No matter if it is a sub-domain.

The package contains 2 files index.php and a lib file [recaptchalib.php]

index.php

[html]

<html>
<body>
<div align="center" style="margin-top:30px;">
<form action="" method="post">
<?php

require_once(‘recaptchalib.php’);
$publickey = "XXXXXXXXXXXX";
$privatekey = "XXXXXXXXXXXX";

# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;

# are we submitting the page?
if ($_POST["submit"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);

if ($resp->is_valid) {
echo "You got it!";
# in a real application, you should send an email, create an account, etc
} else {
# set the error code so that we can display it. You could also use
# die ("reCAPTCHA failed"), but using the error message is
# more user friendly
echo "You Missed it. Try it Again.";
$error = $resp->error;
}
}
?>
<br/>
<?php echo recaptcha_get_html($publickey, $error); ?>
<input type="submit" name="submit" value="submit" />
</form>
</div>
</body>
</html>
[/html]

Note : Replace ‘XXXXXXXXXXX’ with your Private and Public Key.

You are done !

Convert Text to Image using PHP.

This tutorial would help you to convert a string to image using php. I have named the function as text2image as it makes some sense.

The main functions used in the following function is

1. imagecreate
2. imagecolorallocate
3. imagecolorallocate
4. imagestring
5. imagepng

The following code creates output

[php]
function text2image($string) {
// create a 100*30 image
$im = imagecreate(197, 30);

// black background and white text
$bg = imagecolorallocate($im, 0, 0, 0);
$textcolor = imagecolorallocate($im, 255, 255, 255);

// write the string
imagestring($im, 5, 10, 5, $string, $textcolor);

// output the image
header("Content-type: image/png");
return imagepng($im);
}

echo text2image(‘http://www.infoplotter.com’);

[/php]

Hope it helped you !

Image Protection Code using PHP | HTML | Javascript

Hai All ,

I implemented image protection in one of my latest work. Its pretty simple and effective so i am sharing with you.

Check out the demo and try the following :-

1. Try dragging the image to the Navigation Bar.

2. Right Click and Try viewing the image.

3. Take the source and click on the src of img tag.

Step 1 : Create a page named index.php

[php]
<?php
$page = $_REQUEST[‘p’];
if($page == ‘sImage’)  {  include(‘image.php’); }
else { echo ‘<img src="index.php?p=sImage" />’; }
?>
[/php]

Step 2 : Create a page named image.php

[php]
<?php
$imageName = "logo.jpg";
$img1 = imagecreatefromjpeg($imageName);
$img2 = imagejpeg( $img1 );
?>
[/php]

Note : You can save the image by right clicking -> Save Image as [ you can protect that too by disabling right click action using javascript :) ]

There are many other ways to hack the code. But this would save you from Newbies.

You are done !

Symfony | Doctrine | Error | SQLSTATE[HY000]: General error: 1005 Can’t create table XXX.#sql-818 _1′ (errno: 121). Failing Query:” ALTER TABLE xxx ADD CONSTRAINT …. FOREIGN KEY (xyz) REFERENCES XXX(id) ON DELETE CASCADE”

Symfony is a web application framework written in PHP which follows the model-view-controller (MVC) paradigm . A symfony developer may use Object-Relational Mapping (ORM) – Propel or Doctrine . The earlier version of symfony supported propel and i was using it . But in updated versions symfony supported Doctrine and was forced to update my skills in ORM .

Configuring symfony is pretty simple and model and sql was generated successfully . But on executing the command line argument to insert sql .

[php]

symfony doctrine:insert-sql

[/php]

i got an error :

SQLSTATE[HY000]: General error: 1005 Can’t create table XXX.#sql-818_1′ (errno: 121). Failing Query:” ALTER TABLE xxx ADD CONSTRAINT …. FOREIGN KEY (XYZ) REFERENCES XXX(id) ON DELETE CASCADE”

The error got on my nerves and couldn’t figure out what was it all about . But i was sure its something related to foreign key and after some research i got a fix for it and i am sharing it with you .

There is an issue with your ID columns. Normally this has to do with the foreign key and primary keys having different length constraints. Your fix:

Make sure that the length constraints match. If you aren’t specifying a length, you can simply remove the ID field from your schema.yml, and let Doctrine create it for you, or if you want to be explicit, you can set a length and make sure it is matched in the related foreign key field.

MetroUsers:
actAs: { Timestampable: ~ }
columns:
username: { type: string(255), notnull: true, unique: true }
password: { type: string(255), notnull: true }
hash: { type: string(255), notnull: true }

MetroUserDetails:
actAs: { Timestampable: ~ }
columns:
metro_user_id: { type: integer, notnull: true }
ref_from: { type: string(255), notnull: true, unique: true }
mobilenumber: { type: string(255), notnull: true }
is_mobile_valid: { type: boolean, notnull: true, default: 0 }
email_id: { type: string(255), notnull: true }
relations:
MetroUsers: { onDelete: CASCADE, local: metro_user_id, foreign: id, foreignAlias: MetroUserDetail }

Here id is generated automatically for MetroUsers and make sure that metro_user_id is of type integer .