Page 1 of 1
Passing variables to class from url
Posted: Wed Oct 25, 2006 11:43 am
by croosman
Hello,
I am having a problem with a photo upload script that has 2 php files. One is the main upload php page and the other is the class php file. The issue is that I am trying to rename the uploaded photo by including an id number in a string query in the url when sent to upload page.
The problem is that I can send a value into the class fine using $my_upload->test = $test1; ($test1 = 1234;) but when I try to set $test1 to the value in the query string, nothing is sent. $test1 = $_GET['DealerID']; However, I am able to see $test1 on the upload page, so I know that it is an issue passing a query string to the class php, probably for security.
Any ideas on how to set this value from a query string where it can be sent to the class. This is all I need to do to rename the photo to my needs.
Thank you for your help and please let me know if you need any more info from me.
Thank you again,
David D
Posted: Wed Oct 25, 2006 11:45 am
by RobertGonzalez
Post some code. Specifically the part where the var is set to a value and the part, in the class, where the var value is passed.
Posted: Wed Oct 25, 2006 11:46 am
by Cameri
Associative array indices are case sensitive, your url should should look like this:
http://url/path/page.php?DealerID=1
or some other number.
Query strings have nothing to do with class members, as far as I know.
Here is the code
Posted: Wed Oct 25, 2006 11:56 am
by croosman
Everah | Please use Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
The upload php portion.... See below for class portion.
Code: Select all
<?php
include ($_SERVER['DOCUMENT_ROOT']."/classes/upload/upload_class.php"); //classes is the map where the class file is stored (one above the root)
$max_size = 1024*250; // the max. size for uploading
$my_upload = new file_upload;
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
// The three lines below is where I have isolated the issue. DealerID is a string from the URL
$test1 = 1234; // This works fine! It passes the var into the class file. You can see the uploaded file is renamed to 1234.jpg
//$test1 = $_GET['DealerID']; // I am able to pick up and display this var (see bottom echo) but the class file will not return it
$my_upload->test = $test1;
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
$my_upload->upload_dir = $_SERVER['DOCUMENT_ROOT']."/files/new/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".zip", ".pdf", ".jpg"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = true;
// You need to modify the settings below...
include ('../php/prvt/Include.inc');
mysql_connect($DBhost,$DBuser,$DBpass);
@mysql_select_db("$DBName");
// the code to create the test table
mysql_query("
CREATE TABLE IF NOT EXISTS tbl_uploadphotos (
id INT NOT NULL AUTO_INCREMENT,
file_name VARCHAR( 100 ) NOT NULL,
PRIMARY KEY (id))") or die(mysql_error());
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
if ($my_upload->upload()) { // new name is an additional filename information, use this to rename the uploaded file
mysql_query(sprintf("INSERT INTO tbl_uploadphotos SET file_name = '%s'", $my_upload->file_copy));
$result = mysql_query($query);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Upload (database) example</title>
</head>
<body>
<h3>Photo upload script:</h3>
<br>This script is supposed to upload a jpg and rename it to the id number found in the url string.
<p>Manually set: <?php echo $test1; ?></p>
<p>DealerID: <?php echo $DealerID; ?></p>
<p>This example is supposed to upload a file and store the name inside a database<br>
(you need to create a database to use this example). </p>
<p>Max. filesize = <?php echo $max_size; ?> bytes.</p>
<form name="form1" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>">
<?php echo $my_upload->create_file_field("upload", "Select a file...", 25, false); ?>
<input type="submit" name="Submit" value="Submit">
</form>
<br clear="all">
<p><?php echo $my_upload->show_error_string(); ?></p>
</body>
</html>
The class portion is...
Code: Select all
<?php
/*
Easy PHP Upload - version 2.31
A easy to use class for your (multiple) file uploads
Copyright (c) 2004 - 2006, Olaf Lederer
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the finalwebsites.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
______________________________________________________________________
available at http://www.finalwebsites.com/snippets.php
Comments & suggestions: http://www.webdigity.com/index.php/boar ... l,ref.olaf
*/
class file_upload {
var $test; // I declared it here.
var $the_file;
var $the_temp_file;
var $upload_dir;
var $replace;
var $do_filename_check;
var $max_length_filename = 100;
var $extensions;
var $ext_string;
var $language;
var $http_error;
var $rename_file; // if this var is true the file copy get a new name
var $file_copy; // the new name
var $message = array();
var $create_directory = true;
function file_upload() {
$this->language = "en"; // choice of en, nl, es
$this->rename_file = true;
$this->ext_string = "";
}
function show_error_string() {
$msg_string = "";
foreach ($this->message as $value) {
$msg_string .= $value."<br />\n";
}
return $msg_string;
}
function set_file_name($new_name = "") { // this "conversion" is used for unique/new filenames
if ($this->rename_file) {
if ($this->the_file == "") return;
$name = ($new_name == "") ? strtotime("now") : $new_name;
sleep(3);
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$name = $this->test.$this->get_extension($this->the_file); // this is where I am trying to replace the renamed var. This works when using the var that is not the string query.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
} else {
$name = str_replace(" ", "_", $this->the_file); // space will result in problems on linux systems
}
return $name;
}
function upload($to_name = "") {
$new_name = $this->set_file_name($test);
if ($this->check_file_name($new_name)) {
if ($this->validateExtension()) {
if (is_uploaded_file($this->the_temp_file)) {
$this->file_copy = $new_name;
if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
$this->message[] = $this->error_text($this->http_error);
if ($this->rename_file) $this->message[] = $this->error_text(16);
return true;
}
} else {
$this->message[] = $this->error_text($this->http_error);
return false;
}
} else {
$this->show_extensions();
$this->message[] = $this->error_text(11);
return false;
}
} else {
return false;
}
}
function check_file_name($the_name) {
if ($the_name != "") {
if (strlen($the_name) > $this->max_length_filename) {
$this->message[] = $this->error_text(13);
return false;
} else {
if ($this->do_filename_check == "y") {
if (preg_match("/^[a-z0-9_]*\.(.){1,5}$/i", $the_name)) {
return true;
} else {
$this->message[] = $this->error_text(12);
return false;
}
} else {
return true;
}
}
} else {
$this->message[] = $this->error_text(10);
return false;
}
}
function get_extension($from_file) {
$ext = strtolower(strrchr($from_file,"."));
return $ext;
}
function validateExtension() {
$extension = $this->get_extension($this->the_file);
$ext_array = $this->extensions;
if (in_array($extension, $ext_array)) {
// check mime type hier too against allowed/restricted mime types (boolean check mimetype)
return true;
} else {
return false;
}
}
// this method is only used for detailed error reporting
function show_extensions() {
$this->ext_string = implode(" ", $this->extensions);
}
function move_upload($tmp_file, $new_file) {
if ($this->existing_file($new_file)) {
$newfile = $this->upload_dir.$new_file;
if ($this->check_dir($this->upload_dir)) {
if (move_uploaded_file($tmp_file, $newfile)) {
umask(0);
chmod($newfile , 0644);
return true;
} else {
return false;
}
} else {
$this->message[] = $this->error_text(14);
return false;
}
} else {
$this->message[] = $this->error_text(15);
return false;
}
}
function check_dir($directory) {
if (!is_dir($directory)) {
if ($this->create_directory) {
umask(0);
mkdir($directory, 0777);
return true;
} else {
return false;
}
} else {
return true;
}
}
function existing_file($file_name) {
if ($this->replace == "y") {
return true;
} else {
if (file_exists($this->upload_dir.$file_name)) {
return false;
} else {
return true;
}
}
}
function get_uploaded_file_info($name) {
$str = "File name: ".basename($name)."\n";
$str .= "File size: ".filesize($name)." bytes\n";
if (function_exists("mime_content_type")) {
$str .= "Mime type: ".mime_content_type($name)."\n";
}
if ($img_dim = getimagesize($name)) {
$str .= "Image dimensions: x = ".$img_dim[0]."px, y = ".$img_dim[1]."px\n";
}
return $str;
}
// this method was first located inside the foto_upload extension
function del_temp_file($file) {
$delete = @unlink($file);
clearstatcache();
if (@file_exists($file)) {
$filesys = eregi_replace("/","\\",$file);
$delete = @system("del $filesys");
clearstatcache();
if (@file_exists($file)) {
$delete = @chmod ($file, 0644);
$delete = @unlink($file);
$delete = @system("del $filesys");
}
}
}
// this function creates a file field and if $show_alternate is true it will show a text field if the given file already exists
// there is also a submit button to remove the text field value
function create_file_field($element, $label = "", $length = 25, $show_replace = true, $replace_label = "Replace old file?", $file_path = "", $file_name = "", $show_alternate = false, $alt_length = 30, $alt_btn_label = "Delete image") {
$field = ($label != "") ? "<label>".$label."</label>\n" : "";
$file_field = "<input type=\"file\" name=\"".$element."\" size=\"".$length."\" />\n";
$file_field .= ($show_replace) ? "<span>".$replace_label."</span><input type=\"checkbox\" name=\"replace\" value=\"y\" />" : "";
if ($file_name != "" && $show_alternate) {
$field .= "<input type=\"text\" name=\"".$element."\" size=\"".$alt_length."\" value=\"".$file_name."\" readonly=\"readonly\"";
$field .= (!@file_exists($file_path.$file_name)) ? " title=\"".sprintf($this->error_text(17), $file_name)."\" />\n" : " />\n";
$field .= "<input type=\"checkbox\" name=\"del_img\" value=\"y\" /><span>".$alt_btn_label."</span>\n";
} else {
$field .= $file_field;
}
return $field;
}
// some error (HTTP)reporting, change the messages or remove options if you like.
function error_text($err_num) {
switch ($this->language) {
case "nl":
$error[0] = "Foto succesvol kopieert.";
$error[1] = "Het bestand is te groot, controlleer de max. toegelaten bestandsgrootte.";
$error[2] = "Het bestand is te groot, controlleer de max. toegelaten bestandsgrootte.";
$error[3] = "Fout bij het uploaden, probeer het nog een keer.";
$error[4] = "Fout bij het uploaden, probeer het nog een keer.";
$error[10] = "Selecteer een bestand.";
$error[11] = "Het zijn alleen bestanden van dit type toegestaan: <b>".$this->ext_string."</b>";
$error[12] = "Sorry, de bestandsnaam bevat tekens die niet zijn toegestaan. Gebruik alleen nummer, letters en het underscore teken. <br>Een geldige naam eindigt met een punt en de extensie.";
$error[13] = "De bestandsnaam is te lang, het maximum is: ".$this->max_length_filename." teken.";
$error[14] = "Sorry, het opgegeven directory bestaat niet!";
$error[15] = "Uploading <b>".$this->the_file."...Fout!</b> Sorry, er is al een bestand met deze naam aanwezig.";
$error[16] = "Het gekopieerde bestand is hernoemd naar <b>".$this->file_copy."</b>.";
$error[17] = "Het bestand %s bestaat niet.";
break;
case "de":
$error[0] = "Die Datei: <b>".$this->the_file."</b> wurde hochgeladen!";
$error[1] = "Die hochzuladende Datei ist größer als der Wert in der Server-Konfiguration!";
$error[2] = "Die hochzuladende Datei ist größer als der Wert in der Klassen-Konfiguration!";
$error[3] = "Die hochzuladende Datei wurde nur teilweise übertragen";
$error[4] = "Es wurde keine Datei hochgeladen";
$error[10] = "Wählen Sie eine Datei aus!.";
$error[11] = "Es sind nur Dateien mit folgenden Endungen erlaubt: <b>".$this->ext_string."</b>";
$error[12] = "Der Dateiname enthält ungültige Zeichen. Benutzen Sie nur alphanumerische Zeichen für den Dateinamen mit Unterstrich. <br>Ein gültiger Dateiname endet mit einem Punkt, gefolgt von der Endung.";
$error[13] = "Der Dateiname überschreitet die maximale Anzahl von ".$this->max_length_filename." Zeichen.";
$error[14] = "Das Upload-Verzeichnis existiert nicht!";
$error[15] = "Upload <b>".$this->the_file."...Fehler!</b> Eine Datei mit gleichem Dateinamen existiert bereits.";
$error[16] = "Die hochgeladene Datei ist umbenannt in <b>".$this->file_copy."</b>.";
$error[17] = "Die Datei %s existiert nicht.";
break;
//
// place here the translations (if you need) from the directory "add_translations"
//
default:
// start http errors
$error[0] = "File: <b>".$this->the_file."</b> successfully uploaded!";
$error[1] = "The uploaded file exceeds the max. upload filesize directive in the server configuration.";
$error[2] = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form.";
$error[3] = "The uploaded file was only partially uploaded";
$error[4] = "No file was uploaded";
// end http errors
$error[10] = "Please select a file for upload.";
$error[11] = "Only files with the following extensions are allowed: <b>".$this->ext_string."</b>";
$error[12] = "Sorry, the filename contains invalid characters. Use only alphanumerical chars and separate parts of the name (if needed) with an underscore. <br>A valid filename ends with one dot followed by the extension.";
$error[13] = "The filename exceeds the maximum length of ".$this->max_length_filename." characters.";
$error[14] = "Sorry, the upload directory doesn't exist!";
$error[15] = "Uploading <b>".$this->the_file."...Error!</b> Sorry, a file with this name already exitst.";
$error[16] = "The uploaded file is renamed to <b>".$this->file_copy."</b>.";
$error[17] = "The file %s does not exist.";
}
return $error[$err_num];
}
}
?>
Everah | Please use Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Posted: Wed Oct 25, 2006 12:08 pm
by croosman
Cameri wrote:Associative array indices are case sensitive, your url should should look like this:
http://url/path/page.php?DealerID=1
or some other number.
Query strings have nothing to do with class members, as far as I know.
Yes, that is what my url looks like, I am able to see this value by echo on the main upload page.
I should be able to set the $test value to equal the value set in the url. This should then send that value to the class where the file is renamed.
Posted: Wed Oct 25, 2006 12:27 pm
by RobertGonzalez
Your going to have problems if you don't check if the Query String var is set. So if someone loads the page freshly, without a query string, nothing is going to happen except errors will be generated in regards to 'undefined index'.
What I would do is only process the script if the DealerID var is set to an acceptable value. If it is not, then skip the process.
Code: Select all
<?php
if (isset($_GET['DealerID']))
{
// The var is set, so lets process
// enter your code here
$my_upload->test = $_GET['DealerID'];
// etc, etc
}
else
{
echo 'You didn\'t pass anything through the URL parameter';
}
?>
Remember also that you call this by querystring, meaning that you invoke this by going to the page
http://www.yourdomain.com/yourpage.php? ... =somevalue ...
Re: Here is the code
Posted: Wed Oct 25, 2006 2:05 pm
by RobertGonzalez
There are a couple of things that I can think of that might be causing you issues. First...
Code: Select all
<?php
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
// The three lines below is where I have isolated the issue. DealerID is a string from the URL
$test1 = 1234; // This works fine! It passes the var into the class file. You can see the uploaded file is renamed to 1234.jpg
//$test1 = $_GET['DealerID']; // I am able to pick up and display this var (see bottom echo) but the class file will not return it
$my_upload->test = $test1;
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
// ...
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->replace = "y";
$my_upload->do_filename_check = "n"; // use this boolean to check for a valid filename
if ($my_upload->upload()) { // new name is an additional filename information, use this to rename the uploaded file
mysql_query(sprintf("INSERT INTO tbl_uploadphotos SET file_name = '%s'", $my_upload->file_copy));
$result = mysql_query($query);
}
}
?>
This process is involving two separate super globals. The use of $_GET because DealerID is passed by the query string, and the use of $_POST because the file is being posted by a form. Which leads me to the question, are you posting the form to a page like
page.php?DealerID=somevalue?
Secondly, in the class, the method
set_file_name takes a new name value as a parameter and, as long as the object property
rename_file is true AND the object property
the_file is not empty, it attempts to make a new name by using either the passed parameter, or if it is empty, the unixtimestamp. Unfortunately, when this is passed to the object method
upload, the method does something wierd... $new_name = $this->set_file_name($test); ... which will always set the $new_name to the timestamp since there is no value for the function-scope specific variable
$test.
Code: Select all
<?php
function set_file_name($new_name = "") { // this "conversion" is used for unique/new filenames
if ($this->rename_file) {
if ($this->the_file == "") return;
$name = ($new_name == "") ? strtotime("now") : $new_name;
sleep(3);
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
$name = $this->test.$this->get_extension($this->the_file); // this is where I am trying to replace the renamed var. This works when using the var that is not the string query.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
} else {
$name = str_replace(" ", "_", $this->the_file); // space will result in problems on linux systems
}
return $name;
}
function upload($to_name = "") {
$new_name = $this->set_file_name($test);
if ($this->check_file_name($new_name)) {
if ($this->validateExtension()) {
if (is_uploaded_file($this->the_temp_file)) {
$this->file_copy = $new_name;
if ($this->move_upload($this->the_temp_file, $this->file_copy)) {
$this->message[] = $this->error_text($this->http_error);
if ($this->rename_file) $this->message[] = $this->error_text(16);
return true;
}
} else {
$this->message[] = $this->error_text($this->http_error);
return false;
}
} else {
$this->show_extensions();
$this->message[] = $this->error_text(11);
return false;
}
} else {
return false;
}
}
?>
I noticed the header of the file mentioned a developers name/website. Have you asked anyone on the side of the developer of the app if there might be updates to it?
Posted: Wed Oct 25, 2006 2:24 pm
by croosman
(are you posting the form to a page like page.php?DealerID=somevalue?)
Yes, that is why I can echo the DealerID at the bottom of page.
I have not checked for updates.
So is there no way to pass from one global to the other?
Posted: Wed Oct 25, 2006 3:02 pm
by RobertGonzalez
You can pass it, it is just a matter of how. Typically you grab a var and send it to a function/method as a parameter. That is not the case in your code. You can set a property of the class to a var, which can then be used by methods within the class, but I am not seeing where that is done.
Posted: Wed Oct 25, 2006 4:07 pm
by RobertGonzalez
Change this:
To this:
Code: Select all
$test1 = (isset($_GET['DealerID'])) ? $_GET['DealerID'] : 987654;
Run the page and see what the results are.