PHP multi file upload script not working correctly - php

I found a multi file upload script here.
When I try to upload the files i get an error message:
Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/usr/local/apache/htdocs/register/uploaded_files/1321720804-bg.png) is not within the allowed path(s): (/home/:/usr/lib/php:/tmp) in /home/a2767984/public_html/register/multiple.upload.processor.php on line 80
The file permissions for the upload folder which is 'uploaded_files' is set to 777 and is located in the same folder as the script.(public_html/register/)
I really don't understand why this is not working. Spent two days scratching my head. Any ideas??
Here is the processing script:
<?php
// filename: upload.processor.php
// first let's set some variables
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded files
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.form.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'multiple.upload.success.php';
// name of the fieldname used for the file in the HTML form
$fieldname = 'file';
//echo'<pre>';print_r($_FILES);exit;
// Now let's deal with the uploaded files
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check if any files were uploaded and if
// so store the active $_FILES array keys
$active_keys = array();
foreach($_FILES[$fieldname]['name'] as $key => $filename)
{
if(!empty($filename))
{
$active_keys[] = $key;
}
}
// check at least one file was uploaded
count($active_keys)
or error('No files were uploaded', $uploadForm);
// check for standard uploading errors
foreach($active_keys as $key)
{
($_FILES[$fieldname]['error'][$key] == 0)
or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
}
// check that the file we are working on really was an HTTP upload
foreach($active_keys as $key)
{
#is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
}
// validation... since this is an image upload script we
// should run a check to make sure the upload is an image
foreach($active_keys as $key)
{
#getimagesize($_FILES[$fieldname]['tmp_name'][$key])
or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
}
// make a unique filename for the uploaded file and check it is
// not taken... if it is keep trying until we find a vacant one
foreach($active_keys as $key)
{
$now = time();
while(file_exists($uploadFilename[$key] = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'][$key]))
{
$now++;
}
}
// now let's move the file to its final and allocate it with the new filename
foreach($active_keys as $key)
{
#move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
or error('receiving directory insuffiecient permission', $uploadForm);
}
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to the success page.
header('Location: ' . $uploadSuccess);
// make an error handler which will be used if the upload fails
function error($error, $location, $seconds = 5)
{
header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
' <head>'."\n".
' <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
' <title>Upload error</title>'."\n\n".
' </head>'."\n\n".
' <body>'."\n\n".
' <div id="Upload">'."\n\n".
' <h1>Upload failure</h1>'."\n\n".
' <p>An error has occured: '."\n\n".
' <span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler
?>

Your problem is, that $_SERVER['DOCUMENT_ROOT'] seems to return the wrong value, so your $uploadsDirectory is not within in the allowed path (see line 11 of your script).
Try replacing
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
with
$uploadsDirectory = __DIR__.'/uploaded_files/';
If that doesn't work either, I would go the easy way and hardcode the path:
$uploadsDirectory = '/home/a2767984/public_html/register/uploaded_files/';

Related

Download low resolution image instead of high resolution in php

I develop a social android app that users upload high quality image to my server and then download them to show in list view in app feed.
Uploaded image save in ./uploads/ directory in my server. I use the below code in PHP to save image in server:
<?php
// Path to move uploaded files
error_reporting(E_ALL ^ E_DEPRECATED);
include 'conf.php';
$target_path = "uploads/";
// array for final json respone
$response = array();
// getting server ip address
$server_ip = gethostbyname(gethostname());
// final file url that is being uploaded
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path;
if (isset($_FILES['image']['name'])) {
$target_path = $target_path . basename($_FILES['image']['name']);
try {
// Throws exception incase file is not being moved
if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
// make error flag true
print "error1";
}
print basename($_FILES['image']['name']);
} catch (Exception $e) {
// Exception occurred. Make error flag true
print "error2";
}
} else {
// File parameter is missing
print "error3";
}
?>
Now I want to save low resolution of every image in different directory(or in real time get low resolution ) and get url of it and using php send to android app and users in my app can see a thumbnail or low resolution of image before download whole image.
How I should do it?
Easy. You can use the code below to do this :
<?php
$org_info = getimagesize("source image");
echo $org_info[3] . '<br><br>';
$rsr_org = imagecreatefromjpeg("source image");
$rsr_scl = imagescale($rsr_org, new_width, new_height, IMG_BICUBIC_FIXED);
imagejpeg($rsr_scl, "destination image");
imagedestroy($rsr_org);
imagedestroy($rsr_scl);
?>

Internal Server Error with SQL Code

I am trying to insert values into a mysql database and I am getting an "Internal Server Error" and do not know why. I am using an upload form to get user data and then using an upload processor file to write the data to the server. The form is based off of a working tutorial online so everything works, but whenever I added the SQL code, it stopped working. My code is below, and I appreciate your time looking at it.
<?php
// Upload form based off of http://www.htmlgoodies.com/beyond/php/article.php/3877766
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded file
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.form.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';
// fieldname used within the file <input> of the HTML form
$fieldname = 'file';
$promoName = 'sale_name';
$expirDate = 'sale_expir';
// Now let's deal with the upload
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print the form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check for PHP's built-in uploading errors
($_FILES[$fieldname]['error'] == 0)
or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
// check that the file we are working on really was the subject of an HTTP upload
#is_uploaded_file($_FILES[$fieldname]['tmp_name'])
or error('not an HTTP upload', $uploadForm);
// validation... since this is an image upload script we should run a check
// to make sure the uploaded file is in fact an image. Here is a simple check:
// getimagesize() returns false if the file tested is not an image.
#getimagesize($_FILES[$fieldname]['tmp_name'])
or error('only image uploads are allowed', $uploadForm);
// make a unique filename for the uploaded file and check it is not already
// taken... if it is already taken keep trying until we find a vacant one
// sample filename: 1140732936-filename.jpg
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
// now let's move the file to its final location and allocate the new filename to it
#move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
or error('receiving directory insuffiecient permission', $uploadForm);
// these commands move the information onto the database
$imageURL = $uploadsDirectory.$uploadFilename;
$host = '***removed***';
$dbName = '***removed***';
$dbUser = '***removed***';
$dbPass = '***removed***';
$conn = mysql_connect($host, $dbUser, $dbPass);
if (!$conn){
die('Could not connect: '.mysql_error());
} else {
echo 'Connected successfully!';
}
$sql = "INSERT INTO '$dbName'.sales (name, date, saleImage) VALUES ('$promoName', '$expirDate', '$imageURL');";
mysql_select_db($dbName, $conn);
mysql_query($sql, $conn);
mysql_close($conn);
// database work is done
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to a success page.
header('Location: ' . $uploadSuccess);
// The following function is an error handler which is used
// to output an HTML error page if the file upload fails
function error($error, $location, $seconds = 5)
{
header("Refresh: $seconds; URL="$location"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."n".
'"http://www.w3.org/TR/html4/strict.dtd">'."nn".
'<html lang="en">'."n".
' <head>'."n".
' <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."nn".
' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."nn".
' <title>Upload error</title>'."nn".
' </head>'."nn".
' <body>'."nn".
' <div id="Upload">'."nn".
' <h1>Upload failure</h1>'."nn".
' <p>An error has occurred: '."nn".
' <span class="red">' . $error . '...</span>'."nn".
' The upload form is reloading</p>'."nn".
' </div>'."nn".
'</html>';
exit;
} // end error handler
?>
You have this code in your 95th line:
header("Refresh: $seconds; URL="$location"");
Which should be
header("Refresh: $seconds; URL=\"$location\"");

File upload using cakephp

I just want to upload a single pdf file using cakephp,
here is my view called pdfadd.ctp:
<?php echo $this->Form->create('pdfadd1', array('enctype' => 'multipart/form-data'));?>
<fieldset>
<?php
echo $this->Form->file('Document.submittedfile');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
Here is my conroller:
public function pdfadd(){
if ($this->request->is('post') || $this->request->is('put')) {
//die();
$file = $this->request->data['Document']['submittedfile'];
//$this->pdfadd1->save($this->request->data);
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
}
It gives me this error:
Warning (2): move_uploaded_file(D:/Program Files D/xampp/htdocs/app/webroot/files/Functions Package for email (1).pdf): failed to open stream: No such file or directory [APP\Controller\PagesController.php, line 29]
Warning (2): move_uploaded_file() [function.move-uploaded-file]: Unable to move 'D:\Program Files D\xampp\tmp\php862.tmp' to 'D:/Program Files D/xampp/htdocs/app/webroot/files/Functions Package for email (1).pdf' [APP\Controller\PagesController.php, line 29]
And also I want to rename the file to 1.pdf. The file should save in webroot/files.
Replace this:
$_SERVER['DOCUMENT_ROOT'] . '/app/webroot/files/' . $this->data['Document']['submittedfile']['name']
with this:
WWW_ROOT . 'files' . DS . '1.pdf'
However, you really should do more validation, like using PHP's is_uploaded_file function, making sure the file really is a PDF, etc.
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
1.Change this code according to directory
2.c:xampp/htdocs(its a default location for uploading in cakephp ),then put your upload file location
move_uploaded_file($this->data['Document']['submittedfile']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . 'cakephp/app/webroot/files/' . $this->data['Document']['submittedfile']['name']);
3.You can rename it before uploading
This line get only file name, not file.
$file = $this->request->data['Document']['submittedfile'];
You could use this.
$file = $_FILES ['Document'] ['submittedfile'];

Saving the name of the uploaded file into this table on my SQL database

This is what I am trying to accomplish.
I need the users to be able to load a picture and show it on their profile page. There is one table on my sql database named "members" with fields as follow, username, password, firstname, lastname, photo.
All fields except photo are completed on the registration form. Once users go to their profile page they will find a form to upload a picture to their profile.
I got this code for the upload_form.php.. (code listed bellow) and another file upload_processor.php (code listed after)
This code successfully load the file into my folder uploaded_files and it renames the file to something like this... 1140732936-filename.jpg to ensure the file is unique.
How can I get the name of 1140732936-filename.jpg saved into my "photo" field on my sql table? Is there any way? Help please....
Code for the upload_form
<?php
// filename: upload.form.php
// first let's set some variables
// make a note of the current working directory relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the location of the upload handler script
$uploadHandler = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.processor.php';
// set a max file size for the html upload form
$max_file_size = 3000000; // size in bytes
// now echo the html page
?>
Here is the html form on the same file
<form id="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post">
<h1>
Upload form
</h1>
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
</p>
<p>
<label for="file">File to upload:</label>
<input id="file" type="file" name="file">
</p>
<p>
<label for="submit">Press to...</label>
<input id="submit" type="submit" name="submit" value="Upload me!">
</p>
</form>
</body>
Here is the code for the file that process the form.
<?php
// filename: upload.processor.php
// first let's set some variables
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded file
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'updateprofile.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';
// fieldname used within the file <input> of the HTML form
$fieldname = 'file';
// Now let's deal with the upload
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print the form
isset($_POST['submit'])
or error('the upload form is neaded', $uploadForm);
// check for PHP's built-in uploading errors
($_FILES[$fieldname]['error'] == 0)
or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
// check that the file we are working on really was the subject of an HTTP upload
#is_uploaded_file($_FILES[$fieldname]['tmp_name'])
or error('not an HTTP upload', $uploadForm);
// validation... since this is an image upload script we should run a check
// to make sure the uploaded file is in fact an image. Here is a simple check:
// getimagesize() returns false if the file tested is not an image.
#getimagesize($_FILES[$fieldname]['tmp_name'])
or error('only image uploads are allowed', $uploadForm);
// make a unique filename for the uploaded file and check it is not already
// taken... if it is already taken keep trying until we find a vacant one
// sample filename: 1140732936-filename.jpg
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
// now let's move the file to its final location and allocate the new filename to it
#move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
or error('receiving directory insuffiecient permission', $uploadForm);
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to a success page.
header('Location: ' . $uploadSuccess);
// The following function is an error handler which is used
// to output an HTML error page if the file upload fails
function error($error, $location, $seconds = 5)
{
header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
' <head>'."\n".
' <meta http-equiv="content-type" content="text/html; charset=iso- 8859-1">'."\n\n".
' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
' <title>Upload error</title>'."\n\n".
' </head>'."\n\n".
' <body>'."\n\n".
' <div id="Upload">'."\n\n".
' <h1>Upload failure</h1>'."\n\n".
' <p>An error has occured: '."\n\n".
' <span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler
?>
In the page upload_processor.php
Add some SQL just after the image is copied to server.
I have no code therfore iam supposing you have generating image name with microtime().
Save generated image name in a variable called $variable .Then rename the image with that variable and
<?php
// filename: upload.processor.php
// first let's set some variables
// make a note of the current working directory, relative to root.
$directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
// make a note of the directory that will recieve the uploaded file
$uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
// make a note of the location of the upload form in case we need it
$uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'updateprofile.php';
// make a note of the location of the success page
$uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';
// fieldname used within the file <input> of the HTML form
$fieldname = 'file';
// Now let's deal with the upload
// possible PHP upload errors
$errors = array(1 => 'php.ini max file size exceeded',
2 => 'html form max file size exceeded',
3 => 'file upload was only partial',
4 => 'no file was attached');
// check the upload form was actually submitted else print the form
isset($_POST['submit'])
or error('the upload form is needed', $uploadForm);
// check for PHP's built-in uploading errors
($_FILES[$fieldname]['error'] == 0)
or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
// check that the file we are working on really was the subject of an HTTP upload
#is_uploaded_file($_FILES[$fieldname]['tmp_name'])
or error('not an HTTP upload', $uploadForm);
// validation... since this is an image upload script we should run a check
// to make sure the uploaded file is in fact an image. Here is a simple check:
// getimagesize() returns false if the file tested is not an image.
#getimagesize($_FILES[$fieldname]['tmp_name'])
or error('only image uploads are allowed', $uploadForm);
// make a unique filename for the uploaded file and check it is not already
// taken... if it is already taken keep trying until we find a vacant one
// sample filename: 1140732936-filename.jpg
$now = time();
while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
{
$now++;
}
// now let's move the file to its final location and allocate the new filename to it
#move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
or error('receiving directory insuffiecient permission', $uploadForm);
// If you got this far, everything has worked and the file has been successfully saved.
// We are now going to redirect the client to a success page.
//connect database
mysql_query("update members set photo='".$uploadFilename."' where member_id='".$_SESSION['id']."'");
header('Location: ' . $uploadSuccess);
// The following function is an error handler which is used
// to output an HTML error page if the file upload fails
function error($error, $location, $seconds = 5)
{
header("Refresh: $seconds; URL=\"$location\"");
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
'<html lang="en">'."\n".
' <head>'."\n".
' <meta http-equiv="content-type" content="text/html; charset=iso- 8859-1">'."\n\n".
' <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
' <title>Upload error</title>'."\n\n".
' </head>'."\n\n".
' <body>'."\n\n".
' <div id="Upload">'."\n\n".
' <h1>Upload failure</h1>'."\n\n".
' <p>An error has occured: '."\n\n".
' <span class="red">' . $error . '...</span>'."\n\n".
' The upload form is reloading</p>'."\n\n".
' </div>'."\n\n".
'</html>';
exit;
} // end error handler
?>
This is the code I have at the top of the page
<?php require_once('Connections/trusted.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}
$MM_restrictGoTo = "updateprofile.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
$colname_rsuserdets = "-1";
if (isset($_SESSION['MM_Username'])) {
$colname_rsuserdets = $_SESSION['MM_Username'];
}
mysql_select_db($database_trusted, $trusted);
$query_rsuserdets = sprintf("SELECT * FROM members WHERE username = %s", GetSQLValueString($colname_rsuserdets, "text"));
$rsuserdets = mysql_query($query_rsuserdets, $trusted) or die(mysql_error());
$row_rsuserdets = mysql_fetch_assoc($rsuserdets);
$totalRows_rsuserdets = mysql_num_rows($rsuserdets);
?>

How do I set relative paths in PHP?

I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>

Categories