ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Simple File or Image Uploads Using PHP HTML

Updated on January 17, 2014

Simple File and Image Uploads

Today we are going to learn how to upload a file or image using PHP and a web form. No knowledge of PHP is needed or HTML as the full file structure is included:

Build a simple HTML form:

<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadedfile" id="uploadedfile" />
<br />
<input type="submit" name="Submit" value="Submit" />
</form>

Once again nothing fancy, but you will be able to add to the form, so that you can upload the file and email other form contents or store the other form contents in a database.

Page Load:

Once the page loads the form shown above will be rendered, after the Submit button is clicked, here is what happens:

}else{
$path = "uploads/";

$path = $path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
?>
<div style="text-align:center;width:350px;border:1px solid #cccccc;background-color:#f1f1f1;">
"Thanks for your uploaded file!"
</div>
<?php
} else{
echo "There was an error uploading the file, please try again!";
}


}//end if


  • $path = "uploads/"; All we did here is establish a place to put the file
  • move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $path), we did what the function reads, we moved the file to the $path, using the temp name (same name)
  • <div style="text-align:center;width:350px;border:1px solid #cccccc;background-color:#f1f1f1;">
    "Thanks for your uploaded file!"
    </div> using a little css we styled a box that give the user some feedback on the a positive upload

Next, you give some feedback just in case the upload fails, using a conditional statement.

"Thanks for your uploaded file!"

Code in full:

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php if(isset($_POST['Submit'])){ echo 'The file "'. basename( $_FILES['uploadedfile']['name']). '" has been uploaded!';}else{?>Please Choose a File<?php } ?></title>
</head>

<body>
<?php if(!isset($_POST['Submit'])){?>
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploadedfile" id="uploadedfile" />
<br />
<input type="submit" name="Submit" value="Submit" />
</form>
<?php
}else{
$path = "uploads/";

$path = $path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
?>
<div style="text-align:center;width:350px;border:1px solid #cccccc;background-color:#f1f1f1;">
"Thanks for your uploaded file!"
</div>
<?php
} else{
echo "There was an error uploading the file, please try again!";
}

}//end if
?>
</body>
</html>

Recap:

Told ya, short and sweet! Now in PHP you can do a lot more with the validation of a file before you copy or upload it, such as size, type, etc.

That all can be found referencing the $_FILES superglobal using this book.

No working demo for this how to, but follow this to get started:

  1. just copy and paste the full code
  2. create a file folder named "uploads"
  3. chmod the "uploads" folder to 755
  4. Call the page using your browser and that's it

Using this small sample you can quickly build on more possibilities, such as insert the path in the database, emailing the file, whatever you can think of. Thank you and more to come!


File Uploads Survey

Did this help you?

See results

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Ronald 

      5 years ago

      I love your fantastic article! Will follow your hub.

      Go here and read this one http://ownsports.wordpress.com/2012/07/10/new-targ...

    • profile image

      satish 

      6 years ago

      its nice

    • profile image

      Christoph 

      7 years ago

      Hi,

      i had to put my folder permissons tp 777. With 755 it is not working, it get this error:

      Warning: move_uploaded_file(uploads/hopper.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /www/htdocs/w005dcde/Christoph/Tests/imageupload.php on line 23

      Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phplSkUDT' to 'uploads/hopper.jpg' in /www/htdocs/w005dcde/Christoph/Tests/imageupload.php on line 23

      There was an error uploading the file, please try again!

      Can someone help me?

      greets

    • Alpho011 profile imageAUTHOR

      Alpho011 

      8 years ago from Marietta, Georgia

      It gets overridden

    • Afsal Rahim profile image

      Afsal Rahim V 

      8 years ago from India

      Nice simple code.

      What happens if someone uploads files with the same name? Does the older file get replaced by the new file?

    • profile image

      mahesh 

      8 years ago

      its good

    • profile image

      Shrikrishna Meena 

      8 years ago

      Thanks for writing this article...

      Very helpful...

    • tonyhubb profile image

      tonyhubb 

      8 years ago

      Good information! It is very helpful!

    • profile image

      Ben 

      8 years ago

      Please send me a code changing a background image using input text ("path") and will show the image to its corresponding input text (path)...

      tnx

    • profile image

      Simon 

      9 years ago

      WOW! nice and easy! not like some of these upload files which contain files galore!!

      Damn girl you smart! ;) keep it up!

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      felipe

      Sorry been out of town in miami, you need to set the folder permissions to 755, (chmod)

    • profile image

      felipe 

      9 years ago

      this file didn&acute;t work for me, can somebody tell me what could happen? the 2 errors were like this:

      Warning: move_uploaded_file(uploads/HONDEX HE7300.pdf) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/ramcote/public_html/es/subir.php on line 23Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpVNOzZb' to 'uploads/HONDEX HE7300.pdf' in /home/ramcote/public_html/es/subir.php on line 23There was an error uploading the file, please try again!

    • profile image

      grep php 

      9 years ago

      I prefer classic methods, ajax sucks.

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      ok, you have to run the upload script in the background using the http object (AJAX), I am guessing you want the name before you upload right, or do you want to upload with leaving the page (refresh).

    • profile image

      vamshi 

      9 years ago

      Hi this is vamshi, in ajax how to retrieve without using $_files[file][tmp_name], first page is html page and onclick to javascript page and upload.php , in upload.php how to retrieve temp name of upload image in php.....

      Anybody plzzz help me in this.....

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      Using your FTP client, depends on the client, but most you can right click and change the file permissions.

    • profile image

      Scott Z 

      9 years ago

      How do you chmod it to 755?

    • wei654231 profile image

      wei654231 

      9 years ago

      Simple File or Image Uploads Using PHP HTML

      what a wonderful hub! I'd not heard of them before, fascinating.

    • Alpho011 profile imageAUTHOR

      Alpho011 

      9 years ago from Marietta, Georgia

      Thanks that give me incentive to brush up on my HTML, really appreciate it.

    • profile image

      A Friend 

      9 years ago

      Good tutorila, but I think you misunderstood the html attribute (for) of the (label) tag is for.

      http://www.w3schools.com/tags/tag_label.asp

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)