Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, September 14, 2010

PHP Customized Tweeting for Twitter.com

Here is a php script which will let tweet on twitter.com providing your username, password and the message you want to tweet! Since this is a function, you can customize the code anyway you want to.


<?php

function tweet($message, $username, $password)
{
    $context = stream_context_create(array(
        'http' => array(
        'method'  => 'POST',
        'header'  => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)).
                   "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query(array('status' => $message)),
        'timeout' => 5,
    ),
    ));
    $ret = file_get_contents('http://twitter.com/statuses/update.xml', false, $context);
    return false !== $ret;
}

?>


Here is a simple code on using the tweeting function.


<?php

tweet('Php code tweeting!', 'username', 'password');

?>

Tuesday, August 3, 2010

PHP Check if Javascipt is Enabled in Browser

Do you want to check in php if javascript is enabled or not? Now, here is a simple trick in php to check if you have javascript enabled in your browser. The trick is that you have a form with a hidden value which will be set as on if it is submitted by a javascript code. Of course, if the form was not submitted, javascript is disabled in your browser. Please read the comments carefully so that you will be guided with the code.


<?php

// this would not work if no html tags
// you can comment the line after this if you already have a open html and body tag
echo '<html><body>';
// stores the value of js if the form is submitted otherwise off
$js = array_key_exists('js', $_POST) ? $_POST['js'] : '';
// if $js is on, the form was submitted by the javascript submit()
if ($js=="on"){
    echo "Javascript is enabled.";
}
// otherwise display the form and try to submit the form with javascript
else{
    echo '<form name="js_form" method="post"><input type="hidden" name="js" value="on"></form>';
    echo '<script type="text/javascript">document.js_form.submit()</script>';
    echo "Javascript is disabled.";
}
// you can comment the line after this if you already have a close body and html tag
echo '</body></html>';

?>

Monday, August 2, 2010

Dynamic Multiple File Uploads in PHP

I have a PHP script here which will let you specify the folder name and the number of files to be uploaded. Here is the preview.



This program has basic form validation and notifications on entering the data for the file uploads. You are free to copy the code and customize it the way you want it to be. I also provided comments in every lines of code for your guide in tracing or debugging.


<?php

// display open div wrapper
echo "<div class='wrapper'>";
// form for folder name and number of files
$num_form = "<form method=post>
    <table border='0' width='400' cellspacing='0' cellpadding='3' align=center>
    <tr><td>Folder Name</td><td>
    <input type=text name='fname' class='bginput'></td></tr>
    <tr><td>Number of Files</td><td>
    <input type=text name='num_imgs' class='bginput'></td></tr>
    <tr><td><input type=submit name='go' value='GO »' /></td></tr>
    </form>";


// check if the form for folder name and number of files was submitted
if(isset($_POST['go'])){
    //check if both fields were provided data
    if($_POST['fname']=='' || $_POST['num_imgs']==''){
       // notify the data error
       echo "<div class='notify'>Please provide data on both fields.</div>" . $num_form;
    }
    // check if the number of files is valid
    else if(number_format((int) $_POST['num_imgs']) == 0){
       // notify invalid number errors
       echo "<div class='notify'>Invalid number of images inputted.</div>" . $num_form;
    }
    else{
       // get the current directory path
       $thisdir = getcwd();
       // check if the directory already exists
       if(!is_dir($_POST['fname'])){
          // create the directory and change the file permissions
          mkdir(($thisdir.'/'.$_POST['fname']) , 0777);
}
       // form for file uploads
       $form = "<form method=post enctype='multipart/form-data'>";
       $form .= "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
       // input fields depending on the number of files entered
       for($i=1; $i<=$_POST['num_imgs']; $i++){
          $form .= "<tr><td>Image $i</td><td>
          <input type=file name='images[]' class='bginput'></td></tr>";
       }
       $form .= "<tr><td colspan=2 align=center><input type=submit name='add_image' value='Upload Files'></td></tr>";
       $form .= "<input type='hidden' name='fname' value=".$_POST['fname']." />";
       $form .= "</form> </table>";
       // display form file uploads
      echo $form;
    }
}
// check if form file uploads was submitted
else if(isset($_POST['add_image'])){
    // check file name was set
    if(isset($_FILES['images']['name'])){
       // counter for files uploaded
       $ctr = 0;
       // loop through all files to be uploaded
       while(list($key,$value) = each($_FILES['images']['name'])){
          // check if any blank field is entered
          if(!empty($value)){
             // increment counter
             $ctr++;
             // filename stores the value
             $filename = $value;
             // replace blank space with _
             $filename=str_replace(" ","_",$filename);
             //folder name
             $foldername = $_POST['fname'];
             // set upload directory path
             $add = "$foldername/$filename";
             // upload the file to the server
             copy($_FILES['images']['tmp_name'][$key], $add);
          }
       }
       // notify successful uploads
       echo "<div class='notify'>You have successfully uploaded $ctr file(s).</div>";
       echo "<br/><a href='multiple-uploads.php'><button>Upload more files »</button></a>";
    }
}
else{
    // display form for folder name and number of files
    echo $num_form;
}
// display close div wrapper
echo "</div";

?>


I have also here the CSS code for basic formatting of the program.


.wrapper {
    font-family:Verdana, Geneva, sans-serif;
    font-size:12px;
    width:420px;
    margin:0 auto;
    padding: 10px;
    background:#f4f4f4;
}

.notify{
    padding:2px 10px;
    background:#fff;
}

Tuesday, July 27, 2010

Force Download File Using PHP Header Function

Do you want to have a web page that has a script that can make a force download.


I have an example here using PHP to push the file to the browser. To trigger the download of the file, we will use HTML header statements. In PHP, this is possible using header function in passing raw HTML headers to the browser. In this example we will pass the filename in the url for instance - www.domainname.com/download.php?file=filename.zip. Of course, you can customize the codes according to the functionality of your website.


<?php

//path directory of the file
$dir="downloads/";
//cehck if there is a file passed
if (isset($_REQUEST["file"])) {
    //concatinate the directory and the filename
    $file=$dir.$_REQUEST["file"];
    //set HTML headers that must be sent to the browser.
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    //read the file
    readfile($file);
    exit;
}
else {
    //prompt if no file selected
    echo "No file selected";
}

?>


Click here for the php header manual

Monday, July 26, 2010

WampServer - Install PHP Apache MySQL on Windows

If you are a web developer and want to install php, apache and mysql on Microsoft Windows operating system then I highly recommend you to use Wampserver. WampServer 2 is the new version of WAMP5. You just have to download the latest stable version at Wampserver Download Page. Just Click "DOWNLOAD WampServer" and the download window will appear shortly and then hit "Save File".


After the download is completed, locate the executable file and double click it to start the installation process. Just follow the usual installation steps on windows because everything is automatic. When the installation is finished, run the wampserver executable file. Just click the Wampserver trayicon to manage your server and its settings.


A "www" directory is created (generally c:\wamp\www) when you installed WampServer. Create a directory inside "www" for your project and where you should place your PHP files.
To view all your projects on the browser, click on the link "Localhost" in the WampServer menu or open the http://localhost address.



Now, you are ready to create your projects with php running in apache with mysql for the database.

Friday, July 23, 2010

Create Zip Archive File using PHP ZipArchive

Do you want to place certain files on a zip archive file? In php this is possible using the ZipArchive class - a file archive, compressed with Zip. Below is the sample code program of this functionality.


<?php

//sample files in an array to be compressed
$files = array(
    'images/img1.png',
    'images/img2.png',
    'images/img3.png',
    'images/img4.png',
    'images/img5.png'
);

//returns true if creation succeed and false if zip creation failed
$result = create_zip($files,'my-archive.zip');

//function that creates a compressed zip file
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //variable declaration
    $valid_files = array();
    //if files are valid
    if(is_array($files)) {
        //loops and check each file
        foreach($files as $file) {
            //check if file exists and store in array
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //check if there are valid files
    if(count($valid_files)) {
       //create the zip archive object
       $zip = new ZipArchive();
       if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE :     ZIPARCHIVE::CREATE) !== true) {
           return false;
       }
        //add files to the object
        foreach($valid_files as $file) {
          $zip->addFile($file,$file);
        }

       //close the zip after adding the files
        $zip->close();

        //check if the destination file exists
        return file_exists($destination);
    }
    else {
        return false;
    }
}

?>