I have uploaded the project on the server every thing is working fine except for the few things.
I am not able to uplaod the file images on the server please check the errors.
I have even set the permission to 777.
Warning: move_uploaded_file(../images/fail to upload.jpg): failed to open stream: No such file or directory in /srv/disk14/2293074/www/cms.mohsinyounas.info/admin/includes/add_posts.php on line 15
Warning: move_uploaded_file(): Unable to move '/tmp/phpx2WZ8c' to '../images/fail to upload.jpg' in /srv/disk14/2293074/www/cms.mohsinyounas.info/admin/includes/add_posts.php on line 15
Thank you.
<?php
include "./function.php";
global $con;
if(isset($_POST['create_post'])) {
$post_image = $_FILES['post_image']['name'];
$post_image_temp = $_FILES['post_image']['tmp_name'];
move_uploaded_file("$post_image_temp","../images/$post_image");
$sql = "INSERT INTO posts (post_image) VALUES ('$post_image')";
$result = mysqli_query($con,$sql);
confirm($result);
}
?>
Change this code you have to remove "" from variable in move_uploaded_file()
<?php
include "./function.php";
global $con;
if(isset($_POST['create_post'])) {
$post_image =$_FILES['post_image']['name'];
$post_image_temp =$_FILES['post_image']['tmp_name'];
$path = "../images/".$post_image;
move_uploaded_file($post_image_temp,$path);
$sql = "INSERT INTO posts (post_image)
VALUES ('$post_image')";
$result=mysqli_query($con,$sql);
confirm($result);
}
?>
Related
I am creating something like google drive or some cloud using PHP and HTML where you can save your files but i have problem with saving files to binary code and uploading it to database. I mean i want to do something like that:
User is uploading file by form in html -> converting file to binary -> saving it in database.
User can download his file by some button or smh like that -> file is converting from binary to file.
I tried with doing a script what will save bin code in my database but when i am trying to send some files i am getting error like that:
Fatal error: Uncaught TypeError: fopen(): Argument #1 ($filename) must be of type string, array given in C:\xampp\htdocs\fileshub\src\send_file.php:12 Stack trace: #0 C:\xampp\htdocs\fileshub\src\send_file.php(12): fopen(Array, 'rb') #1 {main} thrown in C:\xampp\htdocs\fileshub\src\send_file.php on line 12
This is my form in html:
<form class="upload-form" action="./src/send_file.php" method="post" enctype="multipart/form-data"><br>
<input type="text" name="filename" id="filename" placeholder="File name">
<input type="file" name="file" id="file"><br>
<button type="sumbit" class="submit">Submit</button>
</form>
And this is my script in php:
<?php
session_start();
include "../src/db_conn.php";
if(isset($_SESSION['id'])) {
$id = $_SESSION['id']; // id usera
$filename = $_POST['filename']; // nazwa pliku
$file = $_FILES['file'];
$data = fopen ($file, 'rb');
$size = filesize ($file);
$contents = fread ($data, $size);
fclose ($data);
$binfile = base64_encode($contents);
if(!$filename|| !$file) {
header("Location: ../index.php?error=Enter your data!");
exit();
} else {
$check = "SELECT bin_code FROM files WHERE user_id = '$id' AND bin_code = '$binfile' AND file_name = '$filename'";
$result = mysqli_query($conn, $check);
if(mysqli_num_rows($result) === 1){
header("Location: ../index.php?error=Your file exsist.");
exit();
}else {
$save = "INSERT INTO files (user_id, file_name, bin_code) values('$id', '$filename', $binfile)";
$saveresult = mysqli_query($conn, $save);
$saveresult;
header("Location: ../index.php?error=Your file has been saved");
exit();
}
}
}
?>
db_conn:
<?php
$server = "localhost";
$user ="root";
$password = "";
$db = "fileshub";
$conn = mysqli_connect($server, $user, $password, $db);
?>
If you know any solutions for my problem please help :)
Files table
Users table and example user
I believe you know that uploading an image to a directory is a more efficient way to store it.
Please note that $_FILES['file'] is an array containing all sorts of information of the uploaded file, for your case you have to use the filename of the uploaded file. (which is "tmp_name")
So change
$file = $_FILES['file'];
$data = fopen ($file, 'rb');
to
$file = $_FILES['file']["tmp_name"];
$data = fopen ($file, 'rb');
On the other hand, an alternative way is to use file_get_contents instead of fopen, fread, etc.
$contents = file_get_contents($_FILES['file']["tmp_name"]);
So firstly you need to ensure you have a directory that PHP has access and has permissions on but that is not publicly accessible. Usually, on web hosts the web root folder is a sub folder of the home directory, so you can create a new folder there for file storage. Eg:
/home/myuser/public_html/ <-- might be the web root (some installations differ eg: htdocs or html or httpdocs)
/home/myuser/files/ <-- Create this folder for storing files.
Alternatively, if youre web server is Apache, you can create a folder inside your web root, and protect that folder using a .htaccess file
The easiest way then to store an uploaded file on the file server is to use the move_uploaded_file command that PHP provides, here is how I would achieve this:
$postname = 'file';
$root = '/home/myuser/files';
//cleanse the filename to prevent SQL injections when saving to DB
$filename = preg_replace("/[^a-zA-Z0-9\.]/","_",$_FILES[$postname]['name']);
$path = "$root/$filename";
//Create the files folder if it doesnt already exist...
if(!file_exists($root)) if(!mkdir($root,0775,true)) die("Failed to create root folder $root");
//Store the uploaded file in the files folder
if(!move_uploaded_file($_FILES[$postname]['tmp_name'],$path)) die('Failed to move uploaded file into asset storage');
//Store the file location in the database...
$saveresult = mysqli_query($conn,"INSERT INTO `files` (`filename`,`path`) VALUES ('$filename','$path')");
I am making a form in which user can upload data + an image if he likes using jquery ajax and PHP . So far everything works well on the data side, but on the image upload PHP i am having a problem uploading the file to the right location. The query is working fine and submitting the right data to the table. Can you please help me with the image upload. I tried to debug by using a couple of things but so far everything looks right.
here is my php file script:
if(isset($_POST['discussion_title'], $_POST['discussion_subjects'], $_POST['discussion_textarea'])) {
$user_id = (int)$_SESSION['user_id'];
$title = mysql_prep($_POST['discussion_title']);
$link = mysql_prep($_POST['discussion_link']);
$subject = mysql_prep($_POST['discussion_subjects']);
$discussion = mysql_prep($_POST['discussion_textarea']);
$discussion_timestamp = time();
if ($_FILES["discussion_image"]["name"] != "") {
$test = explode(".", $_FILES["discussion_image"]["name"]);
$extension = end($test);
$name = rand(100, 9999999999);
$file_temp = $_FILES['discussion_image']['tmp_name'];
$file_path = 'uploaded_pictures/uploads/' . $user_id . '/'. $name .'.'.$extension;
$file_path = mysqli_real_escape_string($connection, $file_path);
move_uploaded_file($file_temp, $file_path); // move_uploaded_file() is a built in function of PHP
$query = "INSERT INTO discussions_table (user_id, title, link, image_link, subject, discussion, discussion_timestamp) VALUES ($user_id, '$title', '$link', '$file_path', '$subject', '$discussion', $discussion_timestamp)";
//$save_path = "uploaded_pictures/uploads/" . $user_id ."/$user_id.png";
$save_path = 'uploaded_pictures/uploads/' . $user_id . '/'. $name.'.'.$extension;
$save_path_small = "uploaded_pictures/uploads/" . $user_id . "/" . $name.'small.'.$extension;
create_thumbnail($file_path, $save_path, 250, 250); // creates thumbnail for profile picture
create_thumbnail($file_path, $save_path_small, 50, 50); // creates thumbnail for small user picture
var_dump($_FILES['discussion_image']['tmp_name']);
} else {
$query = "INSERT INTO discussions_table (user_id, title, link, subject, discussion, discussion_timestamp) VALUES ($user_id, '$title', '$link', '$subject', '$discussion', $discussion_timestamp)";
}
$result = mysqli_query($connection, $query);
}
and here is the error being given in the alert() because i used var_dump
Warning: move_uploaded_file(uploaded_pictures/uploads/20/499297822.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in D:\wamp\www\asserter\widgets\discussion_board_submit.php on line 22
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:\wamp\tmp\php260.tmp' to 'uploaded_pictures/uploads/20/499297822.jpg' in D:\wamp\www\asserter\widgets\discussion_board_submit.php on line 22
Warning: getimagesize(uploaded_pictures/uploads/20/499297822.jpg) [function.getimagesize]: failed to open stream: No such file or directory in D:\wamp\www\asserter\includes\create_thumbnail.php on line 4
Warning: getimagesize(uploaded_pictures/uploads/20/499297822.jpg) [function.getimagesize]: failed to open stream: No such file or directory in D:\wamp\www\asserter\includes\create_thumbnail.php on line 4
string(22) "D:\wamp\tmp\php260.tmp"
ok it worked. Thanks everyone for your help. The problem was with the directory, i should go back ../ to be able to upload the image
How to create directory in php? - Use this to create directories, I have answered over there. It will help you to create directories for multi-user. Later you can get which user has uploaded what all files.
for error Undefined offset : 1 in php you should set the values using isset() for
$src_pos[1] , $new_size[0], $new_size[1], $size[0], $size[1]
Hello so i have a simple upload system in php and i want to upload my files to ftp server but when i try to it doesnt work i get these two errors:
Warning: move_uploaded_file(/userfiles/grega): failed to open stream: No such file or directory in /srv/disk3/1618233/www/netdisk.co.nf/upload.php on line 19
Warning: move_uploaded_file(): Unable to move '/tmp/phpVtApVM' to '/userfiles/grega' in /srv/disk3/1618233/www/netdisk.co.nf/upload.php on line 19
and there is folder userfiles/grega on the ftp server please help me out
the code:
<?php
require_once 'core/init.php';
if($_POST[submit]) {
$name = $_FILES['upload']['name'];
$temp = $_FILES['upload']['tmp_name'];
$type = $_FILES['upload']['type'];
$size = $_FILES['upload']['size'];
if($size <= 5000000){
$user = new User();
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
$uploads_dir = '/userfiles';
$username = ($user->data()->username);
move_uploaded_file($temp,"$uploads_dir/$username");
Session::flash('home', '<h3>Datoteka je bila naložena!</h3>');
Redirect::to('mojprofil.php');
} else{
echo "Napaka!";
}
} else {
header("Location: mojprofil.php");
}
?>
You say this:
there is folder userfiles/grega
But the error says this:
move_uploaded_file(/userfiles/grega)
Those are two very (even if subtly) different paths. Note also where you define the path in your code:
$uploads_dir = '/userfiles';
The code is looking for a folder called userfiles in the root of the entire file system, not just in the website. Perhaps you meant to do this?:
$uploads_dir = 'userfiles';
i have a problem with the move_uploaded_file function this is the problem:
Warning: move_uploaded_file(/imagenes/Icon.png) [function.move-uploaded-file]: failed to >open stream: No such file or directory in /home/decc98/public_html/php/insert.php on line 6
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpIBBh5U' >to '/imagenes/Icon.png' in /home/decc98/public_html/php/insert.php on line 6
Insercion exitosa
Other stuff, i speak spanish so part of my code is in spanish... Anyways, my code is:
<?php
include "conexion.php";
$ruta = "/imagenes";
$archivo = $_FILES['imagen']['tmp_name'];
$nombreArchivo = $_FILES['imagen']['name'];
move_uploaded_file($archivo,$ruta."/".$nombreArchivo);
$ruta=$ruta."/".$nombreArchivo;
$texto = $_POST['descripcion'];
$id = rand(1,200);
$insertar = mysql_query("INSERT INTO tablaUno VALUES('".$id."','".$ruta."','".$texto."')");
if ($insertar) {
echo "Inserción exitosa";
}else{
echo "Fallo en la inserción";
}
?>
Please if anyone can help me I would appreciate it!
You need to use a relative path instead of an absolute path.
For example:
$ruta = "imagenes";
leaving out the / at the beginning of your folder name, if you're using your script from the root.
Or, something like:
$ruta = "../imagenes";
depending on the script execution's location.
Note: Using / is mostly used for an (server) absolute path, something to the affect of:
/var/user/user123/public_html/imagenes
I'm trying to set up some image handling for a webpage I'm creating, but I can't get move_uploaded_file() to work properly... I keep getting these errors:
Warning: move_uploaded_file(/htdocs/PHP/Pictures/picture.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /opt/lampp/htdocs/PHP/useredit.php on line 17
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpY0KKxH' to '/htdocs/PHP/Pictures/picture.jpg' in /opt/lampp/htdocs/PHP/useredit.php on line 17
My code looks like this:
if(isset($_FILES['image_file']))
{
$img_tmp_name = $_FILES['image_file']['name'];
$img_dir = "/htdocs/PHP/Pictures/";
$img_name = $img_dir . $img_tmp_name;
if(move_uploaded_file($_FILES['image_file']['tmp_name'],$img_name))
{
list($width,$height,$type,$attr) = getimagesize($img_name);
switch($type)
{
case 1:
$ext = ".gif";
break;
case 2:
$ext = ".jpg";
break;
case 3:
$ext = ".png";
break;
default:
echo "Image format not accepted";
}
$query = "UPDATE profile_pic SET img_path=$img_name WHERE uid='$uid'";
$img_id = mysql_insert_id();
$new_img_name = $img_dir . $img_id . $ext;
rename($img_name, $new_img_name);
}
}
if(mysql_query($query)or die('Error: ' . mysql_error()))
{
header("Refresh:0; url='control.php'");
}
The folder PHP/Pictures exist. How do I fix this?
You've got some major security and logistical problems with this code:
a) You don't check if the upload succeeded and proceed as if it has. There's exactly ONE way for an upload to succeed, and far too many reasons for it to fail.
if ($_FILES['image_file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code {$_FILES['image_file']['error']}");
}
b) You're using the filename provided by the user in the path to save on your server. A malicious user can embed pathing data in that filename and specify any location on your server they want. e.g.
$_FILES['image_file']['name'] = '../../../../../../etc/passwd';
$img_dir should contain a path relative to you current file and not from root folder.
if your current directory contains upload_file.php (ur code) and a folder hierarchy like PHP/Pictures/
then $img_dir="/PHP/Pictures/";