Jump to content

Web technologies -- Laboratory 18 -- 2009-2010 -- info.uvt.ro

From Wikiversity

PHP advanced

[edit]

Connecting and querying a database

[edit]

The steps to connect to a database are listed in the following example:

	<?php
		$dbcnx = @mysql_connect('localhost', 'username', 'password');
		if (!$dbcnx)
			//kill the script
			die "Could not connect to database. Check credentials: " . mysql_error();

		@mysql_select_db('regulus')
		
		$result = @mysql_query('SELECT name, email FROM users;');
		
		while ($row = mysql_fetch_array($result_ta)) {
			//list the users and their passwords. Notice how the name of the array element 
			//is the same with the fields in the above SELECT statement
			echo "User: " . $row['name'] . " Email: " . $row['email'];
		}
	?>

Uploading files using forms and PHP

[edit]

Uploading files is useful when considering a website that displays to users additional information besides the the normal text (e.g., images, XML files, etc.).

To upload a file we must do the following:

  • create a form in HTML and set its enctype attribute to multipart/form-data;
  • set the submission method to POST as we'll send binary data;
  • create an input of type file that allows us to select the desired file from the storage device:
	<form enctype="multipart/form-data" name="frmUploadFile" action="getfile.php" method="post">
		<input type="file" name="fileUpload" size="20">
		<input type="submit" value="Load file" name="cmdSubmit">
	</form>
  • create an PHP script which reads the file send through in the HTTP Request;
    • the file information (name, size, type, temporary name) is read by using the $_FILES variable;
    • the content of the file can then be read read by using fopen and fread:
	<?php 
		$in = $_FILES['fileUpload']['tmp_name'];
		$in_name = $_FILES['fileUpload']['name'];
		$in_size = $_FILES['fileUpload']['size'];
		$in_type = $_FILES['fileUpload']['type'];

		$fileHandle = fopen($in, "rb"); /*rb - read binary file*/
		$fileContent = fread($in, $fileUpload_size); /*read the entire content of the file in one step*/

		//be sure to have an images subdirectory in the directory you place this script and
		//be sure not to already have an image with the same name (hint: use a random name)
		$path = "images/" . $in_name;
		$out = fopen($path, "wb"); /*wb - write binary data*/
		fwrite($out, $fileContent, $fileUpload_size); /*write entire content of the image in one step*/
	?>

Creating and using a random image in forms to avoid automatic submissions

[edit]

Random images in forms are a great way of ensuring that there is no automatic submission (bots, spams, etc.) as an image can only be read by a human (for now).

To create and use a random image we need to follow the next steps:

  • create a form (inside a new file form.php) which contains a text where the user needs to insert the randomly generated code (discussed at the next step):
    • the code is generated on the spot inside the script containing the form;
    • the value of the random code is stored in a session variable:
	<?php
		session_start();

		//function to generate a random number of length characters (default length is 4)
		function gen_code($length = 4) {
			$number = "";
			for ($i = 1; $i <= $length; $i++) {
			 $number .= rand(0,9)."";
			}
			return $number;
		}

		//store inside a session variable the generated code
		$_SESSION['codeCheck'] = gen_code();
	?>

	<form action="checkCode.php" method="get">
		<input type="text" name="insertedCode" id="insertedCode"> &nbsp; <img src="code.php?>"/>
	</form>
  • create an PHP function for generating an image using GD
    • the function should be placed in a file called code.php;
    • the function should receive the code to be displayed as an argument;
    • the function should return the image content inside the HTTP Response:
<?php
	session_start();

	function anti_bot($code, $length = 4)
	{
		//set the image size
		$width = 11 * $length; 
		$height = 30;

		//create the image in memory
		$img = ImageCreate($width, $height);
		//set its background to white
		$background = imagecolorallocate($img, 255, 255, 255);
		//define the black color for the text
		$color_black = imagecolorallocate($img, 0, 0, 0);
		//define a gray color
		$color_grey = imagecolorallocate($img, 169, 169, 169);

		//create a rectangle of gray color
		imagerectangle($img, 0, 0, $width - 1, $height - 1, $color_grey);
		//add the string to the image
		imagestring($img, 5, $length, 7, $code, $color_black);
		//create a PNG image
		imagepng($img);
		//clear the memory
		imagedestroy($img);
	}

	//create a header which specifies that the information to be sent is an image of type PNG
	header("Content-type: image/png");
	//create the content (image) by calling the previous function
	anti_bot($_SESSION['codeCheck']);
?>
  • check the code validity by creating script inside a PHP file named checkCode.php:
	<?php
		session_start();

		if (isset($_REQUEST['insertedCode']) && $_SESSION['codeCheck'] == $_REQUEST['insertedCode']) 
				echo "Correct code";
		else
				echo "Wrong code";
	?>

Checking the existence of emails

[edit]

Checking the existence of emails from PHP can be a hard job. It involves using querying the MX (mail exchange record) from the DNS. It specifies a mail server responsible for accepting email messages.

The following example [1] shows how this can be achieved:

	<?php 

		function domain_exists($email,$record = 'MX') {
			//create a list containing the user and the domain by splitting the email after @
			list($user, $domain) = split('@',$email);
			return checkdnsrr($domain, $record);
		}

		//call the function
		if (domain_exists($_REQUEST['email']))
			echo "Valid email";
		else
			echo "Invalid email";
	?>

NOTE the previous method doesn't really work in case the user is smart enough to attach a fake user to a valid domain.

Links:

Exercise

[edit]
  • Create a form to upload images to a server. You need to use the secure submission using random images:
    • the file names on the server should be chosen randomly to avoid overriding files due to naming duplicates (use the rand() function);
      • you will need to get the file extension and name (list($name, $extension) = explode('.', $filename));
    • after uploading the script should return all the files in the directory (use the readdir function);
  • Add to the previous exercise the option to delete a certain file (as indicated by the user through a form) from the file list (no tips here).