PHP - Paths When Rewriting Urls
I would like to better understand relative and absolute paths when rewriting URLs. My virtual host configuration is shown below.
I wish the server to see something like: https://example.com?page=page1&controller=controller1&data1=123&data2=321Given the rewrites as shown in my virtual host, what would be the proper URL in the browser? One of these (note the ? and &), or something different? https://example.com/page1/controller1?data1=123&data2=321 https://example.com/page1/controller1&data1=123&data2=321Next, if I enter one of the URLs, how do relative paths to images, etc work? Would the browser think it is in the root directory, or in /page1/controller1? I had problems with relative paths, and changed to absolute paths, and it fixed the problem, but I wish to better understand what is happening. On a side note, I would appreciate any critique of my virtual host configuration. My goal is for all requests to example.com to redirect to https://example.com, for only https://example.com (no subdomain) to redirect to https://www.example.com, and do the rewriting of page and controller. Thank you # Note that if a virtual ServerName is not found (i.e. IP 192.168.1.200), Apache defaults to first virtual host. # Note that if ServerName is set to one of the virtual host ServerName's in the Second Section, it doesn't work (why?) # Handle just example.com to http <VirtualHost *:80> ServerName example.com ServerAlias *.example.com Redirect / https://www.example.com/ </VirtualHost> # Handle just example.com without subdomains <VirtualHost *:443> ServerName example.com # ServerAlias example.com SSLEngine on SSLCipherSuite SSLv3:TLSv1:+HIGH:!SSLv2:!MD5:!MEDIUM:!LOW:!EXP:!ADH:!eNULL:!aNULL SSLCertificateKeyFile /etc/pki/tls/private/example_key.pem SSLCertificateFile /etc/pki/tls/certs/example_startssl.crt SSLCertificateChainFile /etc/pki/tls/certs/sub.class1.server.ca.pem Redirect / https://www.example.com/ </VirtualHost> <VirtualHost *:443> ServerName example.com ServerAlias *.example.com DocumentRoot /var/www/example/html SSLEngine on SSLCipherSuite SSLv3:TLSv1:+HIGH:!SSLv2:!MD5:!MEDIUM:!LOW:!EXP:!ADH:!eNULL:!aNULL SSLCertificateKeyFile /etc/pki/tls/private/example_key.pem SSLCertificateFile /etc/pki/tls/certs/example_startssl.crt SSLCertificateChainFile /etc/pki/tls/certs/sub.class1.server.ca.pem <Directory "/var/www/example/html"> allow from all Options +Indexes <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # Are these lines necessary, or should I create a virtual host for http on port 80 instead? RewriteCond %{HTTPS} !=on RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [NE,R,L] ## If the request is for a valid directory, file, or link, don't do anything RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -l RewriteRule ^ - [L] #remove the trailing slash RewriteRule (.+)/$ $1 # If you add this first rule to support views, be sure to remove the QSA flag from the second rule (maybe not required since the first rule has the L flag) #replace mypage/mycontroller with index.php?page=mypage&controller=mycontroller RewriteRule ^([^/]+)/([^/]+)/?$ index.php?page=$1&controller=$2 [L,QSA] #replace mypage with index.php?page=mypage RewriteRule ^([^/]+)/?$ index.php?page=$1 [L,QSA] </IfModule> </Directory> </VirtualHost> Similar TutorialsThis topic has been moved to mod_rewrite. http://www.phpfreaks.com/forums/index.php?topic=359560.0 Hi all, I am looking a developing a script that instead of using something like mysite.com/showproduct.php?id=1 I would like it to appear as mysite.com/php-editor Is their a simple way of doing this? I would still need to pull info from a database so the page would still need to be dynamic, I just want it to appear static! I am used to using the get id function of php, what would the workaround be? would the id be hidden from the url but still usable in a query? I have had a look at the apache mod_rewrite, but quite frankly, I dont understand it! Cheers Hi all, I have a security problem with my website who is a social network (like facebook). Let's me Explain : You can execute this page on my website. www.SocialNetWork.com/ChangeStatus.php?param=Hello So your status become "Hello". On your profile, you can create a link to a picture on the web, for example : <img src='http://www.hacking.com/pic.jpg'> The problem is that a "hacker" create several russian girl profile and made links to pic.jpg on his server, and this .jpg file rewrite URL to : www.SocialNetWork.com/ChangeStatus.php?param=Suck. So when you visite his profil, the php code is launched, and the status OF THE VISITOR is changed ! I have no idea of how to stop this ? If i check the variable : $_SERVER['HTTP_REFERER'] The value is empty or www.SocialNetWork.com, but never www.hacking.com ... How can i stop the fact that a foreign picture could launch a php page on my website ? thanks for help ! ps: sorry for my english It has been brought to my attention that $_SERVER['PHP_SELF']; can be easily hacked. In this code... Code: [Select] <form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Do I even need anything in the Action attribute if I am redirecting the form to itself?! Please advise... Debbie This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=348545.0 Hey everyone, Im writing some code that has to work out a route based on linking airports and output all the flights it takes to get there, tried searching just dont really know what to search for The data table looks like this ID, Origin, Destination, DatetimeDeparting, DatetimeArriving, Price 1, BKK, CNX, 2010-10-14 12:00:00, 2010-10-14 14:00:00, 125 2, STN, BKK, 2010-10-13 18:00:00, 2010-10-13 22:00:00, 300 etc. What is the easiest way of working out the path from STN to CNX via BKK? UPDATE: Just to make it more interesting there will be instances where there is more than 1 path eg. STN -> KUL -> BKK -> CNX hello, i cant see why my navigation file path is not working im working on my localhost: http://localhost:8888/djsonrotation my initialize file is located at http://localhost:8888/djsonrotation/includes/initialize.php my navigation code is located at http://localhost:8888/djsonrotation/pages/pageContent/navigation/ddAccordion.php my js is located at http://localhost:8888/djsonrotation/js/ddaccordion.js if i put these on my ddAccordion.php it works Code: [Select] to find my initialize file <?PHP require_once("../../../includes/initialize.php"); ?> to find my js file <script type="text/javascript" src="../../../js/ddaccordion.js"> this is how my initialize file looks Code: [Select] <?PHP defined('DS') ? null : define('DS', DIRECTORY_SEPARATOR); defined('SITE_DOMAIN') ? null : define('SITE_DOMAIN', 'http://localhost/djsonrotation'); defined('SITE_ROOT') ? null : define('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'].DS.'djsonrotation'); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes'); defined('ELEMENTS') ? null : define('ELEMENTS', $_SERVER['DOCUMENT_ROOT'].DS.'djsonrotation'.DS.'pages'.DS.'contElements'); the problem is i can't seem to change ../../../ in to a file path like this does not work Code: [Select] <?PHP require_once(include(LIB_PATH.DS."initialize.php")); ?> i tried a couple of different file paths for my js file but they dont work either Code: [Select] <script type="text/javascript" src="<?php include(SITE_DOMAIN.DS."js".DS."ddaccordion.js"); ?>"> or Code: [Select] <script type="text/javascript" src="<?php include(SITE_ROOT.DS."js".DS."ddaccordion.js"); ?>"> i guess i could just use ../../../ but why are the include paths not working ???? thanks Any help is much appreciated in advance... I have a master file located along the root path that needs to be included in subdomains. Inside the master file are includes like Code: [Select] <?php include("../bodyCopy/anyfile.php"); ?> that need to reference the /bodyCopy directory IN THE SUBDOMAIN and NOT along the root. The problem that I'm having is that the master file resides OUTSIDE of the subdomain on the root (in a '/bodyCopy' directory. How do I write the PHP include so that files included in a subdomain from outside of the subdomain (on root) search directories INSIDE the subdomain and NOT relative to the root path? Here's what I mean. I have this file sitting on the root: /home/xxxx/public_html/constructfiles/filetoinclude.php It needs to be included he /home/xxxx/public_html/SUBDOMAIN/publicfile.php Then, 'filetoinclude.php' needs to include other files that are he /home/xxxx/public_html/SUBDOMAIN/bodyCopy/otherfilestoinclude.php ...but, 'filetoinclude.php' is searching along the root path for '/home/xxxx/public_html/bodyCopy/otherfilestoinclude.php' (which does not exist), and NOT within the SUBDOMAIN for the '/home/xxxx/public_html/SUBDOMAIN/bodyCopy/otherfilestoinclude.php' like I need it to. It appears that PHP will only search along the root path of the included file and NOT the root path of the file in which an include is included. I'm confusing myself now, but I hope someone can help. Thanks, Jet - I have a directory in public WWW. The files throughout the directory have many PHP includes amongst themselves. For example, the file "registration.php" begins with require('../parameters.php'); The directory is complex, like this:
/Public WWW directory/ How would I do that without breaking all the include paths? (I know the solution is probably a one-liner involving __DIR__ ... but I can't seem to code it so it works). Thank you!!
Hi all, How do I get the following paths from the array separately in a foreach loop? level.dat level.dat_old session.lock uid.data If I use Code: [Select] foreach($outer_dir as $key=>$val) [code] then I get a warning because its returning the folder as 'Array'. The files still upload, as well as a single file called Array. Can i just strip these from the foreach? [code] Array ( [data] => Array ( ) [level.dat] => level.dat [level.dat_old] => level.dat_old [players] => Array ( [herghost.dat] => herghost.dat ) [region] => Array ( [r.-1.0.mcr] => r.-1.0.mcr [r.0.0.mcr] => r.0.0.mcr ) [session.lock] => session.lock [uid.dat] => uid.dat ) herghost.dat Many thanks from a confused user I am using the free web host http://www.byethost2.com/ and need help figuring out where and how to make my php files to?! Currently I have the following Config file... Code: [Select] <?php // Build Date: 2011-12-17 1:15pm // Website Environment define('ENVIRONMENT', 'development'); //define('ENVIRONMENT', 'production'); // Web Root (aka Document Root) (**Physical Location) define('WEB_ROOT', ENVIRONMENT === 'development' ? '/Users/user1/Documents/DEV/++htdocs/05_Debbie/' : '/var/www/vhosts/MySite.com/httpdocs/'); // Base URL (**Virtual Location) define('BASE_URL', ENVIRONMENT === 'development' ? 'http://local.debbie/' : 'http://www.MySite.com/'); ?> What am I supposed to use for WEB_ROOT and BASE_URL on this free hosting site?! Currently, to view my test website you go to... http://www.doubledee.byethost2.com/ I suppose that could be "BASE_URL", but for where things are physically stored so I can redefine "WEB_ROOT" I have no clue... Help! Thanks, Debbie I have a form that lets a user upload an image, aswell as another file. I want the image to go into the images directory, and the pdf file to go into the PDF directory once uploaded. The names of the files will then be uploaded to the database. At the moment I can get the image to upload to the database and directory, but the PDF is only uploading the name to the database, it is not going into the PDF directory aswell. I'm not sure if there is a way you can do this, I am trying to use "move_uploaded_file()" to physically move the files but not sure if you can use it twice. here is my code, if you can point anything out or where im going wrong that would be great. <?php include "include/conn.php"; include "include/session.php"; ?> <?php // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif"); if (in_array($file['type'], $valid_types)) return 1; return 0; } function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } //Target path for image $TARGET_PATH = dirname(__FILE__) . "/images/"; //Target path for PDF files $PDF_TARGET_PATH = dirname(_FILE_) . "/PDF/"; // Get POST variables $image = $_FILES['image']; $pdf = $_FILES['pdf']; $date= date("Y-m-d "); $time = date("H:i:s"); $title = $_POST['title']; $title_escape = mysql_escape_string($title); $title_slashes = stripslashes($title_escape); $content = $_POST['content']; $image['name'] = mysql_real_escape_string($image['name']); $pdf['name'] = mysql_real_escape_string($pdf['name']); //image path $TARGET_PATH .= $image['name']; //PDF path $PDF_TARGET_PATH .= $pdf['file_name']; // Make sure all the fields from the form have inputs if ($image['name'] == "" ) { $_SESSION['error'] = "All fields are required"; header("Location: add_media.php"); exit; } // Verify file is an image if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header("Location: add_media.php"); exit; } // move file into the directory and the path name into the database / along with the rest of the form fields if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { if(move_uploaded_file($pdf['tmp_name'], $PDF_TARGET_PATH)) { $sql = "INSERT INTO media_table(title, text, time, date, image, PDF) VALUES ('" . $title_slashes . "','" . $content . "', '" . $time . "', '" . $date . "', '" . $image['name'] . "', '" . $pdf['name'] . "')"; $result = mysql_query($sql) or die (mysql_error()); header("Location: add_media.php"); exit; } else { print "did not upload"; } } else { $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; exit; } ?> First of all, does anyone know of some good documentation to better understand cookies? I've gone through the PHP manual, and can find how to use PHP to work with cookies, but not how cookies really work.
In particular, it is my understanding that if the domain is .mydomain.com, then mydomain.com, www.mydomain.com, or whatEver.mydomain.com, cookies could be set for each, and available for each, right?
If path was /, cookies will be sent for mydomain.com, mydomain.com/bla, and mydomain.com/bla/bla. If path was /bla, cookies will be not be sent for mydomain.com, but will be sent for mydomain.com and mydomain.com/bla/bla.
Also, what would be the impact if Apache rewrote bla.mydomain.com to mydomain.com/bla?
Please feel free to provide any other insight on this topic.
Thank you
Hi guys, Just a quick one - this is more of a bit of a challenge than a problem! I'm pretty good with PHP - I'm definitely not a beginner, but I've come across a problem I've not yet been able to solve satisfactorily. Essentially, I am trying to write a really good, solid OOP library that I can hand out for people to use for CMS-driven websites, and I want to literally just upload some files and have access to some variables... simple enough. But, my snagging point came when I was writing the image library, which handles uploading files and moving them from place to place. These functions as you know usually require an absolute server path - not a relative path and certainly not a URL, so I wanted to place something in my config file that gets the base URL, puts the relative path in one variable (e.g. mysite.com/directory would give /directory) and the server path in another (e.g. mysite.com/directory might give var/www/mysite/www/directory). Now I might just be being foolish and overlooking something, but I've used HTTP_HOST, DOCUMENT_ROOT etc to get this information, but I only want to get the base directory that the application resides in - usually with installed software sure as WordPress you have to specify which directory the files are going to sit in, which I wondered if you could gauge automatically? Any help would be appreciated - I've tried as many clever approaches as I could think of, and the only one I can think of now is setting the variables based on, say, installtion.php since I know the name of the file and where it resides, I can strip out all folders minus the filename, which would give me the root directory, but that seems a little fiddly to me? Someone must have done this before and have a nice clean solution to the problem? I'm at a loss anyway, and I figured it might be a fair challenge to do? Thanks, Luke my directory on my mamp server looks like this; root/website/index.php I also have some files in a folder like this root/website/pages/files.php My include code is this include("functions.php"); When I try to include a file from the 'website' folder from a page in the 'pages' folder. It gives me errors that look like this. Warning: include(functions.php) [function.include]: failed to open stream: No such file or directory in /website/pages/contact.php on line 2 Warning: include() [function.include]: Failed opening 'functions.php' for inclusion (include_path='.:/Applications/MAMP/bin/php5.3/lib/php') in /Applications/MAMP/htdocs/website/pages/contact.php on line 2 That's what it looks like.. I can't get it working. I am in the process of writing a CMS for a friend that is looking to add a classified section to his site. He will be the only one that will ever use it. I got the code to work with one image when he asked me if I could do it so he could post 6 images for each item. I am unable to figure out how to do this. I was told to do this with a while loop. This is the code that I have written so far. <?php //Check to make sure title is filled in. If not redirects to show_add.php if (!$_POST[title]) { header("Location: show_add.php"); exit; } else { //check and see if a session has started session_start(); } //if session has not been properly started redirects back to the administration menu if ($_SESSION[valid] != "yes") { header("Location: admin_menu.php"); exit; } include('includes/connection.php'); //check and see if the type of uploaded file is an image function is_valid_type($file) { $valid_types = array("image/jpg", "image/jpeg", "image/gif", "image/bmp"); if (in_array($file['type'], $valid_types)) return 1; return 0; } //Set Constants $TARGET_PATH = "/home/content/m/i/k/mikedmartiny/html/db_images/"; $title = $_POST['title']; $year = $_POST['year']; $make = $_POST['make']; $model = $_POST['model']; $descript = $_POST['descript']; $image = $_FILES['image']; //Sanitize the inputs $title = mysql_real_escape_string($title); $year = mysql_real_escape_string($year); $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $descript = mysql_real_escape_string($descript); $image['name'] = mysql_real_escape_string($image['name']); //$target_path full string $TARGET_PATH .= $image['name']; //make sure that all fields from form are filled in if ( $title == "" || $year == "" || $make =="" || $model == "" || $descript == "" || $image['name'] == "") { $_SESSION['error'] = "ALL FIELDS ARE REQUIRED!"; header ("Location: show_add.php"); exit; } //check to make sure it has the right file type if (!is_valid_type($image)){ $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header ("Location: show_add.php"); exit; } //check to see if a file with that name exsists if (file_exists($TARGET_PATH)){ $_SESSION['error'] = "A FILE WITH THAT NAME ALL READY EXIST!"; header ("Location: show_add.php"); exit; } //move the image - write path to database while($image <=2) { move_uploaded_file($image['tmp_name'], $TARGET_PATH) } else { // Make sure you chmod the directory to be writeable $_SESSION['error'] = "COULD NOT UPLOAD FILE. CHECK WRITE/REWRITE PERMISSIONS ON THE FILE DIRECTORY!"; header ("Location: show_add.php"); exit; } $sql = "INSERT INTO $table (id, title, year, make, model, descript, image, image_two) VALUES ('', '$_POST[title]', '$_POST[year]', '$_POST[make]', '$_POST[model]', '$_POST[descript]', '" . $image['name'] . "', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); ?> I only have it set up to work with 2 images right now. I thought it would be easier to get it to work properly. Then I could just add in the rest of the info later. Any help would be greatly appreciated. I was under the impression this was a simple thing to do and I'm fairly certain I've done it before, but it isn't working for some reason. Under the root directory of my project I have two subfolders called "inc" and "lib". lib contains third-party scripts for use in my project. The one in question is phpmailer (lib/class.phpmailer.php). Now, in inc I have a file that needs to include PHPMailer. Inside my script in inc I have this: require_once('../lib/class.phpmailer.php'); It errors out saying it can't find it. I thought that was supposed to go down one directory then back up into lib. The file does indeed exist. What am I doing wrong? This seems like a stupidly simple thing... well good moring dear folks - hope you are all right and everythings is fine across the atlantic today i have a question regarding server-paths - and the absolute and relative in a linux-[opensuse 11.4] lampp-system well i just installed something in to my Lampp on openSuse 11.4 while setting up this application - (it is a joomla 1.7.3 ) i wonder how i name the paths public $unicodeslugs = '0'; public $feed_limit = '10'; public $log_path = 'D:\\Xammp\\xampp\\htdocs\\pre1/logs'; public $tmp_path = 'D:\\Xammp\\xampp\\htdocs\\pre1/tmp'; public $lifetime = '15'; public $session_handler = 'database'; what cou you thinks how shoud i name the paths well you see above this was a windows box where the pahts originally were taken from love to hear from you I've been looking everywhere for a solution of this but I can't find one...
Basically what I did was created a class named USER.
public class USER{ private static $USER = array(); public function __construct($U='') { // if $U is not entered (=='') then set $U to MY USER ID ($_COOKIE['user']) // do a mysql query by the ID (ala $U) and store the results to self::$USER } public function ID() { return self::$USER['id']; } }This is the code I am running... I do a user profile page that shows different properties of the USER from the database: USERNAME(),ID(),PHONE(),EMAIL(), etc. etc. // creates an instance of a different user (other than myself) $PROFILE = new USER($ID); // $ID: 26 will retrieve USERNAME: Test // create an instance of user class for myself using the cookie holding my id $ME = new USER($_COOKIE['user']) // $_COOKIE['user']: 01 will retrieve USERNAME: Monster echo($PROFILE->USERNAME()); // displays Monster echo($PROFILE->ID()); // displays 01Any idea what I am doing wrong? I would assume that $PROFILE->USERNAME() would display Test and $ME->USERNAME() would show monster. Is their something I can do in PHP (like some sort of function/config/array etc...) which would make the following process easier (examples appreciated)... I have an .htaccess file where im rewriting urls to seo friendly ones...now in the PHP script is their something I can place for urls are meant to be displayed/linked (like some sort of placeholder) which makes it easier for me to modify the urls within the PHP script, without constantly editing countless php sourcecode to just change the url? Example scenario: Say I had a php file (called submit.php): <?php echo 'Hey! Thanks for submiting the form, <a href="submit.php?form">click here</a> to go back!'; ?> and my rewrite rule for submit.php?form was: /form How would I easily change the url within submit.php without editing submit.php directly? |