Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP file upload keeps throwing error

Tags:

php

pem

fopen

I am uploading an rsa private key (.pem file) to my website and using fopen to read the contents but lately I keep getting the same error over and over without making much sense.

HTML

  <form enctype="multipart/form-data" action="upload.php" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
    Choose a file to upload: <input name="uploaded_file" type="file" />
    <input type="submit" value="Upload" />
  </form> 

Upload.php

<?php
session_start();

if( $_SERVER['SERVER_PORT'] == 80) {
    header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]); 
    die();
} 



echo $_FILES['uploaded_file']['name'];

//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
  $filename = basename($_FILES['uploaded_file']['name']);
  $ext = substr($filename, strrpos($filename, '.') + 1);
  if (($ext == "pem") && ($_FILES["uploaded_file"]["type"] == "text/plain")) {

$fh = fopen($_FILES['uploaded_file']['name'], 'r');

//continue with code
  } else {
     echo "Error: Only pem files are accepted for upload";
  }
} else {
 echo "Error: No file uploaded";
}
?>

The site keeps returning the error:

Warning: fopen(mykey.pem) [function.fopen]: failed to open stream: No such file or directory in .... on line 38

(which is fopen line). The fact it gets to the fopen state proves to me it does in fact upload but using fopen (also tried using file_get_contents($_FILES['uploaded_file']['name']); as well unsuccessfully) returns an error.

what da puh!

FINAL NOTES:

For whatever reason, fopen() does not like reading OpenSSL certificates and returns an eror:

openssl_private_decrypt(): supplied resource is not a valid OpenSSL X.509/key resource

if you use file_get_contents it works however.

like image 687
JM4 Avatar asked Feb 25 '23 22:02

JM4


1 Answers

I believe you're trying to open a wrong file(name). Since I don't see move_uploaded_file() anywhere in your code, you should probably be reading the tmp_name instead of name from the $_FILES array:

$fh = fopen($_FILES['uploaded_file']['tmp_name'], 'r');
like image 77
Zathrus Writer Avatar answered Mar 03 '23 00:03

Zathrus Writer