Tag Archives: PHP

How to watermark an image in PHP

Watermarking an image in PHP is very easy. If you follow the code below, you can do it in 2 minutes.

<?php

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
//$SourceFile is source of the image file to be watermarked
//$WaterMarkText is the text of the watermark
//$DestinationFile is the destination location where the watermarked images will be placed

//Delete if destinaton file already exists
@unlink($DestinationFile);

//This is the vertical center of the image
$top = getimagesize($SourceFile);
$top = $top[1]/2;
list($width, $height) = getimagesize($SourceFile);

$image_p = imagecreatetruecolor($width, $height);

$image = imagecreatefromjpeg($SourceFile);

imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);

//Path to the font file on the server. Do not miss to upload the font file
$font = ‘arial.ttf’;

//Font sie
$font_size = 16;

//Give a white shadow
$white = imagecolorallocate($image_p, 255, 255, 255);
imagettftext($image_p, $font_size, 0, 10, $top, $white, $font, $WaterMarkText);

//Print in black color
$black = imagecolorallocate($image_p, 0, 0, 0);
imagettftext($image_p, $font_size, 0, 8, $top-1, $black, $font, $WaterMarkText);

if ($DestinationFile<>”) {

imagejpeg ($image_p, $DestinationFile, 100);

} else {

header(‘Content-Type: image/jpeg’);

imagejpeg($image_p, null, 100);

};

imagedestroy($image);

imagedestroy($image_p);

};

?>

<?php

$SourceFile = ‘image.jpg’;//Source image
$DestinationFile = ‘watermarked/image.jpg’;//Destination path
$WaterMarkText = ‘www.phpHelp.co’;//Watermark text

//Call the function to watermark the image
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

//Display watermarked image if desired
if(file_exists($DestinationFile)){
echo “<img src=\”watermarked/image.jpg\”>”;
echo “<p>The image has been watermarked at ‘”.$DestinationFile.”‘</p>”;
}
?>

Note:

  • This code is being provided to you as a help by http://www.phpHelp.co without any warranty and liability
  • Place all the files in a folder on web server.
  • Do not forget to upload the font file – arial.ttf.
  • Once the image is watermarked, it will be placed in the folder named ‘watermarked’.
  • You might need to give ‘write permission’ or ’777 permission’ to the folder named ‘watermarked’ as the new watermarked image will be written in this folder.

How to upload a file in PHP

The code to upload file in PHP is very simple, but we need to understand the flow which is a below.

  • Browse the file from a local system
  • Upload to server
  • Server keeps it on a temporary path
  • Copy from temporary to permanent path

Create a file upload form

<html>

<body>

<form action=”upload-file.php” method=”post” enctype=”multipart/form-data”>

<label for=”file”>Filename:</label>

<input type=”file” name=”file” id=”file” />

<br />

<input type=”submit” name=”submit” value=”Submit” />

</form>

</body>

</html>

Note:

  • An enctype attribute of the <form> tag has been specified. This attribute  specifies which content-type to use when submitting the form
  • We have used “multipart/form-data” to upload binary data, like the contents of a file, to be uploaded
  • If proper enctype is not provided, upload will not work.
  • File upload is a huge security risk so you must check what type of files are being uploade

Create a file upload script (upload-file.php)

<?php

$my_folder = “./uploads/”;

copy($_FILES["file"]["tmp_name"],$my_folder.$_FILES["file"]["name"]);

echo “File uploaded.”;

?>

This will upload the file to the specified path.

Note:

  • The default file upload size using a browser is usually 2MB so files larger than this size may not upload. You will have to alter the file upload setting on the server.
  • You need to set write permission to the folder where file needs to be upload. In our case, the “uploads” folder needs to have a 777 permission on a linux/unix server.

 

 

How to fill a dropdown combo box in PHP from MySQL database table

This is an easy to use code to select records from MySQL database table and display in dropdown combo box using PHP.

$cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());
$sql = "SELECT field_name FROM table_name";
$rs = mysql_query($sql) or die(mysql_error());
echo "<select>";
while($row = mysql_fetch_array($rs)){
echo "<option value='".$row["field_name"]."'>".$row["field_name"]."</option>";
}mysql_free_result($rs);
echo "</select>";

How to send HTML mail in PHP

To send HTML mail in PHP, you need to use some additional headers. Below is the code to send HTML mail in PHP.

$to = “recipient@domain.com“;
$subject= “Subject of email”;
$message= “This is <h1>HTML</h1> mail.”;
$fromName = “Name of the sender”;
$fromEmail = “sender@domain.com“;

// To send HTML mail, the Content-type header must be set
$headers  = “MIME-Version: 1.0″ . “\r\n”;
$headers .= “Content-type: text/html; charset=iso-8859-1″ . “\r\n”;

// Additional headers
$headers .=”From: $fromName <$fromEmail>”.”\r\n”;

//Mail function
mail($to, $subject, $message, $headers);

 

How to select and display MySQL records data in PHP

This is the simplest code to select and display records from MySQL database table and display in PHP.

$cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
mysql_select_db($db_name,$cn) or die(mysql_error());

$sql = “SELECT field_name FROM table_name”;
$rs = mysql_query($sql) or die(mysql_error());

while($row = mysql_fetch_array($rs)){

echo $field_name = $row["field_name"];
echo “</br>”;

}mysql_free_result($rs);

How to do server to server ftp transfer in PHP

It is quite difficult to transfer web site from one server to another. Here is a solution for server to server ftp transfer.

  • Zip the required files as one file. The zipping feature is usually available in your web hosting control panel’s file manager.
  • Upload the below mentioned script on the source server.
  • Run the script on the source server.
  • This will transfer files from one server to the other.
  • Unzip the files on the destination server.
This script can be used for other purposes as well.

<?php
$server = “ftp.you-server.com”; //address of ftp server (leave out ftp://)
$ftp_user_name = “userName”; // Username
$ftp_user_pass = “passwordHere”; // Password
$source = “/home/folder/public_html/filename.ext”;
$dest = “/public_html/filename.ext”;
$mode=”FTP_BINARY”;
$connection = ftp_connect($server);

$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

if (!$connection || !$login) { die(‘Connection attempt failed!’); }

$upload = ftp_put($connection, $dest, $source, FTP_BINARY);

if (!$upload) { echo ‘FTP upload failed!’; }

ftp_close($connection);
echo “done”;
?>

How to make PHP and MySQL support Arabic, Urdu and charactersets or other foreign languages

To enable your PHP/MySQL script support Arabic or Urdu or other foreign languages, you need to do the following.

In database connection, do the following.

$cn=mysql_connect($db_host,$db_user,$db_password) or die(mysql_error());
//Below is an additional line to enable support for foreign languages.
mysql_query(“SET NAMES utf8″) ;
mysql_select_db($db_name,$cn) or die(mysql_error());

In database, set collation of fields to utf8_general_ci. If you can set collation of databas and tables to utg8_general_ci as well, that will even be better. A sample database script is given below.


– Database: `mytest`

CREATE DATABASE `mytest` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `mytest`;

– ——————————————————–


– Table structure for table `mytable`

CREATE TABLE IF NOT EXISTS `mytable` (
`my_id` int(11) NOT NULL auto_increment,
`my_title` varchar(100) NOT NULL,
PRIMARY KEY (`my_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Now you need to set the charset of the page. Add the following meta tag to the head of you web page. If a charset meta tag already exists, then change it to as below.

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″/>

That’s it!

How to print all the months and years between two dates in PHP

function get_months($date1, $date2) {
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$my = date(‘mY’, $time2);

$months = array(date(‘F Y’, $time1));

while($time1 < $time2) {
$time1 = strtotime(date(‘Y-m-d’, $time1).’ +1 month’);
if(date(‘mY’, $time1) != $my && ($time1 < $time2))
$months[] = date(‘F Y’, $time1);
}

$months[] = date(‘F Y’, $time2);
return $months;
}
echo “<pre>”;
print_r(get_months(’2011-02-1′, ’2012-12-1′));

How to set a cron job in CPanel to call a PHP or Web Page

To set a cron job in Cpanel to call a PHP or web page at any given times, do the following.

Go to Cpanel of your web site.

Log in to it.

Go to Cron Jobs. It is under the section called “Advanced”.

Cron Section

Click on it.

This will take you to a new screen as below.

Set Cron Job

One this screen, select the frequency of your choice from “Common Settings”.

Set Cron Job

In the “Command” text box, type the following syntax where http://www.your-site-name.com is the name of your web site.

curl -s http://www.your-web-site.com/path-to-your-file.php>/dev/null 2>&1

*Note:
Sometimes you configure your web site using .htaccess file to open it with or without “www” when someone types the URL. Make sure to follow the same rule here.