Php Variable not working in UPLOAD script - php

I have the following script:
<?php
$userid = $_GET['user'];
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../../'.$userid.'/assets/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
echo ' '.$userid;
exit;
}
}
echo '{"status":"error"}';
echo ' '.$userid;
exit;
?>
The problem is in this line:
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../../'.$userid.'/assets/'.$_FILES['upl']['name'])){
When I use this path - everything works fine and the upload is successful:
'../../assets/'.$_FILES['upl']['name']
or
'../assets/'.$_FILES['upl']['name']
or
'assets/'.$_FILES['upl']['name']
All of these three work fine - but when I add the VARIABLE from a GET (from the URL path), it does not work? I know the VARIABLE "userid" is being recognized because I am echoing out before and after the path and it displays on the screen. Also I DID set write permissions on all of the folders, as defined by the VARIABLE.
Any thoughts?
THIS WAS ADDED >>>>>> THIS IS THE FIRST FILE....
<?
$userid = $_GET['user'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Mini Ajax File Upload Form</title>
<!-- Google web fonts -->
<link href="http://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700" rel='stylesheet' />
<!-- The main CSS file -->
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<p style="text-align:center"><? echo $userid; ?></p>
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div id="drop">
Drop Here
<a>Browse</a>
<input type="file" name="upl" multiple />
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</form>
<!-- JavaScript Includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/jquery.knob.js"></script>
<!-- jQuery File Upload Dependencies -->
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<!-- Our main JS file -->
<script src="js/script.js"></script>
</body>
</html>
THIS IS THE PROCESSING FILE....
<?php
$userid = $_GET['user'];
// A list of permitted file extensions
$allowed = array('png', 'jpg', 'gif','zip');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
// if(move_uploaded_file($_FILES['upl']['tmp_name'], '../../'.$userid.'/assets/'.$_FILES['upl']['name'])){
if(move_uploaded_file($_FILES['upl']['tmp_name'], '../../'.$userid.'/assets/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
echo ' '.$userid;
exit;
}
}
echo '{"status":"error"}';
echo ' '.$userid;
exit;
?>

Unless you're creating a subdirectory in ../../ for each and every user manually, you need to create the directory for that user before trying to move the files to it.
if(!file_exist("../../$userid/")
mkdir("../../$userid/");
... and then you can move your file to it.

Related

Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\izul\Aplikasi Konversi\convert.php on line 15

i try make picture handler form, but get this error
Warning: fopen(): Filename cannot be empty in C:\xampp\htdocs\App\convert.php on line 15
this full code :
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>File Upload Converter Result</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<header>
<h1>File Upload Converter Result</h1>
</header>
<?php
$isi = fopen($_FILES[$_GET["myfiles"]]["tmp_name"], 'r');
?>
<div class="badan">
<p>File Name :</p>
<?php
$values = $_GET["myfiles"];
if (is_array($values) || is_object($values))
{
foreach ($values as $value)
{
echo("<p>". $value ."</p>");
}
}
?>
<p>File Old Type : <?php echo($_GET["tipe1"]) ?></p>
<p>File New Type : <?php echo($_GET["tipe2"]) ?></p>
<img src="<?php echo($isi) ?>" alt="<?php echo($isi) ?>">
</div>
</body>
</html>
can someone help me? thanks.
$_FILES[$_GET["myfiles"]]["tmp_name"]
should be
$_FILES["myfiles"]["tmp_name"]
And if you're having multiple files (what the name "myfiles" suggests), then you need to threat that whole thing as an array:
foreach($_FILES["myfiles"]["tmp_name"] as $filename) {
$isi = fopen($filename, 'r');
}
unset($filename);
That however:
<img src="<?php echo($isi) ?>" alt="<?php echo($isi) ?>">
Makes no sense. Fopen returns a file pointer resource, not any text content. To read the content of a file, you can use:
$isi = file_get_contents($filename);
But even then, using the content as the src-attribute or alt-attribute doesn't make any sense. With the src-attribute you link to a file and the alt-attribute displays an alternative text if, for whatever reason, the file cannot be loaded.

How to show user the URL once image uploaded

I am looking for a way where when a user uploads a image in PHP it shows them the URL to the file.
My current upload.php is the following:
<?php
if(!empty($_FILES)){
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'codexworld';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$targetDir = "http://wotm8.net/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
$conn->query("INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
}
}
?>
Ignore the database. I don't use that
if you need the index file or anything else then ask.
HTML PAGE
<!DOCTYPE html> <html> <head><meta http-equiv="Content-Type" content="text/html; charset=gb18030">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="google-site-verification" content="_wLD3KO_vuO5czv-n-j9YrXxO3OtQuGc6C51vOaRHMU" />
<title>wotm8.net 路 File Hosting</title>
<link rel="stylesheet" type="text/css" href="css/dropzone.css" />
<script type="text/javascript" src="js/dropzone.js"></script>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="build.css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1 id="logo">wotm8.net</h1>
<p class="lead">Max upload size is 75MiB, read the FAQ</p>
<noscript>
<p class="alert alert-error"><strong>Enable JavaScript</strong> you autist neckbeard, it's not gonna hurt you</p>
</noscript>
<p id="no-file-api" class="alert alert-error"><strong>Your browser is shit.</strong> Install the latestFirefox or Botnet and come back <3</p>
<div class="fileUpload btn btn-primary">
<form action="upload.php" class="dropzone" data-max-size="75MiB">
</div>
</form>
<ul id="upload-filelist"></ul>
<audio id="sickerMeme" src="meme.mp3" />
<script>
var i = 0, text;
var str = "Dude, that's a sick meme.";
function start(){
// document.getElementById("sickerMeme").play();type();
}
/* Credits: https://jsfiddle.net/creed88/VG8MJ/1/ */
function type(){
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('logo').innerHTML = text;
setTimeout(type, 80);
}
</script>
</div>
<!-- Leo5gg lol -->
<nav>
<ul>
<li>Index</li>
<li>FAQ</li>
<li>Contact</li>
</ul>
</nav>
<script src="main.js"></script>
</div>
</body>
</html>
I think your upload directory is $targetFile
You can echo it out or return it in any way you think is safe
Like after insert into database
echo $targetFile;
EDIT
Your target dir should be a absolute path, not a website link, should be something like /var/www/folder/
I doubt your upload is working in the example you posted.
after you manage to make the upload successful, just echo your domain + relative folder ( if any) + filename.

php video file upload and play using videoJS

im trying to upload a video file into db and play it with videoJS player.
Everything ok but the video doesn't work and it shows loading icon and there it stops and the video is not played. does anyone can find out whats wrong? im using video js www.videojs.com
This is the index.php file:
<html>
<head>
<title>Video Upload System</title>
<link rel='stylesheet' href='style.css' />
</head>
<body>
<?php
include 'connect.php';
?>
<div id='box'>
<form method="post" enctype='multipart/form-data'>
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['size'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'MP4' && $type != 'avi'){
$message = "Video Format Not Supported";
}else{
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysqli_query($connect, "INSERT INTO cinema VALUES ('','$name','$random_name.$type')");
$message = "Successfully Uploaded";
}
echo "$message <br/><br/>";
}
?>
Select Video: <br/>
<input type='file' name='video' />
<br><br>
<input type='submit' value='Upload Video'/>
</form>
</div>
<div id='box'>
<?php
$query = mysqli_query($connect, "SELECT id, name, url FROM cinema");
while ($run = mysqli_fetch_array($query)){
$video_id = $run['id'];
$video_name = $run['name'];
$video_url = $run['url'];
?>
<a href="view.php?video=<?php echo $video_url; ?>">
<div id='url'>
<?php echo $video_name; ?>
</div>
</a>
<?php
}
?>
</div>
</body>
</html>
and this is the view.php file:
<!doctype html>
<html lang="en">
<head>
<title>Video Upload System</title>
<link rel='stylesheet' href='style.css' />
<link href="http://vjs.zencdn.net/4.2/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.2/video.js"></script>
</head>
<body>
<?php
include 'connect.php';
?>
<div id='box'>
<?php
$video = $_GET['video'];
?>
<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered"
controls preload="auto" width="640" height="264"
poster="http://video-js.zencoder.com/oceans-clip.png"
data-setup='{"example_option":true}'>
<source src="<?php echo $video; ?>" type="video/mp4">
</video>
</div>
</body>
</html>
You can download the latest videojs(zip) player here: http://www.videojs.com/
Extract the zip file and use the demo.html you probably need to build in autoplay = yes, or something like that.
<html>
<head>
<link href="http://vjs.zencdn.net/4.11/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.11/video.js"></script>
</head>
<body>
<body>
<?php
if(isset($_FILES['video'])){
$name = $_FILES['video']['name'];
$type = explode('.', $name);
$type = end($type);
$size = $_FILES['video']['size'];
$random_name = rand();
$tmp = $_FILES['video']['tmp_name'];
if($type != 'mp4' && $type != 'MP4' && $type != 'avi'){
$message = "Video Format Not Supported";
}else{
move_uploaded_file($tmp, 'videos/'.$random_name.'.'.$type);
mysqli_query($connect, "INSERT INTO cinema VALUES ('','$name','$random_name.$type')");
$message = "Successfully Uploaded";
}
echo "$message <br/><br/>";
}
?>
<div id='box'>
<form method="post" enctype='multipart/form-data'>
Select Video: <br/>
<input type='file' name='video' />
<br><br>
<input type='submit' value='Upload Video'/>
</form>
<video id="MY_VIDEO_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="MY_VIDEO_POSTER.jpg"
data-setup="{}">
<source src="MY_VIDEO.mp4" type='video/mp4'>
<source src="MY_VIDEO.webm" type='video/webm'>
<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video</p>
</video>
</body>
</html>

Image not moved from tmp dir to another folder in linux server

I have designed a web site which takes image as input and by using ajax I have displayed the image.It was working fine locally but when I uploaded it into the server the image is not shown. The process that takes place is: 1)User uploads an image 2)The image is stored in a temporary folder by default 3)The image that is stored in the temporary folder is moved to a folder upload 4) The image is displayed in a div. I checked the path but it seems okay for me. I will post the code for review:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="MainStyleSheet.css" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="html5slider.js"></script>
<script type="text/javascript" src="scripts/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#file').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="images/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
</script>
<script type="text/javascript">
function myfunction()
{
$("#display").html('');
$("#display").html('<img src="images/loader.gif" alt="Uploading...."/>');
$("#retrieveimageform").ajaxForm(
{
target: '#display'
}).submit();
$("#tagsform").ajaxForm(
{
target: '#tags'
}).submit();
};
</script>
<title></title>
</head>
<body>
<div id="maindiv">
<div id="banner">
<?php
include 'Header.php';
?>
</div>
<div id="wrapper">
<div id="imageupload">
<form action="uploadimage.php" method="post"
enctype="multipart/form-data" id="imageform">
<label for="file">Upload your image:</label>
<input type="file" name="file" id="file"><br>
</form>
</div>
<div id='preview'>
</div>
<div id='tags'>
</div>
</form>
<div class="clear"></div>
........................................
<div id="footer">
<?php
include 'Footer.php';
?>
</div>
</div>
<div id='screen'>
</div>
</body>
</html>
The uploadimage.php contains:
<?php
session_start();
$allowedExts=array("gif","jpeg","jpg","png");
$extension= end(explode(".", $_FILES["file"]["name"]));
if((($_FILES["file"]["type"]=="image/gif")
||($_FILES["file"]["type"]=="image/jpeg")
||($_FILES["file"]["type"]=="image/jpg")
||($_FILES["file"]["type"]=="image/png"))
&& ($_FILES["file"]["size"]<2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"]>0)
{
echo "Error:".$_FILES["file"]["error"]."<br>";
}
else{
// echo "Upload: ".$_FILES["file"]["name"]."<br>";
// echo "Store in: ".$_FILES["file"]["tmp_name"]."<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$_FILES["file"]["name"]);
//echo "Stored in "."upload/".$_FILES["file"]["name"];
echo "<img src='upload/".$_FILES["file"]["name"]."' class='preview' height='300' width='250'>";
$_SESSION['img']="upload/".$_FILES["file"]["name"];
}
}
else
{
echo "Invalid file";
}
?>
In the server the image is not stored in the upload folder when the user given an input and the image is not shown. Any solutions?:Please help. The server is linux server.
The problem is with file permission.
use the following command
sudo chmod 777 absolute_path_of_you_dir
on Ubuntu.

Upload Photo from iPhone to PHP Using PhoneGap

I have a simple upload form working in PHP (works in web) and also am able to capture a photo from iPhone using PhoneGap (base64) and displaying it on the device.
But I can't figure out how to upload it to my server with PHP.
Here's the code running in PHP:
INDEX.PHP
<?
//print_r($_POST);
if($_POST["action"] == "Upload Image")
{
unset($imagename);
if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;
if(!isset($_FILES['image_file']))
$error["image_file"] = "An image was not found.";
$imagename = basename($_FILES['image_file']['name']);
//echo $imagename;
if(empty($imagename))
$error["imagename"] = "The name of the image was not found.";
if(empty($error))
{
$newimage = "images/" . $imagename;
//echo $newimage;
$result = #move_uploaded_file($_FILES['image_file']['tmp_name'], $newimage);
if(empty($result))
$error["result"] = "There was an error moving the uploaded file.";
}
}
include("upload_form.php");
if(is_array($error))
{
while(list($key, $val) = each($error))
{
echo $val;
echo "<br>\n";
}
}
include("list_images.php");
?>
And here are the two includes...
UPLOAD_FORM.PHP
<form method="POST" enctype="multipart/form-data" name="image_upload_form" action="<?$_SERVER["PHP_SELF"];?>">
<p><input type="file" name="image_file" size="20" value="beautiful.jpg"></p>
<p><input type="submit" value="Upload Image" name="action"></p>
</form>
LIST_IMAGES.PHP
<?
$handle = #opendir("images");
if(!empty($handle))
{
while(false !== ($file = readdir($handle)))
{
if(is_file("images/" . $file))
echo '<img src="images/' . $file . '"><br><br>';
}
}
closedir($handle);
?>
Here's the code running on iPhone 4 (iOS 4.2) in PhoneGap
INDEX.HTML (running in WWW directory in PhoneGap)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=yes" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="style.css">
<!-- iPad/iPhone specific css below, add after your main css >
<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />
<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />
-->
<!-- If you application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.min.js"></script>
<script type="text/javascript" charset="utf-8">
// If you want to prevent dragging, uncomment this section
/*
function preventBehavior(e)
{
e.preventDefault();
};
document.addEventListener("touchmove", preventBehavior, false);
*/
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* When this function is called, PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
// do your thing!
}
function getPicture(sourceType)
{
var options = { quality: 10 };
if (sourceType != undefined) {
options["sourceType"] = sourceType;
}
// if no sourceType specified, the default is CAMERA
navigator.camera.getPicture(getPicture_Success, null, options);
};
function getPicture_Success(imageData)
{
//alert("getpic success");
document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
}
</script>
</head>
<body onload="onBodyLoad()" marginheight=0 marginwidth=0 leftmargin=0 topmargin=0>
<h1>Camera</h1>
<img style="width:80px;height:120px" id="test_img" src="" />
<p>
<!-- for testing, add the buttons below -->
<button onclick="getPicture()">From Camera</button>
<p>
<button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From Photo Library</button>
</body>
</html>
</html>
Incidentally, while I can grab a fresh picture from the device camera, I've been completely unable to get images from the Library... if anyone knows how to do that, I'd appreciate feedback there too.
Had anyone been able to upload photos from PhoneGap/iPhone to PHP? Any source code on both sides of this would be GREATLY appreciated.
The Base64 option is really just for ease of displaying on the webpage. if it's not needed then don't use it.
i'd say your best option is to use FILE_URI instead of DATA_URL for Camera.DestinationType
check out http://docs.phonegap.com/phonegap_camera_camera.md.html for more info
Use options PHOTOLIBRARY or SAVEDPHOTOALBUM to get existing pictures from your phone. See more at http://docs.phonegap.com/en/1.4.0/phonegap_camera_camera.md.html#Camera.
In phonegap:
$.post(URLReport,{
pic1: document.getElementById("image1").src.slice(23),
}, function(xml) {
//stuff to do on success
});
On server:
if (isset($_POST['pic1'])) {
$pic = base64_decode( $_POST['pic1']);
if (strlen($pic) > 9 ) {
$fh = fopen(yourfilename, 'w') or die("can't open file");
fwrite($fh, $pic);
fclose($fh);
}
}
Easy peasy.

Categories