Hi every one
I am trying to upload a file on server but it is not uploading and always giving an error
HEre is code. Please help. Its urgent

<?php session_start();

if(!session_is_registered(username)){

header("location:login.php");

}



if($_REQUEST['title'] != '' && $_REQUEST['type']!='' && $_REQUEST['category'] != '' && $_REQUEST['sub']!=''&&$_REQUEST['elm3'] != '')

    {

        require("db.php");



$cat = $_REQUEST['category'];



$title = $_REQUEST['title'];



$sub=$_REQUEST['sub'];



$author = $_SESSION['username'];



$type =  $_REQUEST['type'];



$desc =  $_REQUEST['elm3'];



$arr = explode(".", $filename);

        

$ext = $arr[count($arr) - 1];















$msg = "";

                                            $fname = $_FILES['file']['name']; 

                                            $arr = explode(".", $fname);

                                            $ext = $arr[count($arr) - 1];

                                            $size = filesize($_FILES['file']['tmp_name']);

                                            print_r($_FILES);

                                            if ($size > 70 * 1024 * 1024) {

                                                $msg .= '<h1>You have exceeded the size limit!</h1>';

                                            } else if($ext != "zip" && $ext!= "rar" && $ext!= "docx" && $ext!= "doc" && $ext!= "ppt" && $ext!= "pptx") {

                                                $msg .= "<h2>Only These Files Allowed</h2><br/><h3>Zip, rar , Doc, Docx, ppt, pptx</h3>";

                                            } else {

                                                array_pop($arr);

                                                $filename = implode('.', $arr) ."_". time().".".$ext;

                                                $name = preg_replace('~[^\w-\.]~', '-', $_FILES['file']['name']);

                                                if($type == "Book") {

                                                    // uploaded

                                                    if(move_uploaded_file($_FILES["file"]["tmp_name"],"books/" . $name))



{

             $loc = "books/$name";

            echo "Successfully uploaded";

}

else {

                                                    $msg .= "<h1>Unable to upload file</h1>";

                                                }            

                                                } 

                                                else {

                                                    if(move_uploaded_file($_FILES["file"]["tmp_name"],"notes/" . $name))



{

             $loc = "notes/$name";

            echo "Successfully uploaded";

}

else {

                                                    $msg .= "<h1>Unable to upload file</h1>";

                                                }    

                                                    }

                                                

                                            }

                                            if(strlen($msg) < 1) {

                                                

            mysql_query(" INSERT INTO `links` (`title`,`maj_cat`,`author`,`sub_cat`,`link`,`description`) VALUES ('$title','$category','','$sub','$loc','$desc')") or die(mysql_error());

            $_SESSION['success'] = "File has successfully uploaded"; ?>

            <script type="text/javascript">

alert("Thanks for sharing knowledge");

window.location = "uploadNotes.php";

</script>

<?php

                                        ?>

                                            <span style="color: green; font-size: 20px;">Your code successfully added!!!</span>

                                        <?php

                                            } else {

                                                echo $msg;

                                            }

                                    

         

    }



?>

<!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>

<title>PageStorm</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href="css/style.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="css/coin-slider.css" />

<link rel="stylesheet" media="screen" href="css/superfish.css" />

<link rel="stylesheet" media="screen" href="css/superfish-navbar.css" />

<script type="text/javascript" src="js/cufon-yui.js"></script>

<script type="text/javascript" src="js/cufon-marketingscript.js"></script>

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<script type="text/javascript" src="js/script.js"></script>

<script type="text/javascript" src="js/coin-slider.min.js"></script>

<script type="text/javascript" src="js/paging.js"></script>

<script src="js/hoverIntent.js"></script>

<script src="js/superfish.js"></script>

<!--Tiny MCE Editor-->



<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>

<script type="text/javascript">

    // Default skin

    tinyMCE.init({

        // General options

        mode : "exact",

        elements : "elm1",

        theme : "advanced",

        plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,autosave",



        // Theme options

        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",

        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",

        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",

        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",

        theme_advanced_toolbar_location : "top",

        theme_advanced_toolbar_align : "left",

        theme_advanced_statusbar_location : "bottom",

        theme_advanced_resizing : true,



        // Example content CSS (should be your site CSS)

        content_css : "css/content.css",



        // Drop lists for link/image/media/template dialogs

        template_external_list_url : "lists/template_list.js",

        external_link_list_url : "lists/link_list.js",

        external_image_list_url : "lists/image_list.js",

        media_external_list_url : "lists/media_list.js",



        // Replace values for the template plugin

        template_replace_values : {

            username : "Some User",

            staffid : "991234"

        }

    });



    // O2k7 skin

    tinyMCE.init({

        // General options

        mode : "exact",

        elements : "elm2",

        theme : "advanced",

        skin : "o2k7",

        plugins : "lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,autosave",



        // Theme options

        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",

        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",

        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",

        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",

        theme_advanced_toolbar_location : "top",

        theme_advanced_toolbar_align : "left",

        theme_advanced_statusbar_location : "bottom",

        theme_advanced_resizing : true,



        // Example content CSS (should be your site CSS)

        content_css : "css/content.css",



        // Drop lists for link/image/media/template dialogs

        template_external_list_url : "lists/template_list.js",

        external_link_list_url : "lists/link_list.js",

        external_image_list_url : "lists/image_list.js",

        media_external_list_url : "lists/media_list.js",



        // Replace values for the template plugin

        template_replace_values : {

            username : "Some User",

            staffid : "991234"

        }

    });



    // O2k7 skin (silver)

    tinyMCE.init({

        // General options

        mode : "exact",

        elements : "elm3",

        theme : "advanced",

        skin : "o2k7",

        skin_variant : "silver",

        plugins : "lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups,autosave",



        // Theme options

        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",

        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,code,|,insertdate,inserttime,|,forecolor,backcolor",

        

        theme_advanced_toolbar_location : "top",

        theme_advanced_toolbar_align : "left",

        theme_advanced_statusbar_location : "bottom",

        theme_advanced_resizing : true,



        // Example content CSS (should be your site CSS)

        content_css : "css/content.css",



        // Drop lists for link/image/media/template dialogs

        template_external_list_url : "lists/template_list.js",

        external_link_list_url : "lists/link_list.js",

        external_image_list_url : "lists/image_list.js",

        media_external_list_url : "lists/media_list.js",



        // Replace values for the template plugin

        template_replace_values : {

            username : "Some User",

            staffid : "991234"

        }

    });



    

</script>



<!--End of Tiny MCE editor-->

<script> 

 

    $(document).ready(function(){ 

        $("ul.sf-menu").superfish({ 

            pathClass:  'current' 

        }); 

    }); 

 

</script>

<script type="text/javascript">

function fill()

        {

        if((document.getElementById('title').value=="" )|| (document.getElementById('file').value==""))

            {

                alert('Fill Required Fields');

                return false;

            }

        }

</script>

<style type="text/css">    

            .pg-normal {

                color: black;

                font-weight: normal;

                text-decoration: none;    

                cursor: pointer;    

            }

            .pg-selected {

                color: black;

                font-weight: bold;       

                text-decoration: underline;

                cursor: pointer;

            }

        </style>

</head>

<body>

<?php require("top.php"); ?>

      <div class="clr">

      </div>

 <?php  require("slider.php");   ?>

      <div class="clr"></div>

    </div>

  </div>

  <div class="content">

    <div class="content_resize">

      <div class="mainbar">

      

          <table id="pa">

            <tr>

              <th></th>

            </tr>

           <tr>

              <td><div class="article">

                  <h2><span>Upload Notes</span> Here</h2><br /><br />

                  

                  <div class="clr"></div>

                  

                  <div class="post_content">

                    <form enctype="multipart/form-data" name="form1" id="form1">

                    <table width="359" border="0" cellpadding="4" cellspacing="4" align="center">

    <tr>

      <td width="76">Title</td>

      <td width="255">

        <input type="text" name="title" value="<?php echo $_REQUEST['title']; ?>" />

      </td>

    </tr>

    <tr>

      <td width="76">Upload Type</td>

      <td width="255">

        <select name="type" id="type">

               

          <option value="Notes">Notes</option>

          <option value="Books">Books</option> 

                               

        </select>

      </td>

    </tr>

    <tr>

      <td>Major field</td>

      <td><select name="category" id="select2" onchange="document.form1.submit()">

                <option value="">--Select--</option>

         <?php

         require("db.php");

                                                    $query=mysql_query("select DISTINCT * from cat");

                                                    while($result=mysql_fetch_array($query))

                                                    {

                                                        $main=$_REQUEST['category'];

                                                ?>

                                                <option value="<?php echo $result['cat_id'];?>"><?php echo $result['category']; ?></option>

                                                <?php } ?>

      </select></td>

    </tr>

    <script language="javascript">

                                            document.form1.category.value=<?php echo $_REQUEST['category']?>;

                                        </script>



    <tr>

      <td>Sub field</td>

      <td><select name="sub" id="select3">

        <option value="" >-- Select--</option>

        <?php

                                                    $query=mysql_query("select * from `cat` WHERE `cat_id` = ".$_REQUEST['category']."");

                                                    while($result=mysql_fetch_array($query))

                                                    {

                                                        $catid=$_REQUEST['sub'];

      ?>

       <option value="<?php echo $result['subcat'];?>"><?php echo $result['subcat']; ?></option>

                                                <?php } ?>

      </select></td>

    </tr>

        <tr>

            <td>                        

  <label>Select File:</label></td><td>

  <input type="file" name="file" id="file" /></td></tr>

  </table>

  <br />

  <br /><textarea id="elm3" name="elm3" rows="15" cols="80" style="width: 80%">

    <?php echo $_REQUEST['elm3']; ?>    

    </textarea>

    <center>

    &nbsp;&nbsp;<input type="button" onclick="document.form1.submit()" name="Submit" value="Upload"  />

    

   &nbsp;<input type="reset" name="reset" value="Reset" /></center>



</form>

                  </div>

                  <div class="clr"></div>

                </div></td>

            </tr>

            

          </table>

          <br />

          

        

        

      </div>

      <div class="sidebar">

        <div class="gadget">

          <h2 class="star"><span>Sidebar</span> Menu</h2>

          <div class="clr"></div>

          <ul class="sb_menu">

           <li><a href="#">Home</a></li>

            <li><a href="#">Computer Science </a></li>

            <li><a href="#">Mathematics</a></li>

            <li><a href="#">Physics</a></li>

            <li><a href="#">Bussiness Administrtion and Comerece </a></li>

            <li><a href="#">Litrature</a></li>

             <li><a href="#">Others</a></li>

          </ul>

        </div>

        <div class="gadget">

          <h2 class="star"><span>Sponsors</span></h2>

          <div class="clr"></div>

          <ul class="ex_menu">

            <li><a href="http://www.dreamtemplate.com/">DreamTemplate</a><br />

              Over 6,000+ Premium Web Templates</li>

            <li><a href="http://www.templatesold.com/">TemplateSOLD</a><br />

              Premium WordPress &amp; Joomla Themes</li>

            <li><a href="http://www.imhosted.com/">ImHosted.com</a><br />

              Affordable Web Hosting Provider</li>

            <li><a href="http://www.megastockphotos.com/">MegaStockPhotos</a><br />

              Unlimited Amazing Stock Photos</li>

            <li><a href="http://www.evrsoft.com/">Evrsoft</a><br />

              Website Builder Software &amp; Tools</li>

            <li><a href="http://www.csshub.com/">CSS Hub</a><br />

              Premium CSS Templates</li>

          </ul>

        </div>

      </div>

      <div class="clr"></div>

    </div>

  </div>

  <div class="fbg">

    <div class="fbg_resize">

      <div class="col c1">

        <h2><span>Image</span> Gallery</h2>

        <a href="#"><img src="OLD/images/gal1.jpg" width="75" height="75" alt="" class="gal" /></a> <a href="#"><img src="OLD/images/gal2.jpg" width="75" height="75" alt="" class="gal" /></a> <a href="#"><img src="OLD/images/gal3.jpg" width="75" height="75" alt="" class="gal" /></a> <a href="#"><img src="OLD/images/gal4.jpg" width="75" height="75" alt="" class="gal" /></a> <a href="#"><img src="OLD/images/gal5.jpg" width="75" height="75" alt="" class="gal" /></a> <a href="#"><img src="OLD/images/gal6.jpg" width="75" height="75" alt="" class="gal" /></a> </div>

      <div class="col c2">

        <h2><span>Services</span> Overview</h2>

        <p>Curabitur sed urna id nunc pulvinar semper. Nunc sit amet tortor sit amet lacus sagittis posuere cursus vitae nunc.Etiam venenatis, turpis at eleifend porta, nisl nulla bibendum justo.</p>

        <ul class="fbg_ul">

          <li><a href="#">Lorem ipsum dolor labore et dolore.</a></li>

          <li><a href="#">Excepteur officia deserunt.</a></li>

          <li><a href="#">Integer tellus ipsum tempor sed.</a></li>

        </ul>

      </div>

      <div class="col c3">

        <h2><span>Contact</span> Us</h2>

        <p>Nullam quam lorem, tristique non vestibulum nec, consectetur in risus. Aliquam a quam vel leo gravida gravida eu porttitor dui.</p>

        <p class="contact_info"> <span>Address:</span> 1458 TemplateAccess, USA<br />

          <span>Telephone:</span> +123-1234-5678<br />

          <span>FAX:</span> +458-4578<br />

          <span>Others:</span> +301 - 0125 - 01258<br />

          <span>E-mail:</span> <a href="#">mail@yoursitename.com</a> </p>

      </div>

      <div class="clr"></div>

    </div>

  </div>

  <div class="footer">

    <div class="footer_resize">

      <p class="lf">&copy; Copyright <a href="#">MyWebSite</a>.</p>

      <p class="rf">Design by Dream <a href="http://www.dreamtemplate.com/">Web Templates</a></p>

      <div style="clear:both;"></div>

    </div>

  </div>

</div>

</body>

</html>

Recommended Answers

All 8 Replies

Provide some details about the error.

It is giving error that "unable to upload file"

Member Avatar for diafol

So your code messes up around here:

...
if($type == "Book") {
 if(move_uploaded_file($_FILES["file"]["tmp_name"],"books/" . $name)){
    $loc = "books/$name";
    echo "Successfully uploaded";
 }else{
    $msg .= "<h1>Unable to upload file</h1>";
 }            
}else{
    if(move_uploaded_file($_FILES["file"]["tmp_name"],"notes/" . $name)){
       $loc = "notes/$name";
       echo "Successfully uploaded";
    }else{
       $msg .= "<h1>Unable to upload file</h1>";
    }
...

How about

$loc = ($type == "Book") ? "books/$name" : "notes/$name";
if(move_uploaded_file($_FILES["file"]["tmp_name"], $loc)){
  echo "Successfully uploaded";
}else{
  echo "Failed to upload to $loc"; //just for debugging purposes
  $msg .= "<h1>Unable to upload file</h1>";
}

You need to know if the directory exists, whether the $name is a valid filename and the directory is writable.

@faisals701,

You need to change $_REQUEST to $_POST.. Anyone can send a remote upload on your form if that's how you are going to process it.

For added security, a unique ID should be auto generated by your script and plugged it in in your session..

Example of a unique id generator

$uID = md5(uniqid (rand(), true));

Re-validate $uID, before finalizing your upload ( this is when you actually rename, move the file, save data into your database.

@ardav:
This is still giving an error. that "only these files allowed, zip, rar, doc ......."

@veedeoo:
Please explain briefly. If I am using php on same page where form is located then can I use post method?

It is still giving error

So your code messes up around here:

...
if($type == "Book") {
 if(move_uploaded_file($_FILES["file"]["tmp_name"],"books/" . $name)){
    $loc = "books/$name";
    echo "Successfully uploaded";
 }else{
    $msg .= "<h1>Unable to upload file</h1>";
 }            
}else{
    if(move_uploaded_file($_FILES["file"]["tmp_name"],"notes/" . $name)){
       $loc = "notes/$name";
       echo "Successfully uploaded";
    }else{
       $msg .= "<h1>Unable to upload file</h1>";
    }
...

How about

$loc = ($type == "Book") ? "books/$name" : "notes/$name";
if(move_uploaded_file($_FILES["file"]["tmp_name"], $loc)){
  echo "Successfully uploaded";
}else{
  echo "Failed to upload to $loc"; //just for debugging purposes
  $msg .= "<h1>Unable to upload file</h1>";
}

You need to know if the directory exists, whether the $name is a valid filename and the directory is writable.

Member Avatar for diafol

Well that's a different error to the one you reported originally:

if ($size > 70 * 1024 * 1024) {
 $msg .= '<h1>You have exceeded the size limit!</h1>';
} else if($ext != "zip" && $ext!= "rar" && $ext!= "docx" && $ext!= "doc" && $ext!= "ppt" && $ext!= "pptx") {
 $msg .= "<h2>Only These Files Allowed</h2><br/><h3>Zip, rar , Doc, Docx, ppt, pptx</h3>";
} else {

You need to set up a few echoes here and there to show exactly where the script is going wrong.

Banging some 400 lines of code onto the forum and then giving piecemeal info about the errors is not going to help you. :(

@faisals701,

Here is a classic example of $_REQUEST vulnerability, if NOT properly PROTECTED.. Copy codes below and upload to your localhost. You can name it anyNameYouWant.php. Regardless of the form method use as long as it not protected, it will have the same vulnerability as to no method at all by way of REQUEST processing.

<?php
$method_one = '<form method ="POST" action ="">';
$method_two = '<form method ="" action ="">';
$method_three = '<form method ="GET" action ="">';

if (isset($_REQUEST['submit'])){
	$name = $_REQUEST['name'];
	$nickName = $_REQUEST['nickname'];
	
	echo $name."<br/>";
	echo $nickName."<br/>";
}
else{
 ## uncomment ONE method at a time here
 
 ## uncomment method one to test POST
 //echo $method_one;
 
 ## uncomment method two to test either method
 echo $method_two;
 
 ## uncomment method three to test GET method
 //echo $method_three;	
?>

<label>Name</label>
<input type = "text" name = "name" value ="" />
<br/>
<label>Nickname</label>
<input type = "text" name = "nickname" value = "" />
<br/>
<input type = "submit" name="submit" value ="submit"/>
</form>
<?php
}
?>

To test uncomment the $method_WhateverNUmberHere, comment out the one that you don't need to test.

Run the script on your browser, and try to test all the options -> $method and closely observe how the script will handle each $option. To make it a lot easier for everyone, if the method $_REQUEST isn't defined will default to $_GET effect. Meaning, if method is assigned like this method = "" (blank) it would have the same effect as method = "get".

For example, I am the bad Morpheus and I am desperate to upload some spamming media on your site. My first step in propagating my crap all over the Internet is by way of uploading my spamming media remotely. The first thing I would write on my fake remote form spoof script will be something like this

## location of my harmful files or spamming media
$local_directory= $upload_directory . $_FILES['my_file']['name'];

## since that I am a the bad Morpheus, I can pretend that I am behind the browser
$userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

## Since that I already know the location of your upload script, I have no problem sending it to your site.
$location = 'http://YourDomainDotCom/YourPageHere.php';

## All the Magical heinous Codes below. Normally, these codes can be use for good purpose, but this time it has been tweaked to do some bad things. 

// of course I am not that stupid to release something that will hurt anyone :)

## end of Magical heinous Codes.

The bottom line is that why take chances on request, if you can absolutely define the method as per your requirements. Request is a lazy code.. Form processing should be protected and should be evaluated for its vulnerability, before uploading the script to production server.

Would you believe, someone actually offered me some money for this type of crap??? NOT in my lifetime...Maybe I am just a humble, starving college student who thrive on cup-O-noodle everyday, but will not resort to something like this. I always believe web technology should move forward without the spamming trolls.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.