PHP upload script - php

Using this upload script and it was working ok a week ago but when i checked it today it fails. I have checked writ privileges on the folder and it is set to 777 so don't think that is the problem. Anyone have a idea of what the problem can be?
this is the error
Warning: move_uploaded_file() [function.move-uploaded-file]:
Unable to access replays/1275389246.ruse in
/usr/home/web/wno159003/systemio.net/ruse.systemio.net/scripts/upload.php on line 95
my script is
<?php
require($_SERVER['DOCUMENT_ROOT'].'/xxxx/xxxx');
$connection = #mysql_connect($db_host, $db_user, $db_password) or die("error connecting");
mysql_select_db($db_name, $connection);
$name = basename($_FILES['uploaded']['name']);
$comment = $_POST["comment"];
$len = strlen($comment);
$username = $_POST["username"];
$typekamp = $_POST["typekamp"];
$date = time();
$target = "replays/";
$target .= basename($_FILES['uploaded']['name']);
$maxsize = 20971520; // 20mb Maximum size of the uploaded file in bytes
// File extension control
// Whilelisting takes preference over blacklisting, so if there is anything in the whilelist, the blacklist _will_ be ignored
// Fill either array as you see fit - eg. Array("zip", "exe", "php")
$fileextensionwhitelist = Array("ruse"); // Whilelist (allow only)
$fileextensionblacklist = Array("zip", "exe", "php", "asp", "txt"); // Blacklist (deny)
$ok = 1;
if ($_FILES['uploaded']['error'] == 4)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
die("No file was uploaded");
}
if ($_FILES['uploaded']['error'] !== 0)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
die("An unexpected upload error has occured.");
}
// This is our size condition
if ($_FILES['uploaded']['size'] > $maxsize)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "Your file is too large.<br />\n";
$ok = 0;
}
// This is our limit file type condition
if ((!empty($fileextensionwhitelist) && !in_array(substr(strrchr($_FILES['uploaded']['name'], "."), 1), $fileextensionwhitelist)) || (empty($fileextensionwhitelist) && !empty($fileextensionblacklist) && in_array(substr(strrchr($_FILES['uploaded']['name'], "."), 1), $fileextensionblacklist)))
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "This type of file has been disallowed.<br />\n";
$ok = 0;
}
// Here we check that $ok was not set to 0 by an error
if ($ok == 0)
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "Sorry, your file was not uploaded. Refer to the errors above.";
}
// If everything is ok we try to upload it
else
{
if($len > 0)
{
$target = "replays/".time().'.'."ruse";
$name = time().'.'."ruse";
$query = "INSERT INTO RR_upload(ID, filename, username, comment, typekamp, date) VALUES (NULL, '$name', '$username','$comment', '$typekamp' ,'$date')";
if (file_exists($target))
{
$target .= "_".time().'.'."ruse";
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo "File already exists, will be uploaded as ".$target;
}
mysql_query($query, $connection) or die (mysql_error());
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo (move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
? "The file ".basename( $_FILES['uploaded']['name'])." has been uploaded. \n"
: "Sorry, there was a problem uploading your file. <br>";
echo "<br>Variable filename: ".$name;
echo "<br>Variable name: ".$username;
echo "<br>Variables comment: ".$comment;
echo "<br>Variables date: ".$date;
echo "<br>Var typekamp; ".$typekamp;
echo "<br>Var target; ".$target;
}
else
{
echo "<html><head><title>php</title></head>";
echo '<body bgcolor="#413839" text="#ffffff">
<p><B>info</b></p>';
echo"you have to put in comment/description";
}
}
?>

Assuming the "replays" directory is in the document root, does the warning persists if you replace this line :
$target = "replays/";
by this one :
$target = $_SERVER['DOCUMENT_ROOT']."replays/";
?

Related

How to Upload the Same File in Different Names for Each Users Using Foreach

other queries working through the foreach loop.but file upload for 1st index of array.this is not multiple file upload.i wanna upload same file in different names for each users.
foreach($_POST['groupmem'] as $user){
//Some Queries
$filename2 = str_replace(" ", "_","{$user}.{$_FILES['proposal']['name']}");
$destination2 = '../img/proposal/' . $filename2;
$extension2 = pathinfo($filename2, PATHINFO_EXTENSION);
$file2 = $_FILES['proposal']['tmp_name'];
$size2 = $_FILES['proposal']['size'];
if (!in_array($extension2, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['proposal']['size'] > 200000000) { // file shouldn't be larger than 200Megabyte
echo "File too large!";
} else {
if (move_uploaded_file($file2, $destination2)) {
$sql = "UPDATE project SET proposal_name='$filename2' WHERE u_id='{$user}' ";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
} else {
echo "Failed to upload file.";
}
}
}
you can not do move_uploaded_file inside the loop
$user1 = $_POST['groupmem'][0];
$filename1 = str_replace(" ", "_","{$user1}.{$_FILES['proposal']['name']}");
$destination1 = '../img/proposal/' . $filename1;
$extension1 = pathinfo($filename1, PATHINFO_EXTENSION);
$file1 = $_FILES['proposal']['tmp_name'];
$size1 = $_FILES['proposal']['size'];
if (!in_array($extension1, ['zip', 'pdf', 'docx'])) {
echo "You file extension must be .zip, .pdf or .docx";
} elseif ($_FILES['proposal']['size'] > 200000000) { // file shouldn't be larger than 200Megabyte
echo "File too large!";
} else {
if (move_uploaded_file($file1, $destination1)) {
foreach($_POST['groupmem'] as $user){
$filename2 = str_replace(" ", "_","{$user}.{$_FILES['proposal']['name']}");
$destination2 = '../img/proposal/' . $filename2;
if ($user <> $user1) {
if (!copy($destination1, $destination2)) echo "failed to copy $file...\n";
}
$sql = "UPDATE project SET proposal_name='$filename2' WHERE u_id='{$user}' ";
if (mysqli_query($conn, $sql)) {
echo "File uploaded successfully";
}
}
} else {
echo "Failed to upload file.";
}
}

Trouble with php upload

I am working on php upload and i have an issue on how to automatically rename a file it does exist already in file folder. Could you give me any road or tips about it? thanks
here is my full code - the code is for testing purpose only
$destination = 'C:/upload_test/';
$max=75200;
if (isset($_POST['upload'])) {
if (isset($_FILES['image']['tmp_name'])) {
$fileTaille= $_FILES['image']['size'];
if ($fileTaille==true) {
if ($fileTaille > $max) {
echo "Your file is too large, select a file smaller than". " ".$fileTaille;
exit(include 'form.php');
}
}
else {
echo "No file selected";
exit(include 'form.php');
}
}
$file_type=getimagesize($_FILES['image']['tmp_name']);
if ($file_type==true) {
echo "File is an image - " .$file_type["mime"]." ";
}
else{
echo "Could not get file type";
}
$fileType = exif_imagetype($_FILES['image']['tmp_name']);
$allowed = array(IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF);
if (!in_array($fileType, $allowed)) {
echo "File type not accepted, Only JPEG file allowed";
exit(include 'form.php');
}
$sanitize_file = preg_replace("/[^A-Z0-9\.\_-]/i", " ", $_FILES["image"]["name"]);
$fileName = $recipient . basename($recipient);
if (file_exists($fileName)) {
echo "File already exist";
exit(include 'form.php');
}
}
if (isset($_FILES['image']['tmp_name'])) {
$result = move_uploaded_file($_FILES['image']['tmp_name'], $recipient . $sanitize_file);
if ($result == true) {
echo "file moved "." ";
}else
{
echo "Could not move filed";
}
$permission = chmod($$recipient . $sanitize_file, 0644);
if ($permission==false) {
echo "No permission to the file";
}
else
{
echo "permission given";
}
}

How to upload ONLY images in database

I want to upload ONLY pictures , in the database using php.
What I tried is,
<?php
if (isset($_POST['Upload'])) {
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("iis", $con);
$image = $_FILES["product_image"]["name"];
$imageType = mysql_real_escape_string($_FILES["product_image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
if (!file_exists("product_images")) {
mkdir("product_images");
}
if ($_FILES["product_image"]["error"] > 0) {
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/" . $_FILES["product_image"]["name"]);
}
}
$UserName = $_SESSION['id'];
$product_image = ("product_images/" . $_FILES["product_image"]["name"]);
mysql_query("INSERT INTO `feedbackzxc` VALUES ('', '$UserName', '$product_image')");
echo "Image Uploaded!";
} else {
echo "Only images are allowed";
}
?>
But when I upload a file other than images it doesn't show the error message. How can I make it show error message if a file other than an image is uploaded?
Your else block where the message Only images are allowed is shown must be located after the if block that check this: substr($imageType,0,5) == "image"
if(substr($imageType,0,5) == "image"){
if(!file_exists("product_images"))
{
mkdir("product_images");
}
if($_FILES["product_image"]["error"] > 0)
{
$error = "ERROR Return Code :" . $_FILES["product_image"]["error"] . "<br />";
}
else
{
move_uploaded_file($_FILES["product_image"]["tmp_name"], "product_images/".
$_FILES["product_image"]["name"]);
}
}
else
{
echo "Only images are allowed";
}

save image to mysql with php

i created this form to add my images to mysql database,and i think i did it right-cause it saves something :D - but it wont show me the image, what should i do to "SEE" the image from mysql?!
this is my form php:
$tmp_name=$_FILES['file']['tmp_name'];
if (isset($_POST['submit'])) {
if ((($_FILES['file']['type']) == "image/jpeg")
|| ($_FILES['file']['type']) == "image/gif"
|| ($_FILES['file']['type']) == "image/pjpeg"
&& ($_FILES['file']['size']) > 200000) {
$tmp_name=$_FILES['file']['tmp_name'];
// i also tried addslasheds
$image = mysql_real_escape_string(file_get_contents($_FILES['file']['tmp_name']));
if ($_FILES['file']['error'] > 0) {
echo "return code : " . $_FILES['FILES']['error'];
}else{
if (file_exists($_FILES['file']['name'])) {
echo "your file is already exists!";
}else{
Query("INSERT INTO image(image) VALUES ('".$tmp_name."')");
echo "FILES has been stored";
}
}
}
}else{
echo "invalid file";
}?>
and my code to show the image is:
<?php
require 'lib.php';
$request=Query('SELECT * FROM image');
while ($row = mysql_fetch_array($request)) {
echo $row['image'];
}?>
Inserting the temporary name into your database won't accomplish anything because it is just that, temporary. You need to save the image somewhere on your server using move_uploaded_file() and then save the new permanent name to your database so that you can use it in html image tags later.
$filename = "myimage.jpg";
$path = "/var/www/images/".$filename;
$link = "http://domain.com/images/".$filename;
move_uploaded_file($FILES['file']['tmp_name'], $path);
$image = mysql_real_escape_string($link);
if ($_FILES['file']['error'] > 0) {
echo "return code : " . $_FILES['FILES']['error'];
}else{
Query("INSERT INTO image(image) VALUES ('".$image."')");
echo "FILES has been stored";
}
Then when you retrieve your image:
<?php
require 'lib.php';
$request=Query('SELECT * FROM image');
while ($row = mysql_fetch_array($request)) {
echo '<img src="'.$row['image'].'" />";
}?>

Error in file uploads

I am trying to upload files in dynamically created folder. It is working properly in my localhost but on server it is showing me error.
The Error is:-
Warning: move_uploaded_file() [function.move-uploaded-file]: open_basedir restriction in effect. File(/tmp/php323kcy) is not within the allowed path(s): (/home/) in /home/..../public_html/www..com./.../controller/add-product-process.php on line 83
My Php code is Here
<?php
include 'connection.php';
if(isset($_POST['product_name']) && ($_POST['category'])&& ($_POST['sub-category']) && ($_POST['product_qty']) && ($_POST['price']) && ($_POST['description']) && ($_POST['weight']))
{
$pname = $_POST['product_name'];
$category = $_POST['category'];
$scategory = $_POST['sub-category'];
$qty = $_POST['product_qty'];
$price = $_POST['price'];
$desc = $_POST['description'];
$dp=$_POST['dp'];
$offer= $_POST['offer'];
$size=$_POST['size'];
$weight=$_POST['weight'];
if(isset($_POST['color']))
{
$color=$_POST['color'];
}
else
{
$color = "N/A";
}
$query3 = mysql_query("select category_id from category where category_name='$category'");
$row3 = mysql_fetch_array($query3);
$query4 = mysql_query("select sub_category_id from sub_category where sub_category_name='$scategory'");
$row4 = mysql_fetch_array($query4);
$query1 = mysql_query("select product_id from stock");
while ($row = mysql_fetch_row($query1)) {
$id = $row[0];
}
$str1 = substr($id, 2, 5);
if (($str1 >= 1) && ($str1 < 9)) {
$str1++;
echo $new_id = "RD0000" . $str1;
} else if (($str1 >= 9) && ($str1 < 99)) {
$str1++;
echo $new_id = "RD000" . $str1;
} else if (($str1 >= 99) && ($str1 < 999)) {
$str1++;
echo $new_id = "RD00" . $str1;
} else if (($str1 >= 999) && ($str1 < 9999)) {
$str1++;
echo $new_id = "RD0" . $str1;
} else if (($str1 >= 9999) && ($str1 < 99999)) {
$str1++;
echo $new_id = "RD" . $str1;
} else {
echo 'Error: Contact PSSP.';
}
$dirPath = "../products/$new_id";
$imgpath = "products/$new_id";
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
define ("FILEREPOSITORY","../products/$new_id");
for ($i = 0; $i < sizeof($_FILES['uploadfile']['name']); $i++) {
echo $path=$new_id.$i;
$filename = $dirPath.$path.'.jpeg';
if (is_uploaded_file($_FILES['uploadfile']['tmp_name'][$i]))
{
$filename2 = $imgpath."/".$path.'.jpeg';
$fl[$i]=$filename2;
if ($_FILES['uploadfile']['type'][$i] != "image/jpeg")
{
echo "<p>Must be Image file.</p>";
}
else if(file_exists($filename))
{
echo "already exist";
}
else
{
//$name = $_POST['corname'];
$result = move_uploaded_file($_FILES['uploadfile']['tmp_name'][$i], FILEREPOSITORY."/$path.jpeg");
echo "result is".$result;
if ($result == 1)
{
echo "<p>File successfully uploaded.</p>";
}
else
{
echo "not uploaded";
}
}
}
}
$files=implode(',',$fl);
>
$query2 = mysql_query("insert into stock(product_id,product_name,category,sub_category,quantity,price,dp,offer,description,image,size,weight,color)values('$new_id','$pname','$row3[0]','$row4[0]','$qty','$price','$dp','$offer','$desc','$files','$size','$weight','$color')");
if (!$query2) {
echo mysql_error();
} else {
?>
<script language="javascript" type="text/javascript">
// Print a message
alert('Successfully Added..');
// Redirect to some page of the site.
window.location = '../add-product.php';
</script>
<?php
}
}
else
{
echo "Error in page...";
}
?>
Please aware me about the problem..
Thanks in advance
Your hosting account is configured in such a way that PHP uploads are not functional:
Apache stores temporary files in /tmp.
PHP is not allowed to read files outside /home/ (funnily enough, it's apparently allowed to read files from other users).
The first path is controlled with the upload_tmp_dir directive. The second path is controlled with the open_basedir directive. As far as I know, both of them are global settings you aren't allowed to change.
You need to contact support and ask for help to get this fixed.

Categories