How To Map Folder Path For Writing In Php - Uploading - php

I'm having trouble with uploading an image to my local server. I test it in POSTMAN.
I doubt it is my $path that causes the error.
My upload.php
header('Content-type : bitmap; charset=utf-8');
if(isset($_POST["encoded_string"])){
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
$path = 'C:/Users/Luffy/Documents/XAMPP/htdocs/images/'.$image_name;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if($is_written > 0) {
$connection = mysqli_connect('localhost', 'root', 'password','photos');
$query = "INSERT INTO photos(name,pathFile) values('$image_name','$path');";
$result = mysqli_query($connection, $query) ;
if($result){
echo "success";
}else{
echo "failed";
}
mysqli_close($connection);
}
}
How do I exactly map folders in Xammp? I tried getting $_SERVER['DOCUMENT_ROOT'] but it doesn't working.

Related

PHP file_exists (overwriting file) not working

I followed the answer on the question about uploading images and overwriting the existing file.
The suggested answer is to use the method file_exists(). I used the same method but the image is not overwriting the existing image when I tried to upload a different image but the same filename.
here is my php code:
<?php
$con = mysqli_connect("127.0.0.1","root","","japorms");
$user_id = $_POST["user_id"];
$base_picture = $_POST["base_picture"];
$binary = base64_decode($base_picture);
if (file_exists('user_img/'.$user_id.'.jpg'))
{
unlink('user_img/'.$user_id.'.jpg');
}
$file = fopen('user_img/'.$user_id.'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
$response["success"]=true;
echo json_encode($response);
?>
SOLVED
I rearranged and fixed my code. it's working now. thanks for all your suggestions.
<?php
$con = mysqli_connect("127.0.0.1","root","","japorms");
/*$con = mysqli_connect("mysql.hostinger.ph","u989983246_jap","japorms","u989983246_jap");
*/
$user_id = $_POST["user_id"];
$base_picture = $_POST["base_picture"];
$binary = base64_decode($base_picture);
if (file_exists('user_img/'.$user_id.'.jpg'))
{
unlink('user_img/'.$user_id.'.jpg');
$file = fopen('user_img/'.$user_id.'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
}
else{
$file = fopen('user_img/'.$user_id.'.jpg', 'wb');
fwrite($file, $binary);
fclose($file);
}
$response["success"]=true;
echo json_encode($response);
?>

PHP - Sending sql command as a string thru two php files

EDIT: This is a original code, that is working ok. sorry for formating.
<?php
$target = "images/";
if(!is_dir($target)) mkdir($target); $target = $target . basename( $_FILES['photo']['name']);
$uvod = $_POST['uvod']; $text = $_POST['text']; $nadpis = $_POST['nadpis']; $datum = date("Y-m-d");
if (isset($_POST['zobrazeno'])) {
$zobrazeno = 1; } else {
$zobrazeno = 0; }
$fname=($_FILES['photo']['name']); $funiquename = uniqid() . $fname; $tmpName = $_FILES['photo']['tmp_name']; $fileSize = $_FILES['photo']['size']; $fileType = $_FILES['photo']['type'];
$fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp);
if(!get_magic_quotes_gpc()){ $fname = addslashes($fname);}
require_once 'db_config.php'; $db_server=mysql_connect($db_hostname,$db_username,$db_password);
if(!$db_server) die("Unable to connect to MySQL" .mysql_error());
mysql_select_db($db_database,$db_server) or die("Unable to connect to database" .mysql_error());
$sql = "INSERT INTO `aktuality` (`nadpis`, `uvod`, `text`, `datum`, `zobrazeno`, `obr_nazev`, `obr_pripona`, `obr_velikost`, `obr_data`) VALUES ('$nadpis', '$uvod', '$text', '$datum', '$zobrazeno', '$funiquename','$fileType','$fileSize','$content')";
mysql_query($sql);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
} else {
echo "Sorry, there was a problem uploading your file.";
}
?>
Im a php beginner.
I have a problem with sending sql command as a string thru two php files.
This php file should call function sql_string() in sql.php, but there is nothing happens.
<?php
------some code here-------
include 'sql.php';
mysql_query(sql_string1());
------some code here------
?>
sql.php
<?php
function sql_string1()
{
$sql ="INSERT INTO `aktuality` (`nadpis`, `uvod`, `text`, `datum`, `zobrazeno`, `obr_nazev`, `obr_pripona`, `obr_velikost`, `obr_data`) VALUES ('$nadpis', '$uvod', '$text', '$datum', '$zobrazeno', '$funiquename','$fileType','$fileSize','$content')";
return $sql;
}
?>
Thanks for your help!
Try doing this for the query to work:
<?php
------some code here-------
include 'sql.php';
$sql = sql_string1() ;
mysql_query($sql) or die(mysql_error());
------some code here------
?>
You should also be able to see what the error is if that query failed.

PHP - fopen(): Failed to Open Stream on uploaded file

Im trying to upload a csv file then insert its contents into my database. I can successfully upload the file but I am having an error in my insert query. Here's a part of the code:
//Upload the file
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
$files = pathinfo($file_path,PATHINFO_EXTENSION);
$uploadstatus = 1;
$found = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// check if the file being submitted is a csv file
$file_type=$_FILES['uploaded_file']['type'];
if ($files=="CSV") {
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
$uploadstatus = 1;
echo "<script type='text/javascript'>alert('File upload successful.')</script>";
} else{
echo "<script type='text/javascript'>alert('File upload failed. Please check then re-upload file.')</script>";
}
}
$filename = $_FILES['uploaded_file']['name'];
if (file_exists($file_path.$filename) && $uploadstatus) {
if (!$found) {
include('conn.php');
//get the file
$handle = fopen($filename,"r");
do {
if (isset($data[0])) {
$data0 = mysql_real_escape_string($data[0]); //rcode
$data1 = mysql_real_escape_string($data[1]); //pcode
$data2 = mysql_real_escape_string($data[2]); //mcode
$data3 = mysql_real_escape_string($data[3]); //bcode
$data4 = mysql_real_escape_string($data[4]); //ecode
$data5 = mysql_real_escape_string($data[5]); //filetype
$data6 = mysql_real_escape_string($data[6]); //rec_count
$data7 = mysql_real_escape_string($data[7]); //gs_count
$data8 = mysql_real_escape_string($data[8]); //be_count
$data9 = mysql_real_escape_string($data[9]); //qc_count
$data10 = mysql_real_escape_string($data[10]); //tt_count
$data11 = mysql_real_escape_string($data[11]); //rm_count
$data12 = mysql_real_escape_string($data[12]); //sc_count
$data13 = mysql_real_escape_string($data[13]); //in_count
$data14 = mysql_real_escape_string($data[14]); //en_count
$data15 = mysql_real_escape_string($data[15]); //co_count
$data16 = mysql_real_escape_string($data[16]); //ve_count
$data17 = mysql_real_escape_string($data[17]); //editing
$query = "INSERT INTO tbltest (rcode,pcode,mcode,bcode,ecode,filetype,rec_count,gs_count,be_count,qc_count,tt_count,rm_count,sc_count,in_count,en_count,co_count,ve_count,ed_count)
VALUES ('$data0','$data1','$data2','$data3','$data4','$data5','$data6','$data7','$data8','$data9','$data10','$data11','$data12','$data13','$data14','$data15','$data16','$data17') ON DUPLICATE KEY UPDATE rec_count=values(rec_count),gs_count=values(gs_count),be_count=values(be_count),qc_count=values(qc_count),tt_count=values(tt_count),rm_count=values(rm_count),sc_count=values(sc_count),in_count=values(in_count),en_count=values(en_count),co_count=values(co_count),ve_count=values(ve_count),ed_count=values(ed_count)";
mysql_query ($query,$connect);
}
} while ($data = fgetcsv($handle,1000,"|"));
}
}
}
The result of the echo is the correct file, but I get an error that says fopen(): failed to open stream: No such file or directory and fgetcsv() expects parameter 1 to be resource, boolean given.
You're trying to open a file that doesn't exist.
The function move_uploaded_file does exactly what it says - it moves a file that has been uploaded. Once you've called this function the file no longer exists in the temporary upload area.
Change this bit:
$filename = $_FILES['uploaded_file']['name'];
if (file_exists($file_path.$filename) && $uploadstatus) {
if (!$found) {
include('conn.php');
//get the file
$handle = fopen($filename,"r");
to:
$filename = $file_path;
if (file_exists($filename) && $uploadstatus) {
if (!$found) {
include('conn.php');
//get the file
$handle = fopen($filename,"r");
files are NOT stored under their original name.
This is the actual file:
$_FILES['userfile']['tmp_name']
Read more in the fine manual:
http://be2.php.net/manual/en/features.file-upload.post-method.php

MySQL Download counter for .DEB files on repository

I had a MySQL Download counter previously "working" a few months ago and all of a sudden it has stopped working, It was recording (individual cydia downloads) to the database then posting it to the main webpage with Stats.
I've gone through all the code and files, over and over again. Over 24Hours digging and it has still not been solved. If i link the files or post the text "on Here" Would someone please help me.
CONNECT.php
<?php
$server = "localhost";
$user = "root";
$password = "PASSWORD";
$database = mysql_connect ($server, $user, $password);
mysql_select_db("DATABASE_NAME", $database); `
?>
COUNTER.php
<?php
include("connect.php");
$filename = mysql_real_escape_string($_GET['file']);
$path = $_SERVER['DOCUMENT_ROOT']."/";
$fullPath = $path.$filename;
$filetypes = array("deb", "zip");
if (!in_array(substr($filename, -3), $filetypes)) {
echo "Invalid download type.";
exit;
}
if ($fd = fopen ($fullPath, "r")) {
$result = mysql_query("SELECT COUNT(*) AS countfile FROM download
WHERE filename='" . $filename . "'");
$data = mysql_fetch_array($result);
$q = "";
if ($data['countfile'] > 0) {
$q = "UPDATE download SET dldate = NOW()+INTERVAL +6 HOUR, stats = stats + 1 WHERE
filename = '" . $filename . "'";
} else {
$q = "INSERT INTO download (filename, dldate, stats) VALUES
('" . $filename . "',NOW()+INTERVAL +6 HOUR, 1)"; /* +6 = UK Timezone */
}
$statresult = mysql_query($q);
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
?>
INDEX.html
<div class="downloads">Downloads:
<?PHP
include("connect.php");
$query = "SELECT stats FROM download WHERE filename = 'deb/com.icon.deb'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
echo $row[0];
}
?>
</div>
</div>

Error FileType after inserting a file as Blob - PHPMySQL

I made a simple script to insert files as BLOB (mediumblob) in MySQL Database.
The script works fine, the file is uploaded and saved into the table but when I download the file and I try to open it, it says: "File type HTML document (text/html) is not supported"!
This means there was an error while saving the file's type!
Here is my code, please tell me what can be wrong in it:
upload.php :
if (isset($_POST['upload']))
{
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$p = $cnx->prepare('INSERT INTO commandes (name, size, type, content) VALUES(:name, :size, :type, :content)');
$p->execute(array('name'=>$fileName, 'size'=>$fileSize, 'type'=>$fileType, 'content'=>$content));
echo "<br>File $fileName uploaded<br>";
}
}
Download.php :
$p = $cnx->prepare('SELECT cmd_id, name FROM commandes');
$p->setFetchMode(PDO::FETCH_OBJ);
$p->execute();
if($p->rowCount() == 0)
{
echo "0 Element <br />";
}
else
{
while($data = $p->fetch())
{
?>
<?php echo $data->name;?> <br>
<?php
}
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = $cnx->prepare('SELECT * FROM commandes WHERE cmd_id = :cmd_id');
$q->setFetchMode(PDO::FETCH_OBJ);
$q->execute(array('cmd_id'=>$id));
while($getFile = $q->fetch())
{
header("Content-length: $getFile->size");
header("Content-type: $getFile->type");
header("Content-Disposition: download; filename=$getFile->name");
echo $getFile->pdf;
exit;
}
}
Thank you!
What is the output for the response headers?
Can you ensure that "Content-type" is "Content-Type"
Also, using a debugger to inspect the response is really valuable.
http://fiddler2.com/get-fiddler

Categories