I'm trying to move my uploaded file to a pictures folder. I dont get any errors when it comes to the script. Im using godaddy as the host. All file permissions are set up correctly. Have really no idea what else to do.
This is the php code:
<?php
public function CheckPicture($picture){
if(empty($_FILES['picture']['name'])){
echo "Must choose a file.";
}else{
$allowed = array('jpg', 'jpeg', 'png');
$file_name = $_FILES['picture']['name'];
//line 157->$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['picture']['tmp_name'];
if(in_array($file_extn, $allowed)){
$this->UploadPicture($username, $file_name, $file_extn);
}else{
echo $file_extn;
echo "Incorect file type. Types allowed: ";
echo implode(', ' , $allowed);
}
}
}
public function UploadPicture($username, $file_temp, $file_extn){
ini_set('display_errors',1);
error_reporting(E_ALL);
$file_path = '/home/content/49/11554349/html/gb/dev/images/pictures/' . substr(md5(time()), 0 , 9) . '.' . $file_extn;
move_uploaded_file($file_temp, $file_path);
echo $file_path;
print_r("$file_temp");
}
?>
This is how I am calling it in the html:
<?php
session_start();
include_once('post.php');
$username = unserialize($_SESSION["username"]);
$email = $_SESSION["email"];
if(!$_SESSION["username"]){
header("Location: http://www.greenboardapp.com/dev/");
}
if(isset($_FILES['picture'])){
$upload = new Post();
$upload->CheckPicture($picture);
}
?>
This is the form:
<div class="tile">
<img src="images/profileimg.png" alt="Tutors" class="tile-image">
<form action="profile.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="picture"><br>
<h6><input type="submit" value="Change Profile Pic" class="btn btn-hg btn-success"></h6>
</form>
</div>
The problem is, that end requires a reference, because it modifies the internal representation of the array (it makes the current element pointer point to the last element).
The result of explode('.', $file_name) cannot be turned into a reference. This is a restriction in the PHP language, that probably exists for simplicity reasons.
Output for 5.1.0 - 5.5.6
Strict Standards: Only variables should be passed by reference
Output for 5.0.5
Fatal error: Only variables can be passed by reference
Process exited with code 255.
Output for 4.3.0 - 5.0.4
Success
Solution
Find:
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $picture['tmp_name'];
Change to:
$file_extn_ex = explode('.', $file_name);
$file_extn_end = end($file_extn_ex);
$file_extn = strtolower($file_extn_end);
$file_temp = $picture['tmp_name'];
Related
I made a uload sistem using php and html, and java, but i am worried about the duplipicate files. How can I made it to save with a random name and add its extension?
<?php
if(isset($_FILES['image'])){
$errors= array();
$test = uniqid()
$file_name = ['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png","rbxl","mp4","mp3");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed";
}
if($file_size > 600000000){
$errors[]='File size must be excately 600 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "https://glotech.cf/images/";
print_r($file_name);
}else{
print_r($errors);
}
}
?>
window.addEventListener("paste", e => {
if (e.clipboardData.files.length > 0) {
const fileImput = document.querySelector("#myFile");
fileImput.files = e.clipboardData.files;
}
});
<form action="/test.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="myFile">
<input type="submit" />
</form>
How can I made it to save it with a random name?
There are some functions in which you can generate random strings in several languages. In PHP, you can use md5() and uniqid(), for example.
Your code is uploading the file with the name of the original file. So, if you want to avoid duplicating filenames, just generate a unique code and include to the filename. In addition, you can use the time() function to add a timestamp to the filename which will prevent duplicated filenames though.
$file_name = time() . "-" . $_FILES['image']['name'];
// output: "1615273926-filename.jpg"
If you want to invert the order of filename and the timestamp in the example above, you can use pathinfo() function. See:
$file_name_pathinfo = pathinfo($_FILES['image']['name']);
$file_name = $file_name_pathinfo['basename'] . "-" . time() . "." . $file_name_pathinfo['extension'];
// output: "filename-1615273926.jpg"
This should prevent files with duplicated names.
LEARN MORE:
pathinfo: https://www.php.net/manual/pt_BR/function.pathinfo.php
time(): https://www.php.net/manual/pt_BR/function.time.php
Try with some random numbers
$file_name = ['image']['name'];
$random = rand(000,999);
$random = str_pad($random, 3, '0', STR_PAD_LEFT);
$imgname = $random.$file_name;
In move upload
move_uploaded_file($_FILES["userImage"]["tmp_name"], "uploaddirectory/" . $imgname);
Put above line in condition check if you want for file exists
if (file_exists("uploaddirectory/" . $imgname)
{
echo $imgname . " already exists. ";
die;
}
else
{
//do something
}
Add timestamp to the end of the file name which makes it unique.
$fileName = time() .' '. $_FILES['image']['name'];
I tried to take it off this error I do not understand why it happens, because I am uploading the file correctly... Right now is uploading the files, it shows me the error Error Notice: Only variables should be passed by reference in...
<?php
if(isset($_FILES['csv'])){
$errors= array();
$file_name = $_FILES['csv']['name'];
$file_size = $_FILES['csv']['size'];
$file_tmp = $_FILES['csv']['tmp_name'];
$file_type = $_FILES['csv']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['csv']['name'])));// error line
$expensions= array("csv");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a csv file.";
}
if($file_size > 2097152) {
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action = "" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "csv" />// If I change this to name this code does not works,
<input type = "submit" value="Subir archivos"/>
</form>
</body>
</html>
When calling end(), you must pass an array as a variable and not the return value of a function. So in...
$file_ext=strtolower(end(explode('.',$_FILES['csv']['name'])));
you can assign the return of explode() to a variable and then call end()
$file_parts =explode('.',$_FILES['csv']['name']);
$file_ext=strtolower(end($file_parts));
If you look at the documentation for end(), it shows the paramter is array &$array, the & shows it's passed by reference.
It complains when you don't pass a plain variable in. It doesn't like functions being passed in.
Also you already assign $_FILES['csv']['name'] as $name, so just use $name.
Split the line up:
$file_ext=strtolower(end(explode('.',$_FILES['csv']['name'])));
To
$file_ext = explode('.',$name);
$file_ext = end($file_ext);
$file_ext = strtolower($file_ext);
Change this line:
$file_ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
To this:
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
And regarding the If I change this to name this code does not works, that is because you also need to change the array index to name on the FILES superglobal to access the data.
if (isset($_FILES['name'])) {
$errors = [];
$file_name = $_FILES['name']['name'];
$file_size = $_FILES['name']['size'];
// and so on...
}
end — Set the internal pointer of an array to its last element.
Separate into different variables. this should work
$file_exploding =explode('.',$_FILES['csv']['name']);
$file_last_element = end($file_exploding);
$file_ext=strtolower($file_last_element);
hi i have already typed my code below. the database is saving the path of image but it is not displaying the image . where could i be wrong?
<div class="profile">
<?php
if (isset($_FILES['profile']) === true) {
if (empty($_FILES['profile']['name']) === true) {
echo 'Please choose a file';
} else {
$allowed = array('jpg', 'jpeg', 'gif', 'png');
$file_name = $_FILES['profile']['name'];
$file_extn = strtolower(end(explode('.', $file_name)));
$file_temp = $_FILES['profile']['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
///upload file.
change_profile_image($session_user_id, $file_temp, $file_extn);
} else {
echo 'incorrect file type. Allowed formats: ';
echo implode(', ', $allowed);
}
}
}
if (empty($user_data['profile']) === false) {
echo '<img src"', $user_data['profile'], '"
alt="', $user_data['first_name'], '\'s">';
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="profile">
<input type="submit">
</form>
</div>
and the function change_profile_image I am calling is below:
function change_profile_image($user_id, $file_temp, $file_extn) {
$file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
//echo $file_path;
move_uploaded_file($file_temp, $file_path);
mysql_query("UPDATE `users` SET `profile` = '"
. mysql_real_escape_string($file_path)
. "' WHERE `user_id` = "
. (int) $user_id);
}
the database is saving the image path but not displaying the image on the webpage.
Where you've written
echo '<img src"', $user_data['profile'], '"
change it to
echo '<img src="'.$user_data['profile'].'"
Note the added equals sign and that full-stops instead of commas are used for concatenation.
First of all, I want to isolate some security issues...
When you're uploading a file, the file extension should never be checked. You should simply check the file MIME like so:
class FileSecure
{
public resource $Allowed;
private object $Info;
public function __construct($allow)
{
$this->Allowed = $allow;
$this->Info = new finfo();
}
public function Check($file) : bool
{
if(in_array($fileType = $this->Info->file($file, FILEINFO_MIME_TYPE, $this->Allowed))) { return true; } else { return false; }
}
}
$fileCheck = array(
'Image' => new FileSecure(['image/bmp', 'image/gif', 'image/jpeg', 'image/png']),
'Text' => new FileSecure(['text/plain']),
'Compressed' => new FileSecure(['application/zip', 'application/x-rar-compressed'])
);
// End of Class
($fileCheck['Image']->Check($_FILES['profile']['name']))? "" : die("Invalid image file..."); // make sure you delete the file if it is false
Now back to the Question...
Firstly, we cannot see what your file server so make sure that the file has saved where that path links too.
If it has, var_dump() your queries and ensure that it is the correct path with the correct extension and name.
Secondly, you have a lot of syntax issues which you could easily find yourself by enabling error reporting...
You can do this by: error_reporting(1);
Edit: Note, if you're storing the directory as the datetime (substr(md5(time()), 0, 10)) you will need to include this date into the database path so you know where it is.
Note: When using the isset() you don't need to match it to true or false, you can simple do:
// false
if(!isset($...))
{
}
// true
if(isset($...))
{
}
Is it possible to have something like the following
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<p>Upload File 1</p>
<input type="file" name="profile"/>
<p>Upload File 2</p>
<input type="file" name="cover"/>
<input type="submit" value="Submit" />
</form>
I then have some php script looking like:
if (empty($_POST['save']) === false) {
// FOR PROFIL CHANGE
if (isset($_FILES['profile']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['profile']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['profile']['tmp_name'];
$id = $user_data['id'];
change_image2($id, $file_temp, $file_extn);
}
// FOR COVER CHANGE
if (isset($_FILES['cover']) === true){
$allowed= array('jpg', 'jpeg', 'png', 'bmp');
$file_name = $_FILES['cover']['name']; //name of the file
$file_exts = explode('.', $file_name); // extension of the file
$file_extn = strtolower(end($file_exts)); //inlowercase
$file_temp = $_FILES['cover']['tmp_name'];
$id = $user_data['id'];
change_image3($id, $file_temp, $file_extn);
}
But if I upload just one file ( cover for example ); it is saved also in profile for some reason ...
If find this weird because i gave different names to the inputs.
Can anybody explain the problem please?
Use print_r($_FILES) to check what data you receive when only one file is uploaded.
I think $_FILES['profile'] is always set, no matter if a file is uploaded using the corresponding <INPUT> element or not. You should check if $_FILES['profile']['name'] contains the file name or is empty.
You must also use is_uploaded_file() (and move_uploaded_file()) with $_FILES['profile']['tmp_name'] to handle the file.
is_uploaded_file() is the only authoritative answer to the question: "did the user uploaded a file using this <input> control?"
// FOR PROFIL CHANGE
if (! empty($_FILES['profile']['name'])
&& is_uploaded_file($_FILES['profile']['tmp_name'])){
// ... process the file ...
Change your condition from if (isset($_FILES['profile']) === true){ into if (strlen($_FILES['profile']['tmp_name']) > 0){.
There will be always $_FILES['profile'], but $_FILES['profile']['tmp_name'] contains some data only if there is some file transfer.
I've built a rather straightforward file uploader in PHP. So far I've had no troubles uploading images and zip files. However, I can't seem to upload .mpg's. Whenever I try then it after hanging for a moment the page seems like it didn't try to upload anything at all. For example: this
// This is also manually set in php.ini
ini_set("upload_max_filesize", "524288000");
...
print_r($_FILES);
print_r($_POST); // I'm sending along one variable in addition to the file
returns nothing but empty arrays. For completeness, here's the front-end
<form action="uploadVideo.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000"/>
<input type="hidden" name="extravar" value="value" />
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<i>Accepted formats: .mp4, .3gp, .wmv, .mpeg and .mpg. Cannot exceed 500MB.</i>
</p>
<p>Description:</p>
<textarea name="description" rows="4" cols="40"></textarea>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The file I am testing with is only 33MB and I tested a .wmv of similar size and it uploaded just fine.
Edit: Entire PHP file listed below
<?php
// Ensure that the user can upload up to the maximum size
ini_set("upload_max_filesize", "524288000");
ini_set("post_max_size", "524288000");
print_r($_POST);
print_r($_FILES);
if(!$link = mysql_connect($SERVER_LOCATION, $DB_USER, $DB_PASS)) die("Error connecting to server.");
mysql_select_db($DB_NAME);
$eventID = $_POST['event'];
// Select the event this is associated with
$query = "SELECT eventName FROM event WHERE eventID = $eventID";
if(!$res = mysql_query($query, $link)) die("Error communicating with database.");
$path = mysql_fetch_row($res);
$path = "media/$path[0]";
// If this event doesn't have a media folder, make one
if(!file_exists($path)) {
mkdir($path);
}
// If this event doesn't have a GIS subfolder, make one
$path = "$path/videos";
if(!file_exists($path)) {
mkdir($path);
}
// Generate todays date and a random number for the new filename
$today = getdate();
$seed = $today['seconds'] * $today['minutes'];
srand($seed);
$random = rand(0, 999);
$today = $today['mon']."-".$today['mday']."-".$today['year'];
$fileType = $_FILES["file"]["type"];
$fileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$isMP4 = ($fileType == "video/mp4" && $fileExtension == "mp4");
$isWMV = ($fileType == "video/x-ms-wmv" && $fileExtension == "wmv");
$isMPG = ($fileType == "video/mpeg" && ($fileExtension == "mpeg" || $fileExtension == "mpg"));
$is3GP = ($fileType == "video/3gp" && $fileExtension == "3gp");
$sizeIsOK = ($_FILES["file"]["size"] < 524288000);
if( ($isMP4 || $isWMV || $isMPG || $is3GP) && $sizeIsOK ) {
if($_FILES["file"]["error"] > 0) {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
die();
} else {
// Ensure that the file get's a unique name
$filename = $today . "-" . $random . "." . $fileExtension;
while(file_exists("$path/$filename")) {
$random = rand(0, 999);
$filename = $today . "-" . $random . "." . $fileExtension;
}
move_uploaded_file($_FILES["file"]["tmp_name"], "$path/$filename");
$description = $_POST['description'];
$query = "INSERT INTO media (eventID,FileName,File,filetype,Description) VALUES ($eventID,'$filename','$path','video','$description')";
if(!$res = mysql_query($query, $link))
echo "<p>Error storing file description. Please contact a system administrator.</p>";
else {
echo "<h3>File: <i>".$_FILES["file"]["name"]."</i></h3>";
if(strlen($description) > 0) {
echo "<h3>Description: <i>".$description."</i></h3>";
}
echo "<p><strong>Upload Complete</strong></p>";
}
echo "<button onclick=\"setTimeout(history.go(-1), '1000000')\">Go Back</button>";
}
} else {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
}
?>
You cannot adjust the file upload limits using ini_set() from within the script that the uploads go to - the script does not get executed until after the upload is completed, so the ini_set() overrides cannot take place. The default parameters in PHP will be in place with the lower limit, and will kill the upload if it exceeds the system upload_max_filesize.
You need to override at the .ini level in PHP, or via a php_value directive in a .htaccess file. Those will change PHP's settings as the upload starts.
Ok, the first thing i thougt would be a problem with the filesize but other files with this size are working as you wrote.
But just do get shure it isn't a file size problem:
When you rise the max filesize you hmust also rise the max post size: post_max_size