Hi i am wondering could anyone help me understand a file upload code. I am currently working on a website like mediafire, raipidshare and the rest of them. I have taken down codes of all sorts and some i got to work but had errors. I don't understand as i take them down perfect and they still don't work. And as i am making a File Uploading site i need to understand them more. I am newish to coding but am a good quick learner and can do everything but use MySQL or connect to a DB. Any help is useful and a code would be nice too :)
Regards,
-Dyla.

Dani AI

Generated

Two separate problems show up in this thread and both are common for beginners.

The PHP source appearing in the browser usually means the file was not served through PHP (open via file:// or Apache/PHP not running). was right to point at server config. Quick checks: open the page with ... (not file://), confirm WAMP/Apache/PHP are running, put files in the webroot (wamp/www or htdocs), and use full <?php ... ?> tags (short tags <? may be disabled). A “Parse error: unexpected ‘}’ on line N” points to a syntax problem near that line — use the reported line number to find a missing semicolon or mismatched brace.

The later error — “failed to open stream: Permission denied” — means the webserver user could not write to the upload folder. correctly advised checking paths and write permissions; fixed it by making the folder writable. Prefer changing ownership to the webserver user and using 755/750 instead of 777 (example on many Linux servers: chown -R www-data:www-data upload then chmod 755 upload). Also use an absolute destination path like __DIR__ . '/upload/' to avoid relative-path confusion.

Also verify PHP settings: file_uploads = On, upload_max_filesize and post_max_size are large enough, and upload_tmp_dir exists and is writable (check with phpinfo()). Always check $_FILES['file']['error'] — constants include UPLOAD_ERR_OK (0), UPLOAD_ERR_INI_SIZE (1), UPLOAD_ERR_FORM_SIZE (2), UPLOAD_ERR_PARTIAL (3), UPLOAD_ERR_NO_FILE (4), UPLOAD_ERR_NO_TMP_DIR (6), UPLOAD_ERR_CANT_WRITE (7), UPLOAD_ERR_EXTENSION (8).

A compact, safer flow (outline):

if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) { /* handle error */ }
if (!is_uploaded_file($_FILES['file']['tmp_name'])) { /* reject */ }
$f = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($f, $_FILES['file']['tmp_name']);
$allowed = ['image/gif','image/jpeg','image/png'];
if (!in_array($mime, $allowed)) { /* reject */ }
$name = preg_replace('/[^A-Za-z0-9_.-]/','_',basename($_FILES['file']['name']));
$dest = __DIR__ . '/upload/' . uniqid() . '-' . $name;
move_uploaded_file($_FILES['file']['tmp_name'], $dest) || /* handle failure */;

Sanitize filenames, verify MIME with FileInfo (do not trust $_FILES['file']['type']), use unique names, and avoid 777 on production.

Recommended Answers

All 15 Replies

Member Avatar for Member #120589

Want to post the code you're using and let us know what the error seems to be?

Yeah sure :) I used the code from W3schools as that seems to be the best place to get codes.

This is index.php

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

Upload_file.php

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

I copied them directly down to see did they work first. The form works as i chose what i upload then when i press submit the code from Upload_file.php just shows up on the screen. I have used a few others and still they didnt work.

Is it on a server that is correctly configured to serve PHP files?

I dont have it online yet i only have it in wamp server and wamp supports php yes.

Member Avatar for Member #120589

Check that your directory references are correct. Is upload directory in the same directory as Upload_file.php? If not, that may be your problem. Also, ensure that the directory is writable.

I have a directory just for the 3 upload files. (index.php, upload_file.php and upload folder) And i am still getting the code when i click submit. Test it yourself and see what you get as it could be just me.

Ok got it working but am getting an error. Line 24 of upload_file.php

Member Avatar for Member #120589

WHat's the error.....

I click submit, the file uploads as i see it bottom left of the screen then i get...

Parse error: syntax error, unexpected '}' in /home/a6181642/public_html/web/Uploads/upload_file.php on line 24

Member Avatar for Member #120589

It suggests something missing like a ; or an extra }

Try this

<?php
if(($_FILES["file"]["type"] == "image/gif" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/pjpeg") && $_FILES["file"]["size"] < 20000) {
	if($_FILES["file"]["error"] > 0) {
		echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
	} else {
		echo "Upload: " . $_FILES["file"]["name"] . "<br />";
		echo "Type: " . $_FILES["file"]["type"] . "<br />";
		echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
		echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

		if(file_exists("upload/" . $_FILES["file"]["name"])) {
			echo $_FILES["file"]["name"] . " already exists. ";
		} else {
			move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
			echo "Stored in:  upload/" . $_FILES["file"]["name"];
		}
	}
} else {
	echo "Invalid file";
}
?>
commented: Code seem better now :) +1

Hmm still another error.

Upload: Image.jpg
Type: image/jpeg
Size: 184.2890625 Kb
Temp file: /tmp/phpsNHDVh

PHP Error Message

Warning: move_uploaded_file(upload/Image.jpg) [function.move-uploaded-file]: failed to open stream: Permission denied in /home/a6181642/public_html/web/Uploads/upload_file.php on line 14


Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpsNHDVh' to 'upload/Image.jpg' in /home/a6181642/public_html/web/Uploads/upload_file.php on line 14


Stored in: upload/Image.jpg

Member Avatar for Member #120589

OK seems we're getting closer. Seems the directory does not exist.

The directory "Uploads" exists but not "upload".

I have a dir called upload yes. still getting the error though...hmm. I have made a free hosting site if you want to check it out.

Nevermind, Permissions to 777 and it works perfect now :) Thanks for the help :D

Member Avatar for Member #120589

As I mnetioned previously:

> Check that your directory references are correct. Is upload directory in the same directory as Upload_file.php? If not, that may be your problem. Also, ensure that the directory is writable.

If this is solved, mark it so by the link below.

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.