Coding Cluster - using asp.net, c#, mvc 4, iphone, php, ios, javascript, in asp.net mvc 3 & more
 
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

How to generate a random password in php

Wednesday

PHP: Generate a random password:
                            The followinf function will generate a random password. We just give total length of the password as input. For this we will print the function value, specifying the length of the password to be generated.

Code

<?php
<!--  -->
function generateRandomPassword($cnt)
{
// characters to be included for randomization, 
$chars= str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@#%$*');

// Here specify the 2nd parameter as start position, it can be anything, default 0
return substr($chars,0,$cnt);
}
// Usage 
$password = generateRandomPassword(7); // specify the length of the generated password
echo "Your random password is:".$password; 
<!-- --> ?>

Get File Size in B/KB/MB/GB/TB using php

Tuesday

Get File Size using php
                              The following PHP code snippet used to Get File Size in B/KB/MB/GB/TB.

Code:

<?php
/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function findFilesize($file,$digits = 2) {
       if (is_file($file)) {
               $filePath = $file;
               if (!realpath($filePath)) {
                       $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
       }
           $fileSize = filesize($filePath);
               $sizes = array("TB","GB","MB","KB","B");
               $total = count($sizes);
               while ($total-- && $fileSize > 1024) {
                       $fileSize /= 1024;
                       }
               return round($fileSize, $digits)." ".$sizes[$total];
       }
       return false;
}
?>

Get value stored in Cookie in php

Saturday

Get value from  Cookie in PHP:

                                                  By using  the following code you can retrieve the value stored in cookie. Here I'm using the global variable $_COOKIE to get the value stored in cookies.

Code:
<?php 
setcookie( "cookiename", "cookievalue", time()+60000);
$yourCookie = $_COOKIE["cookiename"];
if ( isset( $yourCookie ) )
   echo "<p>Your cookie value is - $yourCookie</p>";
else
   echo "<p>Nothing in your cookie.</p>";
?>

Calculating difference between two dates in PHP

Friday

Calculating difference between two dates using PHP:
The following code used to calculating the difference between two dates in PHP without using DateTime class.

                     The strtotime() function parses date wrote as as string to UNIX timestamp. After substracting two timestamps, $diff is equal to number of seconds between these two days, we wanted to have difference in days, so we need to make additional arithmetic operations and return result. The most important here is use of the same timezone.

function dateDifference($dt1, $dt2, $timeZone = 'GMT')
{
    $tZone = new DateTimeZone($timeZone)
;
    $dt1 = new DateTime($dt1, $tZone)
;
    $dt2 = new DateTime($dt2, $tZone)
;

    $ts1 = $dt1->format('Y-m-d')
;
    $ts2 = $dt2->format('Y-m-d')
;

    $diff = abs(strtotime($ts1)-strtotime($ts2))
;

    $diff/= 3600*24
;

    return $diff
;
}

echo date
Difference('2011-11-11', '2011-12-12');

File Upload Using PHP

Wednesday


PHP File Upload:
                             The following HTML form used for uploading files. The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded.

The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field
<html>
<body>
<form action="fileUpload.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>

The "fileUpload.php" file contains the code for uploading a file:

                                           By using the global PHP $_FILES array you can upload files from a client computer to the remote server.
The first parameter is the form's input name and the second index can be either "name", "type", "size", "tmp_name" or "error". Like this:

  • $_FILES["file"]["name"] - the name of the uploaded file
  • $_FILES["file"]["type"] - the type of the uploaded file
  • $_FILES["file"]["size"] - the size in bytes of the uploaded file
  • $_FILES["file"]["tmp_name"] - the name of the temporary copy of the file stored on the server
  • $_FILES["file"]["error"] - the error code resulting from the file upload

                        This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.

fileUpload.php
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 100000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored to: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file format";
  }
?>
The above code checks if the file already exists, if it does not, it copies the file to the specified folder.

How to connect to MySQL database using PHP

Create a Connection to a MySQL Database:

                                                    Before you can get content out of your MySQL database, you must know how to establish a connection to MySQL from inside a PHP script. The following code explained the following concepts,


1. Connection to the database
2. Select a database
3. Execute the query
4. Fetch tha data
5. Close the connection


Sample Code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";

//connection to the database

 $dbhandle = mysql_connect($hostname, $username, $password)
 or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a database to work with

$selected = mysql_select_db("examples",$dbhandle)
  or die("Could not select examples");

//execute the SQL query and return records

$result = mysql_query("SELECT id, model,year FROM cars");

//fetch tha data from the database

   while ($row = mysql_fetch_array($result)) {
   echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ".
   $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>

Sending Email with Attachment in PHP

Sending Email with Attachment:
                                      To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:

<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash

$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks

$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>






As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

 
 
 

RECENT POSTS

Boost

 
Blogger Widgets