Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Wednesday 10 August 2016

Using jQuery FormData to include files when making POST request

In this example I create a form, with a text, and file input field. When I submit the form, contents from all input fields are submitted through the 'FormData' class. The results from the called script are returned to a div. Finally, the fields are then cleared.
<html>
<head>
    <title>jQuery File Upload</title>
</head>
<body>
    <form action="upload.php" method="POST" enctype="multipart/form-data">
        <input type="text" name="myname" />
        <input type="file" name="fileinfo" multiple="" />
        <button type="submit">Submit</button>
    </form>
    <div id="result"></div>
    <script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
    <script>  
    (function()
    {
        $('form').on('submit', function(e)
        {
            var theDiv = $('div#result');
            var thisForm = $(this);
            var action = thisForm.attr('action');
            var method = thisForm.attr('method');
            $.ajax(
            {
                url: action,
                type: method,
                data: new FormData(this),
                processData: false,
                contentType: false
            }).done(function(datareceived)
            {
                thisForm.find('input, textarea').val('');
                theDiv.html(datareceived);
            });
            e.preventDefault();
        });
    })();
    </script>
</body>
</html>

To test if it works I use upload.php. See
<?php
$str = NULL;
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $file['name']) == FALSE)
    {
        $str .= $file['name'].' not uploaded<br />';
    }
}
$str .= '<br />POST items include : <br />';
foreach($_POST as $postitem => $value)
{
    $str .= 'Name : '.$postitem.' Value : '.$value.'<br />';
}
echo $str;
?>

Wednesday 1 October 2014

jQuery file upload in Twitter Bootstrap modal

For a recent project, I have needed to add a file upload form to a modal. This has required me to perform the upload through jQuery in order to avoid the page reloading when the form is submitted.
To accomplish this I have used the jQuery form plugin at http://malsup.com/jquery/form/.
Here's the code with the important bits highlighted in red.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap 101 Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <style>
    body
    {
    padding-top:2em;
    }
    </style>
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
  <div class="container">
  <div class="col-md-6">
  <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
 
  </div>
  <div id="myResult" class="col-md-6 alert alert-success" role="alert">
 
  </div><!-- myResult -->
  </div><!-- .container -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
   <div class="modal-content">
     <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
       <h4 class="modal-title">Modal title</h4>
     </div>
     <div class="modal-body">
       <form action="uploadfile.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="file">File input</label>
<input type="file" name="file">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
     </div>
   </div><!-- /.modal-content -->
 </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.50/jquery.form.min.js"></script>
    <script>
(function()
{
$('#myResult').hide();
$('form').submit(function()
{
$(this).ajaxSubmit(
{
url:$(this).attr('action'),
method:$(this).attr('method'),
target: '#myResult'
});
$('#myModal').modal('hide');
$('#myResult').show();
return false;
});
})();
</script>
  </body>
</html>

Friday 17 June 2011

Using PHP to create a dynamic page navigation based on filenames

Here is the problem. You create a bunch of pages. You want to highlight the current page within the navigation. You don't want to manually change the navigation elements to each page.

See demo.

In the example below I create an associative array which contains two elements:

  1. The name of the page which the navigation points to.
  2. The name which should appear in the navigation.

I then grab the filename of the of the current page in the browser.
I then traverse the associative array, each time comparing the filename against the current file shown in the browser, each time creating an anchor using the values.

If array filename and current page filename are the same, then I add a CSS ID to the anchor tag.

You will need to write a little CSS to highlight the current page anchor such as:

nav a#activeMenuItem
{
background:#EEEEEE;
}


But other than that, it works like a charm. Have fun!


<nav>
<?php
$navArray = array('index.php'=>'home', 'services.php'=>'services','portfolio.php'=>'portfolio','contact.php'=>'contact');
$fileName = substr(strrchr($_SERVER['SCRIPT_NAME'],47),1);
foreach($navArray as $fname => $linktitle)
{
echo '<a href="'.$fname.'"';
if($fname==$fileName)
{
echo ' id="activeMenuItem"';
}
echo '>'.$linktitle.'</a>';
}
?>
</nav>

Thursday 18 November 2010

PHP to get current file name without the extension

This little function will return the file name which calls it minus the .php extension.

<?php

function getCurrentFile()
{
    $currentFile = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $currentFile);
    $currentFile = substr($parts[count($parts) - 1],0,-4);
    return $currentFile;
}
?>

How to get all the content from a directory using PHP

I've been developing a small CMS. It solves a small problem. Some of our customers would like to edit small amounts of text on a page. I don't want to create a CMS database for this. I just want to use text files. There is a tiny CMS which does this, but your website has to be in root, there is an install and it's a bit of a pig to configure.
My CMS is much simpler than that.
Anyway, to cut a long story short I created a PHP function for it which I wanted to share. It takes a directory name as a parameter then looks at that directory  and reads all the files within it. Obviously missing out those ugly  . and .. at the beginning. Manipulate at will.


<?php
function getDirContents($dirLoc)
{  
    foreach(array_slice(scandir($dirLoc),2) as $fileEntry)
    {
        echo file_get_contents($dirLoc.'/'.$fileEntry);
    }
}
?>

Friday 1 October 2010

Send a file attachment and send as an e-mail in PHP

This is not the full story. First you need a form to collect the data and put it in a field (in this case) called myValue.

This piece of code takes the field contents, creates a text file and sends it.


<?php
    $filetitle = "testFile.txt";  
    $data = $_POST["myValue"]);
    $to = 'jimmy@googlemail.com';
    $subject = 'My subject';  
    $filetype = "text/plain";  
    $email_from = "jammy@googlemail.com";  
    $headers = "From: ".$email_from;      
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
  
    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";
  
    $email_message .= "This is a multi-part message in MIME format.\n\n" .
    "--{$mime_boundary}\n" .
    "Content-Type:text/html; charset=\"iso-8859-1\"\n" .
    "Content-Transfer-Encoding: 7bit\n\n" .
    $email_message . "\n\n";
  
    $data = chunk_split(base64_encode($data));
  
    $email_message .= "--{$mime_boundary}\n" .
    "Content-Type: {$filetype};\n" .
    " name=\"{$filetitle}\"\n" .  
    "Content-Transfer-Encoding: base64\n\n" .
    $data . "\n\n" .
    "--{$mime_boundary}--\n";
  
    $ok = @mail($to, $subject, $email_message, $headers);

    if($ok)
    {
        echo "It worked";
    }
    else
    {
        die("It failed");
    }
?>