Tag Archives: Examples

How to Upload in PHP Files | Examples

  • With PHP, it is easy to upload files to the server.
  • However, with ease comes danger, so always be careful when allowing file uploads!

Configure The “php.ini” File :

  • First, ensure that PHP is configured to allow file uploads.
  • In your “php.ini” file, search for the file_uploads directive, and set it to On:

[php]file_uploads = On[/php]

Create The HTML Form :

Next, create an HTML form that allow users to choose the image file they want to upload:

[php]<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>[/php]

Some rules to follow for the HTML form above:

  • Make sure that the form uses method=”post”
  • The form also needs the following attribute: enctype=”multipart/form-data”. It specifies which content-type to use when submitting the form
  • Without the requirements above, the file upload will not work.
  • Other things to notice:
  • The type=”file” attribute of the <input> tag shows the input field as a file-select control, with a “Browse” button next to the input control
  • The form above sends data to a file called “upload.php”, which we will create next.

Create The Upload File PHP Script :

  • The “upload.php” file contains the code for uploading a file:

[php]<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image – " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>[/php]

PHP script explained:

  • $target_dir = “uploads/” – specifies the directory where the file is going to be placed
  • $target_file specifies the path of the file to be uploaded
  • $uploadOk=1 is not used yet (will be used later)
  • $imageFileType holds the file extension of the file
  • Next, check if the image file is an actual image or a fake image

Check if File Already Exists  :

  • Now we can add some restrictions.
  • First, we will check if the file already exists in the “uploads” folder. If it does, an error message is displayed, and $uploadOk is set to 0:

[php]// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}[/php]

Limit File Size :

  • The file input field in our HTML form above is named “fileToUpload”.
  • Now, we want to check the size of the file. If the file is larger than 500kb, an error message is displayed, and $uploadOk is set to 0:

[php] // Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}[/php]

Limit File Type :

  • The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:

[php]// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}[/php]

Complete Upload File PHP Script :

The complete “upload.php” file now looks like this:

[php]<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image – " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>[/php]

Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Example : 1

[php]<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image – " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>[/php]

Example :  2

[php]<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>[/php]

Post() Methods jQuery – AJAX get() and | Examples

  • The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

HTTP Request: GET vs. POST :

  • Two commonly used methods for a request-response between a client and server are: GET and POST.
  • GET – Requests data from a specified resource
  • POST – Submits data to be processed to a specified resource
  • GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data.
  • POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
  • To learn more about GET and POST, and the differences between the two methods, please read our HTTP Methods GET vs POSTchapter.

jQuery $.get() Method :

  • The $.get() method requests data from the server with an HTTP GET request.

Syntax:

[code lang=”js”]$.get(<i>URL,callback</i>);[/code]
  • The required URL parameter specifies the URL you wish to request.
  • The optional callback parameter is the name of a function to be executed if the request succeeds.
  • The following example uses the $.get() method to retrieve data from a file on the server:

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>[/code]

  • The first parameter of $.get() is the URL we wish to request (“demo_test.asp”).
  • The second parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
  • Tip: Here is how the ASP file looks like (“demo_test.asp”):
[code lang=”js”]<%
response.write("This is some text from an external ASP file.")
%>[/code]

jQuery $.post() Method :

  • The $.post() method requests data from the server using an HTTP POST request.

Syntax:

[code language=”lang="js'”]$.post(<i>URL,data,callback</i>);[/code]
  • The required URL parameter specifies the URL you wish to request.
  • The optional data parameter specifies some data to send along with the request.
  • The optional callback parameter is the name of a function to be executed if the request succeeds.
  • The following example uses the $.post() method to send some data along with the request:

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>[/code]

  • The first parameter of $.post() is the URL we wish to request (“demo_test_post.asp”).
  • Then we pass in some data to send along with the request (name and city).
  • The ASP script in “demo_test_post.asp” reads the parameters, processes them, and returns a result.
  • The third parameter is a callback function. The first callback parameter holds the content of the page requested, and the second callback parameter holds the status of the request.
  • Tip: Here is how the ASP file looks like (“demo_test_post.asp”):
[code lang=”js”]<%
dim fname,city
fname=Request.Form("name")
city=Request.Form("city")
Response.Write("Dear " & fname & ". ")
Response.Write("Hope you live well in " & city & ".")
%>[/code]

jQuery AJAX Reference :

For a complete overview of all jQuery AJAX methods, please go to our jQuery AJAX Reference.

Example : 1

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>

</body>
</html>[/code]

Example : 2

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>

<button>Send an HTTP GET request to a page and get the result back</button>

</body>
</html>[/code]

jQuery Traversing – Filtering | Narrow Down The Search For Elements |jQuery first() Method | jQuery last() Method |jQuery eq() method |jQuery filter() Method |Examples

Narrow Down The Search For Elements :

  • The three most basic filtering methods are first(), last() and eq(), which allow you to select a specific element based on its position in a group of elements.
  • Other filtering methods, like filter() and not() allow you to select elements that match, or do not match, a certain criteria.

jQuery first() Method :

  • The first() method returns the first element of the selected elements.
  • The following example selects the first <p> element inside the first <div> element:

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div p").first().css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>This is the first paragraph in body.</p>

<div style="border: 1px solid black;">
<p>This is the first paragraph in a div.</p>
<p>This is the last paragraph in a div.</p>
</div><br>

<div style="border: 1px solid black;">
<p>This is the first paragraph in another div.</p>
<p>This is the last paragraph in another div.</p>
</div>

<p>This is the last paragraph in body.</p>

</body>
</html>[/code]

jQuery last() Method :

  • The last() method returns the last element of the selected elements.
  • The following example selects the last <p> element inside the last <div> element:

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div p").last().css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>This is the first paragraph in body.</p>

<div style="border: 1px solid black;">
<p>This is the first paragraph in a div.</p>
<p>This is the last paragraph in a div.</p>
</div><br>

<div style="border: 1px solid black;">
<p>This is the first paragraph in another div.</p>
<p>This is the last paragraph in another div.</p>
</div>

<p>This is the last paragraph in body.</p>

</body>
</html>[/code]

jQuery eq() method :

  • The eq() method returns an element with a specific index number of the selected elements.
  • The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second <p> element (index number 1):

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").eq(1).css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald (index 0).</p>
<p>Donald Duck (index 1).</p>
<p>I live in Duckburg (index 2).</p>
<p>My best friend is Mickey (index 3).</p>

</body>
</html>[/code]

jQuery filter() Method :

  • The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.
  • The following example returns all <p> elements with class name “intro”:

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").filter(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald.</p>
<p class="intro">I live in Duckburg.</p>
<p class="intro">I love Duckburg.</p>
<p>My best friend is Mickey.</p>

</body>
</html>[/code]

jQuery not() Method :

  • The not() method returns all elements that do not match the criteria.
  • Tip: The not() method is the opposite of filter().
  • The following example returns all <p> elements that do not have class name “intro”:

Example :

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").not(".intro").css("background-color", "yellow");
});
</script>
</head>
<body>

<h1>Welcome to My Homepage</h1>

<p>My name is Donald.</p>
<p class="intro">I live in Duckburg.</p>
<p class="intro">I love Duckburg.</p>
<p>My best friend is Mickey.</p>

</body>
</html>[/code]

Example : 1

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// add code here
});
</script>
</head>
<body>

<p>First paragraph.</p>
<p>Second paragraph.</p>
<p>Third paragraph.</p>
<p>Last paragraph.</p>

</body>
</html>[/code]

Example : 2

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// add code here
});
</script>
</head>
<body>

<p>First paragraph.</p>
<p>Second paragraph.</p>
<p>Third paragraph.</p>
<p>Last paragraph.</p>

</body>
</html>[/code]

Example : 3

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// add code here
});
</script>
</head>
<body>

<p>First paragraph.</p>
<p class="intro">Second paragraph.</p>
<p class="intro">Third paragraph.</p>
<p>Last paragraph.</p>

</body>
</html>[/code]

Example : 4

[code lang=”js”]<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// add code here
});
</script>
</head>
<body>

<div style="border: 1px solid black;">
<p>This is the first paragraph in a div.</p>
<p>This is the last paragraph in a div.</p>
</div><br>

<div style="border: 1px solid black;">
<p>This is the first paragraph in another div.</p>
<p>This is the last paragraph in another div.</p>
</div>

</body>
</html>[/code]

 

[wpsp]